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
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
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})\"",
")",
"host",
"=",
"uri",
".",
"host",
"connection",
"=",
"Rightscale",
"::",
"HttpConnection",
".",
"new",
"(",
":logger",
"=>",
"Log",
",",
":exception",
"=>",
"QueryFailed",
")",
"request",
"=",
"Net",
"::",
"HTTP",
"::",
"Get",
".",
"new",
"(",
"uri",
".",
"path",
")",
"request",
"[",
"'Connection'",
"]",
"=",
"keep_alive",
"?",
"'keep-alive'",
":",
"'close'",
"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",
")",
"location",
"=",
"response",
"[",
"'Location'",
"]",
"uri",
"=",
"safe_parse_http_uri",
"(",
"location",
")",
"else",
"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 | train |
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",
"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",
"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 | train |
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 | train |
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",
")",
"if",
"continue?",
"||",
"@shutdown_scheduled",
"block",
".",
"call",
"if",
"block",
"return",
"true",
"end",
"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",
"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 | train |
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 | train |
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",
"update_predecate_for_enum",
"(",
"arel_table",
"[",
"method",
"]",
",",
"op",
",",
"value",
")",
"else",
"update_predecate_for_rest",
"(",
"arel_table",
"[",
"method",
"]",
",",
"op",
",",
"value",
")",
"end",
"end",
"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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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?",
"report_success",
"return",
"true",
"end",
"@audit",
".",
"create_new_section",
"(",
"'Retrieving credentials'",
")",
"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 | train |
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",
"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",
"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",
"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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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",
"repo_dir",
"=",
"@scraper",
".",
"repo_dir",
"(",
"repo",
")",
"if",
"File",
".",
"directory?",
"(",
"repo_dir",
")",
"if",
"callback",
"callback",
".",
"call",
"(",
":commit",
",",
":initialize",
",",
"\"Skipping checkout -- repository already exists in #{repo_dir}\"",
",",
"nil",
")",
"end",
"@registered_checkouts",
"[",
"repo_sha",
"]",
"=",
"repo_dir",
"else",
"success",
"=",
"false",
"begin",
"success",
"=",
"@scraper",
".",
"scrape",
"(",
"repo",
",",
"&",
"callback",
")",
"ensure",
"if",
"success",
"@registered_checkouts",
"[",
"repo_sha",
"]",
"=",
"repo_dir",
"else",
"FileUtils",
".",
"rm_rf",
"(",
"repo_dir",
")",
"unless",
"success",
"@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 | train |
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",
")",
"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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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",
")",
"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 | train |
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 | train |
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",
")",
"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 | train |
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",
"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 | train |
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",
")",
"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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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",
")",
"path",
"=",
"File",
".",
"normalize_path",
"(",
"File",
".",
"join",
"(",
"AgentConfig",
".",
"cache_dir",
",",
"'right_scripts_content'",
",",
"\"rs_attach\"",
"+",
"script",
".",
"object_id",
".",
"to_s",
")",
")",
"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 | train |
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 | train |
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 | train |
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 | train |
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",
"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",
"if",
"text_indent",
"&&",
"indent",
"<",
"text_indent",
"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",
"/",
"if",
"@line",
"=~",
"/",
"\\A",
"\\\\",
"\\Z",
"/",
"@line",
"=",
"$`",
"+",
"$1",
"end",
"end",
"@stacks",
".",
"last",
"<<",
"[",
":newline",
"]",
"if",
"!",
"first_line",
"&&",
"!",
"embedded",
"@stacks",
".",
"last",
"<<",
"[",
":slim",
",",
":interpolate",
",",
"(",
"text_indent",
"?",
"\"\\n\"",
":",
"''",
")",
"+",
"@line",
"]",
"<<",
"[",
":newline",
"]",
"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 | train |
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",
"@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 | train |
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",
"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 | train |
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",
")",
"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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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\"",
"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 | train |
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",
")",
"return",
"if",
"InstanceState",
".",
"value",
"==",
"'stranded'",
"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",
"||=",
"[",
"]",
"begin",
"mappings",
"=",
"merge_planned_volume_mappings",
"(",
"last_mappings",
",",
"res",
")",
"InstanceState",
".",
"planned_volume_state",
".",
"mappings",
"=",
"mappings",
"if",
"mappings",
".",
"empty?",
"@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",
"mappings",
".",
"each",
"do",
"|",
"mapping",
"|",
"if",
"is_unmanaged_attached_volume?",
"(",
"mapping",
")",
"detach_planned_volume",
"(",
"mapping",
")",
"do",
"detachable_volume_count",
"-=",
"1",
"if",
"0",
"==",
"detachable_volume_count",
"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",
")",
"}",
"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'",
"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",
"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 | train |
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",
"|",
"mapping",
"[",
":management_status",
"]",
"=",
"'detached'",
"mapping",
"[",
":attempts",
"]",
"=",
"nil",
"yield",
"if",
"block_given?",
"end",
"req",
".",
"errback",
"do",
"|",
"res",
"|",
"unless",
"InstanceState",
".",
"value",
"==",
"'stranded'",
"Log",
".",
"error",
"(",
"\"Failed to detach volume #{mapping[:volume_id]} (#{res})\"",
")",
"mapping",
"[",
":attempts",
"]",
"||=",
"0",
"mapping",
"[",
":attempts",
"]",
"+=",
"1",
"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 | train |
rightscale/right_link | lib/instance/volume_management.rb | RightScale.VolumeManagementHelper.attach_planned_volume | def attach_planned_volume(mapping)
# preserve the initial list of disks/volumes before attachment for comparison later.
vm = RightScale::Platform.volume_manager
InstanceState.planned_volume_state.disks ||= vm.disks
InstanceState.planned_volume_state.volumes ||= vm.volumes
# attach.
payload = {:agent_identity => @agent_identity, :volume_id => mapping[:volume_id], :device_name => mapping[:device_name]}
Log.info("Attaching volume #{mapping[:volume_id]}.")
req = RetryableRequest.new("/storage_valet/attach_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] = 'attached'
mapping[:attempts] = nil
yield if block_given?
end
req.errback do |res|
# volume could already be attaching 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 attach 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 attaching volume #{mapping[:volume_id]} with error: #{res}")
else
yield if block_given?
end
end
req.run
end | ruby | def attach_planned_volume(mapping)
# preserve the initial list of disks/volumes before attachment for comparison later.
vm = RightScale::Platform.volume_manager
InstanceState.planned_volume_state.disks ||= vm.disks
InstanceState.planned_volume_state.volumes ||= vm.volumes
# attach.
payload = {:agent_identity => @agent_identity, :volume_id => mapping[:volume_id], :device_name => mapping[:device_name]}
Log.info("Attaching volume #{mapping[:volume_id]}.")
req = RetryableRequest.new("/storage_valet/attach_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] = 'attached'
mapping[:attempts] = nil
yield if block_given?
end
req.errback do |res|
# volume could already be attaching 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 attach 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 attaching volume #{mapping[:volume_id]} with error: #{res}")
else
yield if block_given?
end
end
req.run
end | [
"def",
"attach_planned_volume",
"(",
"mapping",
")",
"vm",
"=",
"RightScale",
"::",
"Platform",
".",
"volume_manager",
"InstanceState",
".",
"planned_volume_state",
".",
"disks",
"||=",
"vm",
".",
"disks",
"InstanceState",
".",
"planned_volume_state",
".",
"volumes",
"||=",
"vm",
".",
"volumes",
"payload",
"=",
"{",
":agent_identity",
"=>",
"@agent_identity",
",",
":volume_id",
"=>",
"mapping",
"[",
":volume_id",
"]",
",",
":device_name",
"=>",
"mapping",
"[",
":device_name",
"]",
"}",
"Log",
".",
"info",
"(",
"\"Attaching volume #{mapping[:volume_id]}.\"",
")",
"req",
"=",
"RetryableRequest",
".",
"new",
"(",
"\"/storage_valet/attach_volume\"",
",",
"payload",
",",
":retry_delay",
"=>",
"VolumeManagement",
"::",
"VOLUME_RETRY_SECONDS",
")",
"req",
".",
"callback",
"do",
"|",
"res",
"|",
"mapping",
"[",
":management_status",
"]",
"=",
"'attached'",
"mapping",
"[",
":attempts",
"]",
"=",
"nil",
"yield",
"if",
"block_given?",
"end",
"req",
".",
"errback",
"do",
"|",
"res",
"|",
"Log",
".",
"error",
"(",
"\"Failed to attach volume #{mapping[:volume_id]} (#{res})\"",
")",
"mapping",
"[",
":attempts",
"]",
"||=",
"0",
"mapping",
"[",
":attempts",
"]",
"+=",
"1",
"if",
"mapping",
"[",
":attempts",
"]",
">=",
"VolumeManagement",
"::",
"MAX_VOLUME_ATTEMPTS",
"strand",
"(",
"\"Exceeded maximum of #{VolumeManagement::MAX_VOLUME_ATTEMPTS} attempts attaching volume #{mapping[:volume_id]} with error: #{res}\"",
")",
"else",
"yield",
"if",
"block_given?",
"end",
"end",
"req",
".",
"run",
"end"
] | Attaches the planned volume given by its mapping.
=== Parameters
mapping(Hash):: details of planned volume | [
"Attaches",
"the",
"planned",
"volume",
"given",
"by",
"its",
"mapping",
"."
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/volume_management.rb#L180-L214 | train |
rightscale/right_link | lib/instance/volume_management.rb | RightScale.VolumeManagementHelper.manage_volume_device_assignment | def manage_volume_device_assignment(mapping)
# only managed volumes should be in an attached state ready for assignment.
unless 'attached' == mapping[:management_status]
raise VolumeManagement::UnexpectedState.new("The volume #{mapping[:volume_id]} was in an unexpected managed state: #{mapping.inspect}")
end
# check for changes in disks.
last_disks = InstanceState.planned_volume_state.disks
last_volumes = InstanceState.planned_volume_state.volumes
vm = RightScale::Platform.volume_manager
current_disks = vm.disks
current_volumes = vm.volumes
# correctly managing device assignment requires expecting precise changes
# to disks and volumes. any deviation from this requires a retry.
succeeded = false
if new_disk = find_distinct_item(current_disks, last_disks, :index)
# if the new disk as no partitions, then we will format and assign device.
if vm.partitions(new_disk[:index]).empty?
# FIX: ignore multiple mount points for simplicity and only only create
# a single primary partition for the first mount point.
# if we had the UI for it, then the user would probably specify
# partition sizes as a percentage of disk size and associate those with
# mount points formatted optionally specifying file system, label, etc.
@audit.append_info("Creating primary partition and formatting \"#{mapping[:mount_points].first}\".")
vm.format_disk(new_disk[:index], mapping[:mount_points].first)
succeeded = true
else
# FIX: ignoring multiple existing partitiions on a disk (which should
# result in multiple new volumes appearing when the disk comes online)
# for simplicity until we have a UI supporting multiple mount points.
@audit.append_info("Preparing \"#{mapping[:mount_points].first}\" for use.")
new_volume = find_distinct_item(current_volumes, last_volumes, :device)
unless new_volume
vm.online_disk(new_disk[:index])
current_volumes = vm.volumes
new_volume = find_distinct_item(current_volumes, last_volumes, :device)
end
if new_volume
# prefer selection by existing device because it is more reliable in Windows 2003 case.
unless new_volume[:device] && (0 == new_volume[:device].casecmp(mapping[:mount_points].first))
device_or_index_to_select = new_volume[:device] || new_volume[:index]
vm.assign_device(device_or_index_to_select, mapping[:mount_points].first)
end
succeeded = true
end
end
end
# retry only if still not assigned.
if succeeded
# volume is (finally!) assigned to correct device name.
mapping[:management_status] = 'assigned'
mapping[:attempts] = nil
# reset cached volumes/disks for next attempt (to attach), if any.
InstanceState.planned_volume_state.disks = nil
InstanceState.planned_volume_state.volumes = nil
# continue.
yield if block_given?
else
mapping[:attempts] ||= 0
mapping[:attempts] += 1
if mapping[:attempts] >= VolumeManagement::MAX_VOLUME_ATTEMPTS
strand("Exceeded maximum of #{VolumeManagement::MAX_VOLUME_ATTEMPTS} attempts waiting for volume #{mapping[:volume_id]} to be in a managable state.")
else
yield if block_given?
end
end
rescue Exception => e
strand(e)
end | ruby | def manage_volume_device_assignment(mapping)
# only managed volumes should be in an attached state ready for assignment.
unless 'attached' == mapping[:management_status]
raise VolumeManagement::UnexpectedState.new("The volume #{mapping[:volume_id]} was in an unexpected managed state: #{mapping.inspect}")
end
# check for changes in disks.
last_disks = InstanceState.planned_volume_state.disks
last_volumes = InstanceState.planned_volume_state.volumes
vm = RightScale::Platform.volume_manager
current_disks = vm.disks
current_volumes = vm.volumes
# correctly managing device assignment requires expecting precise changes
# to disks and volumes. any deviation from this requires a retry.
succeeded = false
if new_disk = find_distinct_item(current_disks, last_disks, :index)
# if the new disk as no partitions, then we will format and assign device.
if vm.partitions(new_disk[:index]).empty?
# FIX: ignore multiple mount points for simplicity and only only create
# a single primary partition for the first mount point.
# if we had the UI for it, then the user would probably specify
# partition sizes as a percentage of disk size and associate those with
# mount points formatted optionally specifying file system, label, etc.
@audit.append_info("Creating primary partition and formatting \"#{mapping[:mount_points].first}\".")
vm.format_disk(new_disk[:index], mapping[:mount_points].first)
succeeded = true
else
# FIX: ignoring multiple existing partitiions on a disk (which should
# result in multiple new volumes appearing when the disk comes online)
# for simplicity until we have a UI supporting multiple mount points.
@audit.append_info("Preparing \"#{mapping[:mount_points].first}\" for use.")
new_volume = find_distinct_item(current_volumes, last_volumes, :device)
unless new_volume
vm.online_disk(new_disk[:index])
current_volumes = vm.volumes
new_volume = find_distinct_item(current_volumes, last_volumes, :device)
end
if new_volume
# prefer selection by existing device because it is more reliable in Windows 2003 case.
unless new_volume[:device] && (0 == new_volume[:device].casecmp(mapping[:mount_points].first))
device_or_index_to_select = new_volume[:device] || new_volume[:index]
vm.assign_device(device_or_index_to_select, mapping[:mount_points].first)
end
succeeded = true
end
end
end
# retry only if still not assigned.
if succeeded
# volume is (finally!) assigned to correct device name.
mapping[:management_status] = 'assigned'
mapping[:attempts] = nil
# reset cached volumes/disks for next attempt (to attach), if any.
InstanceState.planned_volume_state.disks = nil
InstanceState.planned_volume_state.volumes = nil
# continue.
yield if block_given?
else
mapping[:attempts] ||= 0
mapping[:attempts] += 1
if mapping[:attempts] >= VolumeManagement::MAX_VOLUME_ATTEMPTS
strand("Exceeded maximum of #{VolumeManagement::MAX_VOLUME_ATTEMPTS} attempts waiting for volume #{mapping[:volume_id]} to be in a managable state.")
else
yield if block_given?
end
end
rescue Exception => e
strand(e)
end | [
"def",
"manage_volume_device_assignment",
"(",
"mapping",
")",
"unless",
"'attached'",
"==",
"mapping",
"[",
":management_status",
"]",
"raise",
"VolumeManagement",
"::",
"UnexpectedState",
".",
"new",
"(",
"\"The volume #{mapping[:volume_id]} was in an unexpected managed state: #{mapping.inspect}\"",
")",
"end",
"last_disks",
"=",
"InstanceState",
".",
"planned_volume_state",
".",
"disks",
"last_volumes",
"=",
"InstanceState",
".",
"planned_volume_state",
".",
"volumes",
"vm",
"=",
"RightScale",
"::",
"Platform",
".",
"volume_manager",
"current_disks",
"=",
"vm",
".",
"disks",
"current_volumes",
"=",
"vm",
".",
"volumes",
"succeeded",
"=",
"false",
"if",
"new_disk",
"=",
"find_distinct_item",
"(",
"current_disks",
",",
"last_disks",
",",
":index",
")",
"if",
"vm",
".",
"partitions",
"(",
"new_disk",
"[",
":index",
"]",
")",
".",
"empty?",
"@audit",
".",
"append_info",
"(",
"\"Creating primary partition and formatting \\\"#{mapping[:mount_points].first}\\\".\"",
")",
"vm",
".",
"format_disk",
"(",
"new_disk",
"[",
":index",
"]",
",",
"mapping",
"[",
":mount_points",
"]",
".",
"first",
")",
"succeeded",
"=",
"true",
"else",
"@audit",
".",
"append_info",
"(",
"\"Preparing \\\"#{mapping[:mount_points].first}\\\" for use.\"",
")",
"new_volume",
"=",
"find_distinct_item",
"(",
"current_volumes",
",",
"last_volumes",
",",
":device",
")",
"unless",
"new_volume",
"vm",
".",
"online_disk",
"(",
"new_disk",
"[",
":index",
"]",
")",
"current_volumes",
"=",
"vm",
".",
"volumes",
"new_volume",
"=",
"find_distinct_item",
"(",
"current_volumes",
",",
"last_volumes",
",",
":device",
")",
"end",
"if",
"new_volume",
"unless",
"new_volume",
"[",
":device",
"]",
"&&",
"(",
"0",
"==",
"new_volume",
"[",
":device",
"]",
".",
"casecmp",
"(",
"mapping",
"[",
":mount_points",
"]",
".",
"first",
")",
")",
"device_or_index_to_select",
"=",
"new_volume",
"[",
":device",
"]",
"||",
"new_volume",
"[",
":index",
"]",
"vm",
".",
"assign_device",
"(",
"device_or_index_to_select",
",",
"mapping",
"[",
":mount_points",
"]",
".",
"first",
")",
"end",
"succeeded",
"=",
"true",
"end",
"end",
"end",
"if",
"succeeded",
"mapping",
"[",
":management_status",
"]",
"=",
"'assigned'",
"mapping",
"[",
":attempts",
"]",
"=",
"nil",
"InstanceState",
".",
"planned_volume_state",
".",
"disks",
"=",
"nil",
"InstanceState",
".",
"planned_volume_state",
".",
"volumes",
"=",
"nil",
"yield",
"if",
"block_given?",
"else",
"mapping",
"[",
":attempts",
"]",
"||=",
"0",
"mapping",
"[",
":attempts",
"]",
"+=",
"1",
"if",
"mapping",
"[",
":attempts",
"]",
">=",
"VolumeManagement",
"::",
"MAX_VOLUME_ATTEMPTS",
"strand",
"(",
"\"Exceeded maximum of #{VolumeManagement::MAX_VOLUME_ATTEMPTS} attempts waiting for volume #{mapping[:volume_id]} to be in a managable state.\"",
")",
"else",
"yield",
"if",
"block_given?",
"end",
"end",
"rescue",
"Exception",
"=>",
"e",
"strand",
"(",
"e",
")",
"end"
] | Manages device assignment for volumes with considerations for formatting
blank attached volumes.
=== Parameters
mapping(Hash):: details of planned volume | [
"Manages",
"device",
"assignment",
"for",
"volumes",
"with",
"considerations",
"for",
"formatting",
"blank",
"attached",
"volumes",
"."
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/volume_management.rb#L221-L294 | train |
rightscale/right_link | lib/instance/volume_management.rb | RightScale.VolumeManagementHelper.merge_planned_volume_mappings | def merge_planned_volume_mappings(last_mappings, current_planned_volumes)
results = []
vm = RightScale::Platform.volume_manager
# merge latest mappings with last mappings, if any.
current_planned_volumes.each do |planned_volume|
raise VolumeManagement::InvalidResponse.new("Reponse for volume mapping was invalid: #{mapping.inspect}") unless planned_volume.is_valid?
if mount_point = planned_volume.mount_points.find { |mount_point| false == vm.is_attachable_volume_path?(mount_point) }
raise VolumeManagement::UnsupportedMountPoint.new("Cannot mount a volume using \"#{mount_point}\".")
end
mapping = {:volume_id => planned_volume.volume_id,
:device_name => planned_volume.device_name,
:volume_status => planned_volume.volume_status,
:mount_points => planned_volume.mount_points.dup}
if last_mapping = last_mappings.find { |last_mapping| last_mapping[:volume_id] == mapping[:volume_id] }
# if device name or mount point(s) have changed then we must start
# over (we can't prevent the user from doing this).
if last_mapping[:device_name] != mapping[:device_name] || last_mapping[:mount_points] != mapping[:mount_points]
last_mapping[:device_name] = mapping[:device_name]
last_mapping[:mount_points] = mapping[:mount_points].dup
last_mapping[:management_status] = nil
end
last_mapping[:volume_status] = mapping[:volume_status]
mapping = last_mapping
end
results << mapping
end
# preserve any last mappings which do not appear in current mappings by
# assuming that they are 'detached' to support a limitation of the initial
# query implementation.
last_mappings.each do |last_mapping|
mapping = results.find { |mapping| mapping[:volume_id] == last_mapping[:volume_id] }
unless mapping
last_mapping[:volume_status] = 'detached'
results << last_mapping
end
end
return results
end | ruby | def merge_planned_volume_mappings(last_mappings, current_planned_volumes)
results = []
vm = RightScale::Platform.volume_manager
# merge latest mappings with last mappings, if any.
current_planned_volumes.each do |planned_volume|
raise VolumeManagement::InvalidResponse.new("Reponse for volume mapping was invalid: #{mapping.inspect}") unless planned_volume.is_valid?
if mount_point = planned_volume.mount_points.find { |mount_point| false == vm.is_attachable_volume_path?(mount_point) }
raise VolumeManagement::UnsupportedMountPoint.new("Cannot mount a volume using \"#{mount_point}\".")
end
mapping = {:volume_id => planned_volume.volume_id,
:device_name => planned_volume.device_name,
:volume_status => planned_volume.volume_status,
:mount_points => planned_volume.mount_points.dup}
if last_mapping = last_mappings.find { |last_mapping| last_mapping[:volume_id] == mapping[:volume_id] }
# if device name or mount point(s) have changed then we must start
# over (we can't prevent the user from doing this).
if last_mapping[:device_name] != mapping[:device_name] || last_mapping[:mount_points] != mapping[:mount_points]
last_mapping[:device_name] = mapping[:device_name]
last_mapping[:mount_points] = mapping[:mount_points].dup
last_mapping[:management_status] = nil
end
last_mapping[:volume_status] = mapping[:volume_status]
mapping = last_mapping
end
results << mapping
end
# preserve any last mappings which do not appear in current mappings by
# assuming that they are 'detached' to support a limitation of the initial
# query implementation.
last_mappings.each do |last_mapping|
mapping = results.find { |mapping| mapping[:volume_id] == last_mapping[:volume_id] }
unless mapping
last_mapping[:volume_status] = 'detached'
results << last_mapping
end
end
return results
end | [
"def",
"merge_planned_volume_mappings",
"(",
"last_mappings",
",",
"current_planned_volumes",
")",
"results",
"=",
"[",
"]",
"vm",
"=",
"RightScale",
"::",
"Platform",
".",
"volume_manager",
"current_planned_volumes",
".",
"each",
"do",
"|",
"planned_volume",
"|",
"raise",
"VolumeManagement",
"::",
"InvalidResponse",
".",
"new",
"(",
"\"Reponse for volume mapping was invalid: #{mapping.inspect}\"",
")",
"unless",
"planned_volume",
".",
"is_valid?",
"if",
"mount_point",
"=",
"planned_volume",
".",
"mount_points",
".",
"find",
"{",
"|",
"mount_point",
"|",
"false",
"==",
"vm",
".",
"is_attachable_volume_path?",
"(",
"mount_point",
")",
"}",
"raise",
"VolumeManagement",
"::",
"UnsupportedMountPoint",
".",
"new",
"(",
"\"Cannot mount a volume using \\\"#{mount_point}\\\".\"",
")",
"end",
"mapping",
"=",
"{",
":volume_id",
"=>",
"planned_volume",
".",
"volume_id",
",",
":device_name",
"=>",
"planned_volume",
".",
"device_name",
",",
":volume_status",
"=>",
"planned_volume",
".",
"volume_status",
",",
":mount_points",
"=>",
"planned_volume",
".",
"mount_points",
".",
"dup",
"}",
"if",
"last_mapping",
"=",
"last_mappings",
".",
"find",
"{",
"|",
"last_mapping",
"|",
"last_mapping",
"[",
":volume_id",
"]",
"==",
"mapping",
"[",
":volume_id",
"]",
"}",
"if",
"last_mapping",
"[",
":device_name",
"]",
"!=",
"mapping",
"[",
":device_name",
"]",
"||",
"last_mapping",
"[",
":mount_points",
"]",
"!=",
"mapping",
"[",
":mount_points",
"]",
"last_mapping",
"[",
":device_name",
"]",
"=",
"mapping",
"[",
":device_name",
"]",
"last_mapping",
"[",
":mount_points",
"]",
"=",
"mapping",
"[",
":mount_points",
"]",
".",
"dup",
"last_mapping",
"[",
":management_status",
"]",
"=",
"nil",
"end",
"last_mapping",
"[",
":volume_status",
"]",
"=",
"mapping",
"[",
":volume_status",
"]",
"mapping",
"=",
"last_mapping",
"end",
"results",
"<<",
"mapping",
"end",
"last_mappings",
".",
"each",
"do",
"|",
"last_mapping",
"|",
"mapping",
"=",
"results",
".",
"find",
"{",
"|",
"mapping",
"|",
"mapping",
"[",
":volume_id",
"]",
"==",
"last_mapping",
"[",
":volume_id",
"]",
"}",
"unless",
"mapping",
"last_mapping",
"[",
":volume_status",
"]",
"=",
"'detached'",
"results",
"<<",
"last_mapping",
"end",
"end",
"return",
"results",
"end"
] | Merges mappings from query with any last known mappings which may have a
locally persisted state which needs to be evaluated.
=== Parameters
last_mappings(Array):: previously merged mappings or empty
current_mappings(Array):: current unmerged mappings or empty
=== Returns
results(Array):: array of hashes representing merged mappings | [
"Merges",
"mappings",
"from",
"query",
"with",
"any",
"last",
"known",
"mappings",
"which",
"may",
"have",
"a",
"locally",
"persisted",
"state",
"which",
"needs",
"to",
"be",
"evaluated",
"."
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/volume_management.rb#L406-L447 | train |
rightscale/right_link | lib/instance/login_manager.rb | RightScale.LoginManager.supported_by_platform? | def supported_by_platform?
right_platform = RightScale::Platform.linux?
# avoid calling user_exists? on unsupported platform(s)
right_platform && LoginUserManager.user_exists?('rightscale') && FeatureConfigManager.feature_enabled?('managed_login_enable')
end | ruby | def supported_by_platform?
right_platform = RightScale::Platform.linux?
# avoid calling user_exists? on unsupported platform(s)
right_platform && LoginUserManager.user_exists?('rightscale') && FeatureConfigManager.feature_enabled?('managed_login_enable')
end | [
"def",
"supported_by_platform?",
"right_platform",
"=",
"RightScale",
"::",
"Platform",
".",
"linux?",
"right_platform",
"&&",
"LoginUserManager",
".",
"user_exists?",
"(",
"'rightscale'",
")",
"&&",
"FeatureConfigManager",
".",
"feature_enabled?",
"(",
"'managed_login_enable'",
")",
"end"
] | Can the login manager function on this platform?
== Returns:
@return [TrueClass] if LoginManager works on this platform
@return [FalseClass] if LoginManager does not work on this platform | [
"Can",
"the",
"login",
"manager",
"function",
"on",
"this",
"platform?"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/login_manager.rb#L51-L55 | train |
rightscale/right_link | lib/instance/login_manager.rb | RightScale.LoginManager.update_policy | def update_policy(new_policy, agent_identity)
return false unless supported_by_platform?
update_users(new_policy.users, agent_identity, new_policy) do |audit_content|
yield audit_content if block_given?
end
true
end | ruby | def update_policy(new_policy, agent_identity)
return false unless supported_by_platform?
update_users(new_policy.users, agent_identity, new_policy) do |audit_content|
yield audit_content if block_given?
end
true
end | [
"def",
"update_policy",
"(",
"new_policy",
",",
"agent_identity",
")",
"return",
"false",
"unless",
"supported_by_platform?",
"update_users",
"(",
"new_policy",
".",
"users",
",",
"agent_identity",
",",
"new_policy",
")",
"do",
"|",
"audit_content",
"|",
"yield",
"audit_content",
"if",
"block_given?",
"end",
"true",
"end"
] | Enact the login policy specified in new_policy for this system. The policy becomes
effective immediately and controls which public keys are trusted for SSH access to
the superuser account.
== Parameters:
@param [RightScale::LoginPolicy] New login policy
@param [String] Serialized instance agent identity
== Yields:
@yield [String] audit content yielded to the block provided
== Returns:
@return [TrueClass] if supported by given platform
@return [FalseClass] if not supported by given platform | [
"Enact",
"the",
"login",
"policy",
"specified",
"in",
"new_policy",
"for",
"this",
"system",
".",
"The",
"policy",
"becomes",
"effective",
"immediately",
"and",
"controls",
"which",
"public",
"keys",
"are",
"trusted",
"for",
"SSH",
"access",
"to",
"the",
"superuser",
"account",
"."
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/login_manager.rb#L72-L80 | train |
rightscale/right_link | lib/instance/login_manager.rb | RightScale.LoginManager.get_key_prefix | def get_key_prefix(username, email, uuid, superuser, profile_data = nil)
if profile_data
profile = " --profile #{Shellwords.escape(profile_data).gsub('"', '\\"')}"
else
profile = ""
end
superuser = superuser ? " --superuser" : ""
%Q{command="rs_thunk --username #{username} --uuid #{uuid}#{superuser} --email #{email}#{profile}" }
end | ruby | def get_key_prefix(username, email, uuid, superuser, profile_data = nil)
if profile_data
profile = " --profile #{Shellwords.escape(profile_data).gsub('"', '\\"')}"
else
profile = ""
end
superuser = superuser ? " --superuser" : ""
%Q{command="rs_thunk --username #{username} --uuid #{uuid}#{superuser} --email #{email}#{profile}" }
end | [
"def",
"get_key_prefix",
"(",
"username",
",",
"email",
",",
"uuid",
",",
"superuser",
",",
"profile_data",
"=",
"nil",
")",
"if",
"profile_data",
"profile",
"=",
"\" --profile #{Shellwords.escape(profile_data).gsub('\"', '\\\\\"')}\"",
"else",
"profile",
"=",
"\"\"",
"end",
"superuser",
"=",
"superuser",
"?",
"\" --superuser\"",
":",
"\"\"",
"%Q{command=\"rs_thunk --username #{username} --uuid #{uuid}#{superuser} --email #{email}#{profile}\" }",
"end"
] | Returns prefix command for public key record
== Parameters:
@param [String] account's username
@param [String] account's email address
@param [String] account's uuid
@param [Boolean] designates whether the account has superuser privileges
@param [String] optional profile_data to be included
== Returns:
@return [String] command string | [
"Returns",
"prefix",
"command",
"for",
"public",
"key",
"record"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/login_manager.rb#L94-L104 | train |
rightscale/right_link | lib/instance/login_manager.rb | RightScale.LoginManager.get_ssh_host_keys | def get_ssh_host_keys()
# Try to read the sshd_config file first
keys = File.readlines(
File.join(RightScale::Platform.filesystem.ssh_cfg_dir, 'sshd_config')).map do |l|
key = nil
/^\s*HostKey\s+([^ ].*)/.match(l) { |m| key = m.captures[0] }
key
end.compact
# If the config file was empty, try these defaults
keys = keys.empty? ? SSH_DEFAULT_KEYS : keys
# Assume the public keys are just the public keys with '.pub' extended and
# read in each existing key.
keys.map { |k| k="#{k}.pub"; File.exists?(k) ? File.read(k) : nil }.compact
end | ruby | def get_ssh_host_keys()
# Try to read the sshd_config file first
keys = File.readlines(
File.join(RightScale::Platform.filesystem.ssh_cfg_dir, 'sshd_config')).map do |l|
key = nil
/^\s*HostKey\s+([^ ].*)/.match(l) { |m| key = m.captures[0] }
key
end.compact
# If the config file was empty, try these defaults
keys = keys.empty? ? SSH_DEFAULT_KEYS : keys
# Assume the public keys are just the public keys with '.pub' extended and
# read in each existing key.
keys.map { |k| k="#{k}.pub"; File.exists?(k) ? File.read(k) : nil }.compact
end | [
"def",
"get_ssh_host_keys",
"(",
")",
"keys",
"=",
"File",
".",
"readlines",
"(",
"File",
".",
"join",
"(",
"RightScale",
"::",
"Platform",
".",
"filesystem",
".",
"ssh_cfg_dir",
",",
"'sshd_config'",
")",
")",
".",
"map",
"do",
"|",
"l",
"|",
"key",
"=",
"nil",
"/",
"\\s",
"\\s",
"/",
".",
"match",
"(",
"l",
")",
"{",
"|",
"m",
"|",
"key",
"=",
"m",
".",
"captures",
"[",
"0",
"]",
"}",
"key",
"end",
".",
"compact",
"keys",
"=",
"keys",
".",
"empty?",
"?",
"SSH_DEFAULT_KEYS",
":",
"keys",
"keys",
".",
"map",
"{",
"|",
"k",
"|",
"k",
"=",
"\"#{k}.pub\"",
";",
"File",
".",
"exists?",
"(",
"k",
")",
"?",
"File",
".",
"read",
"(",
"k",
")",
":",
"nil",
"}",
".",
"compact",
"end"
] | Returns current SSH host keys
== Returns:
@return [Array<String>] Base64 encoded SSH public keys | [
"Returns",
"current",
"SSH",
"host",
"keys"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/login_manager.rb#L110-L125 | train |
rightscale/right_link | lib/instance/login_manager.rb | RightScale.LoginManager.update_users | def update_users(users, agent_identity, new_policy)
# Create cache of public keys from stored instance state
# but there won't be any on initial launch
public_keys_cache = {}
if old_policy = InstanceState.login_policy
public_keys_cache = old_policy.users.inject({}) do |keys, user|
user.public_key_fingerprints ||= user.public_keys.map { |key| fingerprint(key, user.username) }
user.public_keys.zip(user.public_key_fingerprints).each { |(k, f)| keys[f] = k if f }
keys
end
end
# See if there are any missing keys and if so, send a request to retrieve them
# Then make one more pass to populate any missing keys and reject any that are still not populated
unless (missing = populate_public_keys(users, public_keys_cache)).empty?
payload = {:agent_identity => agent_identity, :public_key_fingerprints => missing.map { |(u, f)| f }}
request = RightScale::RetryableRequest.new("/key_server/retrieve_public_keys", payload)
request.callback do |public_keys|
if public_keys
missing = populate_public_keys(users, public_keys, remove_if_missing = true)
finalize_policy(new_policy, agent_identity, users, missing.map { |(u, f)| u }.uniq) do |audit_content|
yield audit_content
end
end
end
request.errback do |error|
Log.error("Failed to retrieve public keys for users #{missing.map { |(u, f)| u.username }.uniq.inspect} (#{error})")
missing = populate_public_keys(users, {}, remove_if_missing = true)
finalize_policy(new_policy, agent_identity, users, missing.map { |(u, f)| u }.uniq) do |audit_content|
yield audit_content
end
end
request.run
else
finalize_policy(new_policy, agent_identity, users, missing.map { |(u, f)| u }.uniq) do |audit_content|
yield audit_content
end
end
true
end | ruby | def update_users(users, agent_identity, new_policy)
# Create cache of public keys from stored instance state
# but there won't be any on initial launch
public_keys_cache = {}
if old_policy = InstanceState.login_policy
public_keys_cache = old_policy.users.inject({}) do |keys, user|
user.public_key_fingerprints ||= user.public_keys.map { |key| fingerprint(key, user.username) }
user.public_keys.zip(user.public_key_fingerprints).each { |(k, f)| keys[f] = k if f }
keys
end
end
# See if there are any missing keys and if so, send a request to retrieve them
# Then make one more pass to populate any missing keys and reject any that are still not populated
unless (missing = populate_public_keys(users, public_keys_cache)).empty?
payload = {:agent_identity => agent_identity, :public_key_fingerprints => missing.map { |(u, f)| f }}
request = RightScale::RetryableRequest.new("/key_server/retrieve_public_keys", payload)
request.callback do |public_keys|
if public_keys
missing = populate_public_keys(users, public_keys, remove_if_missing = true)
finalize_policy(new_policy, agent_identity, users, missing.map { |(u, f)| u }.uniq) do |audit_content|
yield audit_content
end
end
end
request.errback do |error|
Log.error("Failed to retrieve public keys for users #{missing.map { |(u, f)| u.username }.uniq.inspect} (#{error})")
missing = populate_public_keys(users, {}, remove_if_missing = true)
finalize_policy(new_policy, agent_identity, users, missing.map { |(u, f)| u }.uniq) do |audit_content|
yield audit_content
end
end
request.run
else
finalize_policy(new_policy, agent_identity, users, missing.map { |(u, f)| u }.uniq) do |audit_content|
yield audit_content
end
end
true
end | [
"def",
"update_users",
"(",
"users",
",",
"agent_identity",
",",
"new_policy",
")",
"public_keys_cache",
"=",
"{",
"}",
"if",
"old_policy",
"=",
"InstanceState",
".",
"login_policy",
"public_keys_cache",
"=",
"old_policy",
".",
"users",
".",
"inject",
"(",
"{",
"}",
")",
"do",
"|",
"keys",
",",
"user",
"|",
"user",
".",
"public_key_fingerprints",
"||=",
"user",
".",
"public_keys",
".",
"map",
"{",
"|",
"key",
"|",
"fingerprint",
"(",
"key",
",",
"user",
".",
"username",
")",
"}",
"user",
".",
"public_keys",
".",
"zip",
"(",
"user",
".",
"public_key_fingerprints",
")",
".",
"each",
"{",
"|",
"(",
"k",
",",
"f",
")",
"|",
"keys",
"[",
"f",
"]",
"=",
"k",
"if",
"f",
"}",
"keys",
"end",
"end",
"unless",
"(",
"missing",
"=",
"populate_public_keys",
"(",
"users",
",",
"public_keys_cache",
")",
")",
".",
"empty?",
"payload",
"=",
"{",
":agent_identity",
"=>",
"agent_identity",
",",
":public_key_fingerprints",
"=>",
"missing",
".",
"map",
"{",
"|",
"(",
"u",
",",
"f",
")",
"|",
"f",
"}",
"}",
"request",
"=",
"RightScale",
"::",
"RetryableRequest",
".",
"new",
"(",
"\"/key_server/retrieve_public_keys\"",
",",
"payload",
")",
"request",
".",
"callback",
"do",
"|",
"public_keys",
"|",
"if",
"public_keys",
"missing",
"=",
"populate_public_keys",
"(",
"users",
",",
"public_keys",
",",
"remove_if_missing",
"=",
"true",
")",
"finalize_policy",
"(",
"new_policy",
",",
"agent_identity",
",",
"users",
",",
"missing",
".",
"map",
"{",
"|",
"(",
"u",
",",
"f",
")",
"|",
"u",
"}",
".",
"uniq",
")",
"do",
"|",
"audit_content",
"|",
"yield",
"audit_content",
"end",
"end",
"end",
"request",
".",
"errback",
"do",
"|",
"error",
"|",
"Log",
".",
"error",
"(",
"\"Failed to retrieve public keys for users #{missing.map { |(u, f)| u.username }.uniq.inspect} (#{error})\"",
")",
"missing",
"=",
"populate_public_keys",
"(",
"users",
",",
"{",
"}",
",",
"remove_if_missing",
"=",
"true",
")",
"finalize_policy",
"(",
"new_policy",
",",
"agent_identity",
",",
"users",
",",
"missing",
".",
"map",
"{",
"|",
"(",
"u",
",",
"f",
")",
"|",
"u",
"}",
".",
"uniq",
")",
"do",
"|",
"audit_content",
"|",
"yield",
"audit_content",
"end",
"end",
"request",
".",
"run",
"else",
"finalize_policy",
"(",
"new_policy",
",",
"agent_identity",
",",
"users",
",",
"missing",
".",
"map",
"{",
"|",
"(",
"u",
",",
"f",
")",
"|",
"u",
"}",
".",
"uniq",
")",
"do",
"|",
"audit_content",
"|",
"yield",
"audit_content",
"end",
"end",
"true",
"end"
] | For any user with a public key fingerprint but no public key, obtain the public key
from the old policy or by querying RightScale using the fingerprints
Remove a user if no public keys are available for it
== Parameters:
@param [Array<LoginUsers>] Login users whose public keys are to be populated
@param [String] Serialized instance agent identity
@param [RightScale::LoginPolicy] New login policy
== Yields:
@yield [String] audit content yielded to the block provided
== Returns:
@return [TrueClass] always returns true | [
"For",
"any",
"user",
"with",
"a",
"public",
"key",
"fingerprint",
"but",
"no",
"public",
"key",
"obtain",
"the",
"public",
"key",
"from",
"the",
"old",
"policy",
"or",
"by",
"querying",
"RightScale",
"using",
"the",
"fingerprints",
"Remove",
"a",
"user",
"if",
"no",
"public",
"keys",
"are",
"available",
"for",
"it"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/login_manager.rb#L144-L187 | train |
rightscale/right_link | lib/instance/login_manager.rb | RightScale.LoginManager.finalize_policy | def finalize_policy(new_policy, agent_identity, new_policy_users, missing)
manage_existing_users(new_policy_users)
user_lines = login_users_to_authorized_keys(new_policy_users)
InstanceState.login_policy = new_policy
write_keys_file(user_lines, RIGHTSCALE_KEYS_FILE, { :user => 'rightscale', :group => 'rightscale' })
unless @login_policy_tag_set
tags = [RESTRICTED_TAG]
AgentTagManager.instance.add_tags(tags)
@login_policy_tag_set = true
end
# Schedule a timer to handle any expiration that is planned to happen in the future
schedule_expiry(new_policy, agent_identity)
# Yield a human-readable description of the policy, e.g. for an audit entry
yield describe_policy(new_policy_users, new_policy_users.select { |u| u.superuser }, missing)
true
end | ruby | def finalize_policy(new_policy, agent_identity, new_policy_users, missing)
manage_existing_users(new_policy_users)
user_lines = login_users_to_authorized_keys(new_policy_users)
InstanceState.login_policy = new_policy
write_keys_file(user_lines, RIGHTSCALE_KEYS_FILE, { :user => 'rightscale', :group => 'rightscale' })
unless @login_policy_tag_set
tags = [RESTRICTED_TAG]
AgentTagManager.instance.add_tags(tags)
@login_policy_tag_set = true
end
# Schedule a timer to handle any expiration that is planned to happen in the future
schedule_expiry(new_policy, agent_identity)
# Yield a human-readable description of the policy, e.g. for an audit entry
yield describe_policy(new_policy_users, new_policy_users.select { |u| u.superuser }, missing)
true
end | [
"def",
"finalize_policy",
"(",
"new_policy",
",",
"agent_identity",
",",
"new_policy_users",
",",
"missing",
")",
"manage_existing_users",
"(",
"new_policy_users",
")",
"user_lines",
"=",
"login_users_to_authorized_keys",
"(",
"new_policy_users",
")",
"InstanceState",
".",
"login_policy",
"=",
"new_policy",
"write_keys_file",
"(",
"user_lines",
",",
"RIGHTSCALE_KEYS_FILE",
",",
"{",
":user",
"=>",
"'rightscale'",
",",
":group",
"=>",
"'rightscale'",
"}",
")",
"unless",
"@login_policy_tag_set",
"tags",
"=",
"[",
"RESTRICTED_TAG",
"]",
"AgentTagManager",
".",
"instance",
".",
"add_tags",
"(",
"tags",
")",
"@login_policy_tag_set",
"=",
"true",
"end",
"schedule_expiry",
"(",
"new_policy",
",",
"agent_identity",
")",
"yield",
"describe_policy",
"(",
"new_policy_users",
",",
"new_policy_users",
".",
"select",
"{",
"|",
"u",
"|",
"u",
".",
"superuser",
"}",
",",
"missing",
")",
"true",
"end"
] | Manipulates the authorized_keys file to match the given login policy
Schedules expiration of users from policy and audits the policy in
a human-readable format
== Parameters:
@param [RightScale::LoginPolicy] New login policy
@param [String] Serialized instance agent identity
@param [Array<LoginUsers>] Array of updated users
@param [Array<LoginUsers>] Array of users with public keys missing
== Yields:
@yield [String] audit content yielded to the block provided
== Returns:
@return [TrueClass] always returns true | [
"Manipulates",
"the",
"authorized_keys",
"file",
"to",
"match",
"the",
"given",
"login",
"policy",
"Schedules",
"expiration",
"of",
"users",
"from",
"policy",
"and",
"audits",
"the",
"policy",
"in",
"a",
"human",
"-",
"readable",
"format"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/login_manager.rb#L205-L227 | train |
rightscale/right_link | lib/instance/login_manager.rb | RightScale.LoginManager.populate_public_keys | def populate_public_keys(users, public_keys_cache, remove_if_missing = false)
missing = []
users.reject! do |user|
reject = false
# Create any missing fingerprints from the public keys so that fingerprints
# are as populated as possible
user.public_key_fingerprints ||= user.public_keys.map { |key| fingerprint(key, user.username) }
user.public_key_fingerprints = user.public_keys.zip(user.public_key_fingerprints).map do |(k, f)|
f || fingerprint(k, user.username)
end
# Where possible use cache of old public keys to populate any missing ones
public_keys = user.public_keys.zip(user.public_key_fingerprints).inject([]) do |keys, (k, f)|
if f
if k ||= public_keys_cache[f]
keys << k
else
if remove_if_missing
Log.error("Failed to obtain public key with fingerprint #{f.inspect} for user #{user.username}, " +
"removing it from login policy")
else
keys << k
end
missing << [user, f]
end
else
Log.error("Failed to obtain public key with fingerprint #{f.inspect} for user #{user.username}, " +
"removing it from login policy")
end
keys
end
# Reject user if none of its public keys could be populated
# This will not happen unless remove_if_missing is true
if public_keys.empty?
reject = true
else
user.public_keys = public_keys
end
reject
end
missing
end | ruby | def populate_public_keys(users, public_keys_cache, remove_if_missing = false)
missing = []
users.reject! do |user|
reject = false
# Create any missing fingerprints from the public keys so that fingerprints
# are as populated as possible
user.public_key_fingerprints ||= user.public_keys.map { |key| fingerprint(key, user.username) }
user.public_key_fingerprints = user.public_keys.zip(user.public_key_fingerprints).map do |(k, f)|
f || fingerprint(k, user.username)
end
# Where possible use cache of old public keys to populate any missing ones
public_keys = user.public_keys.zip(user.public_key_fingerprints).inject([]) do |keys, (k, f)|
if f
if k ||= public_keys_cache[f]
keys << k
else
if remove_if_missing
Log.error("Failed to obtain public key with fingerprint #{f.inspect} for user #{user.username}, " +
"removing it from login policy")
else
keys << k
end
missing << [user, f]
end
else
Log.error("Failed to obtain public key with fingerprint #{f.inspect} for user #{user.username}, " +
"removing it from login policy")
end
keys
end
# Reject user if none of its public keys could be populated
# This will not happen unless remove_if_missing is true
if public_keys.empty?
reject = true
else
user.public_keys = public_keys
end
reject
end
missing
end | [
"def",
"populate_public_keys",
"(",
"users",
",",
"public_keys_cache",
",",
"remove_if_missing",
"=",
"false",
")",
"missing",
"=",
"[",
"]",
"users",
".",
"reject!",
"do",
"|",
"user",
"|",
"reject",
"=",
"false",
"user",
".",
"public_key_fingerprints",
"||=",
"user",
".",
"public_keys",
".",
"map",
"{",
"|",
"key",
"|",
"fingerprint",
"(",
"key",
",",
"user",
".",
"username",
")",
"}",
"user",
".",
"public_key_fingerprints",
"=",
"user",
".",
"public_keys",
".",
"zip",
"(",
"user",
".",
"public_key_fingerprints",
")",
".",
"map",
"do",
"|",
"(",
"k",
",",
"f",
")",
"|",
"f",
"||",
"fingerprint",
"(",
"k",
",",
"user",
".",
"username",
")",
"end",
"public_keys",
"=",
"user",
".",
"public_keys",
".",
"zip",
"(",
"user",
".",
"public_key_fingerprints",
")",
".",
"inject",
"(",
"[",
"]",
")",
"do",
"|",
"keys",
",",
"(",
"k",
",",
"f",
")",
"|",
"if",
"f",
"if",
"k",
"||=",
"public_keys_cache",
"[",
"f",
"]",
"keys",
"<<",
"k",
"else",
"if",
"remove_if_missing",
"Log",
".",
"error",
"(",
"\"Failed to obtain public key with fingerprint #{f.inspect} for user #{user.username}, \"",
"+",
"\"removing it from login policy\"",
")",
"else",
"keys",
"<<",
"k",
"end",
"missing",
"<<",
"[",
"user",
",",
"f",
"]",
"end",
"else",
"Log",
".",
"error",
"(",
"\"Failed to obtain public key with fingerprint #{f.inspect} for user #{user.username}, \"",
"+",
"\"removing it from login policy\"",
")",
"end",
"keys",
"end",
"if",
"public_keys",
".",
"empty?",
"reject",
"=",
"true",
"else",
"user",
".",
"public_keys",
"=",
"public_keys",
"end",
"reject",
"end",
"missing",
"end"
] | Populate missing public keys from old public keys using associated fingerprints
Also populate any missing fingerprints where possible
== Parameters:
@param [Array<LoginUser>] Login users whose public keys are to be updated if nil
@param [Hash<String, String>] Public keys with fingerprint as key and public key as value
@param [Boolean] Whether to remove a user's public key if it cannot be obtained
and the user itself if none of its public keys can be obtained
== Returns:
@return [Array<LoginUser,String] User and fingerprint for each missing public key | [
"Populate",
"missing",
"public",
"keys",
"from",
"old",
"public",
"keys",
"using",
"associated",
"fingerprints",
"Also",
"populate",
"any",
"missing",
"fingerprints",
"where",
"possible"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/login_manager.rb#L241-L284 | train |
rightscale/right_link | lib/instance/login_manager.rb | RightScale.LoginManager.fingerprint | def fingerprint(public_key, username)
LoginUser.fingerprint(public_key) if public_key
rescue Exception => e
Log.error("Failed to create public key fingerprint for user #{username}", e)
nil
end | ruby | def fingerprint(public_key, username)
LoginUser.fingerprint(public_key) if public_key
rescue Exception => e
Log.error("Failed to create public key fingerprint for user #{username}", e)
nil
end | [
"def",
"fingerprint",
"(",
"public_key",
",",
"username",
")",
"LoginUser",
".",
"fingerprint",
"(",
"public_key",
")",
"if",
"public_key",
"rescue",
"Exception",
"=>",
"e",
"Log",
".",
"error",
"(",
"\"Failed to create public key fingerprint for user #{username}\"",
",",
"e",
")",
"nil",
"end"
] | Create fingerprint for public key
== Parameters:
@param [String] RSA public key
@param [String] Name of user owning this key
== Return:
@return [String] Fingerprint for key if it could create it
@return [NilClass] if it could not create it | [
"Create",
"fingerprint",
"for",
"public",
"key"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/login_manager.rb#L296-L301 | train |
rightscale/right_link | lib/instance/login_manager.rb | RightScale.LoginManager.load_keys | def load_keys(path)
file_lines = read_keys_file(path)
keys = []
file_lines.map do |l|
components = LoginPolicy.parse_public_key(l)
if components
#preserve algorithm, key and comments; discard options (the 0th element)
keys << [ components[1], components[2], components[3] ]
elsif l =~ COMMENT
next
else
RightScale::Log.error("Malformed (or not SSH2) entry in authorized_keys file: #{l}")
next
end
end
keys
end | ruby | def load_keys(path)
file_lines = read_keys_file(path)
keys = []
file_lines.map do |l|
components = LoginPolicy.parse_public_key(l)
if components
#preserve algorithm, key and comments; discard options (the 0th element)
keys << [ components[1], components[2], components[3] ]
elsif l =~ COMMENT
next
else
RightScale::Log.error("Malformed (or not SSH2) entry in authorized_keys file: #{l}")
next
end
end
keys
end | [
"def",
"load_keys",
"(",
"path",
")",
"file_lines",
"=",
"read_keys_file",
"(",
"path",
")",
"keys",
"=",
"[",
"]",
"file_lines",
".",
"map",
"do",
"|",
"l",
"|",
"components",
"=",
"LoginPolicy",
".",
"parse_public_key",
"(",
"l",
")",
"if",
"components",
"keys",
"<<",
"[",
"components",
"[",
"1",
"]",
",",
"components",
"[",
"2",
"]",
",",
"components",
"[",
"3",
"]",
"]",
"elsif",
"l",
"=~",
"COMMENT",
"next",
"else",
"RightScale",
"::",
"Log",
".",
"error",
"(",
"\"Malformed (or not SSH2) entry in authorized_keys file: #{l}\"",
")",
"next",
"end",
"end",
"keys",
"end"
] | Returns array of public keys of specified authorized_keys file
== Parameters:
@param [String] path to authorized_keys file
== Returns:
@return [Array<Array(String, String, String)>] array of authorized_key parameters: algorith, public key, comment | [
"Returns",
"array",
"of",
"public",
"keys",
"of",
"specified",
"authorized_keys",
"file"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/login_manager.rb#L312-L331 | train |
rightscale/right_link | lib/instance/login_manager.rb | RightScale.LoginManager.describe_policy | def describe_policy(users, superusers, missing = [])
normal_users = users - superusers
audit = "#{users.size} authorized users (#{normal_users.size} normal, #{superusers.size} superuser).\n"
audit << "Public key missing for #{missing.map { |u| u.username }.join(", ") }.\n" if missing.size > 0
#unless normal_users.empty?
# audit += "\nNormal users:\n"
# normal_users.each do |u|
# audit += " #{u.common_name.ljust(40)} #{u.username}\n"
# end
#end
#
#unless superusers.empty?
# audit += "\nSuperusers:\n"
# superusers.each do |u|
# audit += " #{u.common_name.ljust(40)} #{u.username}\n"
# end
#end
return audit
end | ruby | def describe_policy(users, superusers, missing = [])
normal_users = users - superusers
audit = "#{users.size} authorized users (#{normal_users.size} normal, #{superusers.size} superuser).\n"
audit << "Public key missing for #{missing.map { |u| u.username }.join(", ") }.\n" if missing.size > 0
#unless normal_users.empty?
# audit += "\nNormal users:\n"
# normal_users.each do |u|
# audit += " #{u.common_name.ljust(40)} #{u.username}\n"
# end
#end
#
#unless superusers.empty?
# audit += "\nSuperusers:\n"
# superusers.each do |u|
# audit += " #{u.common_name.ljust(40)} #{u.username}\n"
# end
#end
return audit
end | [
"def",
"describe_policy",
"(",
"users",
",",
"superusers",
",",
"missing",
"=",
"[",
"]",
")",
"normal_users",
"=",
"users",
"-",
"superusers",
"audit",
"=",
"\"#{users.size} authorized users (#{normal_users.size} normal, #{superusers.size} superuser).\\n\"",
"audit",
"<<",
"\"Public key missing for #{missing.map { |u| u.username }.join(\", \") }.\\n\"",
"if",
"missing",
".",
"size",
">",
"0",
"return",
"audit",
"end"
] | Return a verbose, human-readable description of the login policy, suitable
for appending to an audit entry. Contains formatting such as newlines and tabs.
== Parameters:
@param [Array<LoginUser>] All LoginUsers
@param [Array<LoginUser>] Subset of LoginUsers who are authorized to act as superusers
@param [LoginPolicy] Effective login policy
@param [Array<LoginUser>] Users for which a public key could not be obtained
== Returns:
@return [String] description | [
"Return",
"a",
"verbose",
"human",
"-",
"readable",
"description",
"of",
"the",
"login",
"policy",
"suitable",
"for",
"appending",
"to",
"an",
"audit",
"entry",
".",
"Contains",
"formatting",
"such",
"as",
"newlines",
"and",
"tabs",
"."
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/login_manager.rb#L345-L366 | train |
rightscale/right_link | lib/instance/login_manager.rb | RightScale.LoginManager.login_users_to_authorized_keys | def login_users_to_authorized_keys(new_users)
now = Time.now
user_lines = []
new_users.each do |u|
if u.expires_at.nil? || u.expires_at > now
u.public_keys.each do |k|
user_lines << "#{get_key_prefix(u.username, u.common_name, u.uuid, u.superuser, u.profile_data)} #{k}"
end
end
end
return user_lines.sort
end | ruby | def login_users_to_authorized_keys(new_users)
now = Time.now
user_lines = []
new_users.each do |u|
if u.expires_at.nil? || u.expires_at > now
u.public_keys.each do |k|
user_lines << "#{get_key_prefix(u.username, u.common_name, u.uuid, u.superuser, u.profile_data)} #{k}"
end
end
end
return user_lines.sort
end | [
"def",
"login_users_to_authorized_keys",
"(",
"new_users",
")",
"now",
"=",
"Time",
".",
"now",
"user_lines",
"=",
"[",
"]",
"new_users",
".",
"each",
"do",
"|",
"u",
"|",
"if",
"u",
".",
"expires_at",
".",
"nil?",
"||",
"u",
".",
"expires_at",
">",
"now",
"u",
".",
"public_keys",
".",
"each",
"do",
"|",
"k",
"|",
"user_lines",
"<<",
"\"#{get_key_prefix(u.username, u.common_name, u.uuid, u.superuser, u.profile_data)} #{k}\"",
"end",
"end",
"end",
"return",
"user_lines",
".",
"sort",
"end"
] | Given a list of LoginUsers, compute an authorized_keys file that encompasses all
of the users and has a suitable options field that invokes rs_thunk with the right
command-line params for that user. Omit any users who are expired.
== Parameters:
@param [Array<LoginUser>] array of updated users list
== Returns:
@return [Array<String>] public key lines of user accounts | [
"Given",
"a",
"list",
"of",
"LoginUsers",
"compute",
"an",
"authorized_keys",
"file",
"that",
"encompasses",
"all",
"of",
"the",
"users",
"and",
"has",
"a",
"suitable",
"options",
"field",
"that",
"invokes",
"rs_thunk",
"with",
"the",
"right",
"command",
"-",
"line",
"params",
"for",
"that",
"user",
".",
"Omit",
"any",
"users",
"who",
"are",
"expired",
"."
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/login_manager.rb#L420-L434 | train |
rightscale/right_link | lib/instance/login_manager.rb | RightScale.LoginManager.manage_existing_users | def manage_existing_users(new_policy_users)
now = Time.now
previous = {}
if InstanceState.login_policy
InstanceState.login_policy.users.each do |user|
previous[user.uuid] = user
end
end
current = {}
new_policy_users.each do |user|
current[user.uuid] = user
end
added = current.keys - previous.keys
removed = previous.keys - current.keys
stayed = current.keys & previous.keys
removed.each do |k|
begin
user = current[k] || previous[k]
LoginUserManager.manage_user(user.uuid, user.superuser, :disable => true)
rescue Exception => e
RightScale::Log.error("Failed to disable user '#{user.uuid}'", e) unless e.is_a?(ArgumentError)
end
end
(added + stayed).each do |k|
begin
user = current[k] || previous[k]
disable = !!(user.expires_at) && (now >= user.expires_at)
LoginUserManager.manage_user(user.uuid, user.superuser, :disable => disable)
rescue Exception => e
RightScale::Log.error("Failed to manage existing user '#{user.uuid}'", e) unless e.is_a?(ArgumentError)
end
end
rescue Exception => e
RightScale::Log.error("Failed to manage existing users", e)
end | ruby | def manage_existing_users(new_policy_users)
now = Time.now
previous = {}
if InstanceState.login_policy
InstanceState.login_policy.users.each do |user|
previous[user.uuid] = user
end
end
current = {}
new_policy_users.each do |user|
current[user.uuid] = user
end
added = current.keys - previous.keys
removed = previous.keys - current.keys
stayed = current.keys & previous.keys
removed.each do |k|
begin
user = current[k] || previous[k]
LoginUserManager.manage_user(user.uuid, user.superuser, :disable => true)
rescue Exception => e
RightScale::Log.error("Failed to disable user '#{user.uuid}'", e) unless e.is_a?(ArgumentError)
end
end
(added + stayed).each do |k|
begin
user = current[k] || previous[k]
disable = !!(user.expires_at) && (now >= user.expires_at)
LoginUserManager.manage_user(user.uuid, user.superuser, :disable => disable)
rescue Exception => e
RightScale::Log.error("Failed to manage existing user '#{user.uuid}'", e) unless e.is_a?(ArgumentError)
end
end
rescue Exception => e
RightScale::Log.error("Failed to manage existing users", e)
end | [
"def",
"manage_existing_users",
"(",
"new_policy_users",
")",
"now",
"=",
"Time",
".",
"now",
"previous",
"=",
"{",
"}",
"if",
"InstanceState",
".",
"login_policy",
"InstanceState",
".",
"login_policy",
".",
"users",
".",
"each",
"do",
"|",
"user",
"|",
"previous",
"[",
"user",
".",
"uuid",
"]",
"=",
"user",
"end",
"end",
"current",
"=",
"{",
"}",
"new_policy_users",
".",
"each",
"do",
"|",
"user",
"|",
"current",
"[",
"user",
".",
"uuid",
"]",
"=",
"user",
"end",
"added",
"=",
"current",
".",
"keys",
"-",
"previous",
".",
"keys",
"removed",
"=",
"previous",
".",
"keys",
"-",
"current",
".",
"keys",
"stayed",
"=",
"current",
".",
"keys",
"&",
"previous",
".",
"keys",
"removed",
".",
"each",
"do",
"|",
"k",
"|",
"begin",
"user",
"=",
"current",
"[",
"k",
"]",
"||",
"previous",
"[",
"k",
"]",
"LoginUserManager",
".",
"manage_user",
"(",
"user",
".",
"uuid",
",",
"user",
".",
"superuser",
",",
":disable",
"=>",
"true",
")",
"rescue",
"Exception",
"=>",
"e",
"RightScale",
"::",
"Log",
".",
"error",
"(",
"\"Failed to disable user '#{user.uuid}'\"",
",",
"e",
")",
"unless",
"e",
".",
"is_a?",
"(",
"ArgumentError",
")",
"end",
"end",
"(",
"added",
"+",
"stayed",
")",
".",
"each",
"do",
"|",
"k",
"|",
"begin",
"user",
"=",
"current",
"[",
"k",
"]",
"||",
"previous",
"[",
"k",
"]",
"disable",
"=",
"!",
"!",
"(",
"user",
".",
"expires_at",
")",
"&&",
"(",
"now",
">=",
"user",
".",
"expires_at",
")",
"LoginUserManager",
".",
"manage_user",
"(",
"user",
".",
"uuid",
",",
"user",
".",
"superuser",
",",
":disable",
"=>",
"disable",
")",
"rescue",
"Exception",
"=>",
"e",
"RightScale",
"::",
"Log",
".",
"error",
"(",
"\"Failed to manage existing user '#{user.uuid}'\"",
",",
"e",
")",
"unless",
"e",
".",
"is_a?",
"(",
"ArgumentError",
")",
"end",
"end",
"rescue",
"Exception",
"=>",
"e",
"RightScale",
"::",
"Log",
".",
"error",
"(",
"\"Failed to manage existing users\"",
",",
"e",
")",
"end"
] | Schedules expiration of new users from policy and existing ones
@param [Array<LoginUsers>] Array of updated users
== Returns:
@return [TrueClass] always returns true | [
"Schedules",
"expiration",
"of",
"new",
"users",
"from",
"policy",
"and",
"existing",
"ones"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/login_manager.rb#L442-L481 | train |
rightscale/right_link | lib/instance/login_manager.rb | RightScale.LoginManager.write_keys_file | def write_keys_file(keys, keys_file, chown_params = nil)
dir = File.dirname(keys_file)
FileUtils.mkdir_p(dir)
FileUtils.chmod(0700, dir)
File.open(keys_file, 'w') do |f|
f.puts "#" * 78
f.puts "# USE CAUTION WHEN EDITING THIS FILE BY HAND"
f.puts "# This file is generated based on the RightScale dashboard permission"
f.puts "# 'server_login'. You can add trusted public keys to the file, but"
f.puts "# it is regenerated every 24 hours and keys may be added or removed"
f.puts "# without notice if they correspond to a dashboard user."
f.puts "#"
f.puts "# Instead of editing this file, you probably want to do one of the"
f.puts "# following:"
f.puts "# - Edit dashboard permissions (Settings > Account > Users)"
f.puts "# - Change your personal public key (Settings > User > SSH)"
f.puts "#"
keys.each { |k| f.puts k }
end
FileUtils.chmod(0600, keys_file)
FileUtils.chown_R(chown_params[:user], chown_params[:group], File.dirname(keys_file)) if chown_params
return true
end | ruby | def write_keys_file(keys, keys_file, chown_params = nil)
dir = File.dirname(keys_file)
FileUtils.mkdir_p(dir)
FileUtils.chmod(0700, dir)
File.open(keys_file, 'w') do |f|
f.puts "#" * 78
f.puts "# USE CAUTION WHEN EDITING THIS FILE BY HAND"
f.puts "# This file is generated based on the RightScale dashboard permission"
f.puts "# 'server_login'. You can add trusted public keys to the file, but"
f.puts "# it is regenerated every 24 hours and keys may be added or removed"
f.puts "# without notice if they correspond to a dashboard user."
f.puts "#"
f.puts "# Instead of editing this file, you probably want to do one of the"
f.puts "# following:"
f.puts "# - Edit dashboard permissions (Settings > Account > Users)"
f.puts "# - Change your personal public key (Settings > User > SSH)"
f.puts "#"
keys.each { |k| f.puts k }
end
FileUtils.chmod(0600, keys_file)
FileUtils.chown_R(chown_params[:user], chown_params[:group], File.dirname(keys_file)) if chown_params
return true
end | [
"def",
"write_keys_file",
"(",
"keys",
",",
"keys_file",
",",
"chown_params",
"=",
"nil",
")",
"dir",
"=",
"File",
".",
"dirname",
"(",
"keys_file",
")",
"FileUtils",
".",
"mkdir_p",
"(",
"dir",
")",
"FileUtils",
".",
"chmod",
"(",
"0700",
",",
"dir",
")",
"File",
".",
"open",
"(",
"keys_file",
",",
"'w'",
")",
"do",
"|",
"f",
"|",
"f",
".",
"puts",
"\"#\"",
"*",
"78",
"f",
".",
"puts",
"\"# USE CAUTION WHEN EDITING THIS FILE BY HAND\"",
"f",
".",
"puts",
"\"# This file is generated based on the RightScale dashboard permission\"",
"f",
".",
"puts",
"\"# 'server_login'. You can add trusted public keys to the file, but\"",
"f",
".",
"puts",
"\"# it is regenerated every 24 hours and keys may be added or removed\"",
"f",
".",
"puts",
"\"# without notice if they correspond to a dashboard user.\"",
"f",
".",
"puts",
"\"#\"",
"f",
".",
"puts",
"\"# Instead of editing this file, you probably want to do one of the\"",
"f",
".",
"puts",
"\"# following:\"",
"f",
".",
"puts",
"\"# - Edit dashboard permissions (Settings > Account > Users)\"",
"f",
".",
"puts",
"\"# - Change your personal public key (Settings > User > SSH)\"",
"f",
".",
"puts",
"\"#\"",
"keys",
".",
"each",
"{",
"|",
"k",
"|",
"f",
".",
"puts",
"k",
"}",
"end",
"FileUtils",
".",
"chmod",
"(",
"0600",
",",
"keys_file",
")",
"FileUtils",
".",
"chown_R",
"(",
"chown_params",
"[",
":user",
"]",
",",
"chown_params",
"[",
":group",
"]",
",",
"File",
".",
"dirname",
"(",
"keys_file",
")",
")",
"if",
"chown_params",
"return",
"true",
"end"
] | Replace the contents of specified keys file
== Parameters:
@param [Array<String>] list of lines that authorized_keys file should contain
@param [String] path to authorized_keys file
@param [Hash] additional parameters for user/group
== Returns:
@return [TrueClass] always returns true | [
"Replace",
"the",
"contents",
"of",
"specified",
"keys",
"file"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/login_manager.rb#L508-L533 | train |
mattThousand/sad_panda | lib/sad_panda/helpers.rb | SadPanda.Helpers.frequencies_for | def frequencies_for(words)
word_frequencies = {}
words.each { |word| word_frequencies[word] = words.count(word) }
word_frequencies
end | ruby | def frequencies_for(words)
word_frequencies = {}
words.each { |word| word_frequencies[word] = words.count(word) }
word_frequencies
end | [
"def",
"frequencies_for",
"(",
"words",
")",
"word_frequencies",
"=",
"{",
"}",
"words",
".",
"each",
"{",
"|",
"word",
"|",
"word_frequencies",
"[",
"word",
"]",
"=",
"words",
".",
"count",
"(",
"word",
")",
"}",
"word_frequencies",
"end"
] | Returns a Hash of frequencies of each uniq word in the text | [
"Returns",
"a",
"Hash",
"of",
"frequencies",
"of",
"each",
"uniq",
"word",
"in",
"the",
"text"
] | 2ccb1496529d5c5a453d3822fa44b746295f3962 | https://github.com/mattThousand/sad_panda/blob/2ccb1496529d5c5a453d3822fa44b746295f3962/lib/sad_panda/helpers.rb#L13-L17 | train |
mattThousand/sad_panda | lib/sad_panda/helpers.rb | SadPanda.Helpers.stems_for | def stems_for(words)
stemmer = Lingua::Stemmer.new(language: 'en')
words.map! { |word| stemmer.stem(word) }
end | ruby | def stems_for(words)
stemmer = Lingua::Stemmer.new(language: 'en')
words.map! { |word| stemmer.stem(word) }
end | [
"def",
"stems_for",
"(",
"words",
")",
"stemmer",
"=",
"Lingua",
"::",
"Stemmer",
".",
"new",
"(",
"language",
":",
"'en'",
")",
"words",
".",
"map!",
"{",
"|",
"word",
"|",
"stemmer",
".",
"stem",
"(",
"word",
")",
"}",
"end"
] | Converts all the words to its stem form | [
"Converts",
"all",
"the",
"words",
"to",
"its",
"stem",
"form"
] | 2ccb1496529d5c5a453d3822fa44b746295f3962 | https://github.com/mattThousand/sad_panda/blob/2ccb1496529d5c5a453d3822fa44b746295f3962/lib/sad_panda/helpers.rb#L20-L23 | train |
mattThousand/sad_panda | lib/sad_panda/helpers.rb | SadPanda.Helpers.emojies_in | def emojies_in(text)
(sad_emojies + happy_emojies).map do |emoji|
text.scan(emoji)
end.flatten
end | ruby | def emojies_in(text)
(sad_emojies + happy_emojies).map do |emoji|
text.scan(emoji)
end.flatten
end | [
"def",
"emojies_in",
"(",
"text",
")",
"(",
"sad_emojies",
"+",
"happy_emojies",
")",
".",
"map",
"do",
"|",
"emoji",
"|",
"text",
".",
"scan",
"(",
"emoji",
")",
"end",
".",
"flatten",
"end"
] | Captures and returns emojies in the text | [
"Captures",
"and",
"returns",
"emojies",
"in",
"the",
"text"
] | 2ccb1496529d5c5a453d3822fa44b746295f3962 | https://github.com/mattThousand/sad_panda/blob/2ccb1496529d5c5a453d3822fa44b746295f3962/lib/sad_panda/helpers.rb#L31-L35 | train |
mattThousand/sad_panda | lib/sad_panda/helpers.rb | SadPanda.Helpers.sanitize | def sanitize(text)
text.gsub!(/[^a-z ]/i, '')
text.gsub!(/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/, '')
text.gsub!(/(?=\w*h)(?=\w*t)(?=\w*t)(?=\w*p)\w*/, '')
text.gsub!(/\s\s+/, ' ')
text.downcase
end | ruby | def sanitize(text)
text.gsub!(/[^a-z ]/i, '')
text.gsub!(/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/, '')
text.gsub!(/(?=\w*h)(?=\w*t)(?=\w*t)(?=\w*p)\w*/, '')
text.gsub!(/\s\s+/, ' ')
text.downcase
end | [
"def",
"sanitize",
"(",
"text",
")",
"text",
".",
"gsub!",
"(",
"/",
"/i",
",",
"''",
")",
"text",
".",
"gsub!",
"(",
"/",
"\\/",
"\\/",
"\\+",
"\\$",
"\\w",
"\\+",
"\\$",
"\\w",
"\\/",
"\\+",
"\\/",
"\\w",
"\\?",
"\\+",
"\\w",
"\\w",
"/",
",",
"''",
")",
"text",
".",
"gsub!",
"(",
"/",
"\\w",
"\\w",
"\\w",
"\\w",
"\\w",
"/",
",",
"''",
")",
"text",
".",
"gsub!",
"(",
"/",
"\\s",
"\\s",
"/",
",",
"' '",
")",
"text",
".",
"downcase",
"end"
] | Removing non ASCII characters from text | [
"Removing",
"non",
"ASCII",
"characters",
"from",
"text"
] | 2ccb1496529d5c5a453d3822fa44b746295f3962 | https://github.com/mattThousand/sad_panda/blob/2ccb1496529d5c5a453d3822fa44b746295f3962/lib/sad_panda/helpers.rb#L38-L45 | train |
rightscale/right_link | lib/instance/cook/audit_logger.rb | RightScale.AuditLogFormatter.call | def call(severity, time, progname, msg)
sprintf("%s: %s\n", time.strftime("%H:%M:%S"), hide_inputs(msg2str(msg)))
end | ruby | def call(severity, time, progname, msg)
sprintf("%s: %s\n", time.strftime("%H:%M:%S"), hide_inputs(msg2str(msg)))
end | [
"def",
"call",
"(",
"severity",
",",
"time",
",",
"progname",
",",
"msg",
")",
"sprintf",
"(",
"\"%s: %s\\n\"",
",",
"time",
".",
"strftime",
"(",
"\"%H:%M:%S\"",
")",
",",
"hide_inputs",
"(",
"msg2str",
"(",
"msg",
")",
")",
")",
"end"
] | Generate log line from given input | [
"Generate",
"log",
"line",
"from",
"given",
"input"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/audit_logger.rb#L38-L40 | train |
rightscale/right_link | lib/instance/cook/audit_logger.rb | RightScale.AuditLogger.is_filtered? | def is_filtered?(severity, message)
if filters = MESSAGE_FILTERS[severity]
filters.each do |filter|
return true if filter =~ message
end
end
return false
end | ruby | def is_filtered?(severity, message)
if filters = MESSAGE_FILTERS[severity]
filters.each do |filter|
return true if filter =~ message
end
end
return false
end | [
"def",
"is_filtered?",
"(",
"severity",
",",
"message",
")",
"if",
"filters",
"=",
"MESSAGE_FILTERS",
"[",
"severity",
"]",
"filters",
".",
"each",
"do",
"|",
"filter",
"|",
"return",
"true",
"if",
"filter",
"=~",
"message",
"end",
"end",
"return",
"false",
"end"
] | Filters any message which should not appear in audits.
=== Parameters
severity(Constant):: One of Logger::DEBUG, Logger::INFO, Logger::WARN, Logger::ERROR or Logger::FATAL
message(String):: Message to be audited | [
"Filters",
"any",
"message",
"which",
"should",
"not",
"appear",
"in",
"audits",
"."
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/audit_logger.rb#L166-L173 | train |
rightscale/right_link | scripts/system_configurator.rb | RightScale.SystemConfigurator.configure_root_access | def configure_root_access(options = {})
public_key = ENV['VS_SSH_PUBLIC_KEY'].to_s.strip
# was there a key found?
if public_key.nil? || public_key.empty?
puts "No public SSH key found in metadata"
return
end
update_authorized_keys(public_key)
end | ruby | def configure_root_access(options = {})
public_key = ENV['VS_SSH_PUBLIC_KEY'].to_s.strip
# was there a key found?
if public_key.nil? || public_key.empty?
puts "No public SSH key found in metadata"
return
end
update_authorized_keys(public_key)
end | [
"def",
"configure_root_access",
"(",
"options",
"=",
"{",
"}",
")",
"public_key",
"=",
"ENV",
"[",
"'VS_SSH_PUBLIC_KEY'",
"]",
".",
"to_s",
".",
"strip",
"if",
"public_key",
".",
"nil?",
"||",
"public_key",
".",
"empty?",
"puts",
"\"No public SSH key found in metadata\"",
"return",
"end",
"update_authorized_keys",
"(",
"public_key",
")",
"end"
] | Configure root access for vSphere cloud | [
"Configure",
"root",
"access",
"for",
"vSphere",
"cloud"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/scripts/system_configurator.rb#L144-L152 | train |
rightscale/right_link | scripts/system_configurator.rb | RightScale.SystemConfigurator.update_authorized_keys | def update_authorized_keys(public_key)
auth_key_file = "/root/.ssh/authorized_keys"
FileUtils.mkdir_p(File.dirname(auth_key_file)) # make sure the directory exists
key_exists = false
File.open(auth_key_file, "r") do |file|
file.each_line { |line| key_exists = true if line == public_key }
end if File.exists?(auth_key_file)
if key_exists
puts "Public ssh key for root already exists in #{auth_key_file}"
else
puts "Appending public ssh key to #{auth_key_file}"
File.open(auth_key_file, "a") { |f| f.puts(public_key) }
end
# make sure it's private
FileUtils.chmod(0600, auth_key_file)
true
end | ruby | def update_authorized_keys(public_key)
auth_key_file = "/root/.ssh/authorized_keys"
FileUtils.mkdir_p(File.dirname(auth_key_file)) # make sure the directory exists
key_exists = false
File.open(auth_key_file, "r") do |file|
file.each_line { |line| key_exists = true if line == public_key }
end if File.exists?(auth_key_file)
if key_exists
puts "Public ssh key for root already exists in #{auth_key_file}"
else
puts "Appending public ssh key to #{auth_key_file}"
File.open(auth_key_file, "a") { |f| f.puts(public_key) }
end
# make sure it's private
FileUtils.chmod(0600, auth_key_file)
true
end | [
"def",
"update_authorized_keys",
"(",
"public_key",
")",
"auth_key_file",
"=",
"\"/root/.ssh/authorized_keys\"",
"FileUtils",
".",
"mkdir_p",
"(",
"File",
".",
"dirname",
"(",
"auth_key_file",
")",
")",
"key_exists",
"=",
"false",
"File",
".",
"open",
"(",
"auth_key_file",
",",
"\"r\"",
")",
"do",
"|",
"file",
"|",
"file",
".",
"each_line",
"{",
"|",
"line",
"|",
"key_exists",
"=",
"true",
"if",
"line",
"==",
"public_key",
"}",
"end",
"if",
"File",
".",
"exists?",
"(",
"auth_key_file",
")",
"if",
"key_exists",
"puts",
"\"Public ssh key for root already exists in #{auth_key_file}\"",
"else",
"puts",
"\"Appending public ssh key to #{auth_key_file}\"",
"File",
".",
"open",
"(",
"auth_key_file",
",",
"\"a\"",
")",
"{",
"|",
"f",
"|",
"f",
".",
"puts",
"(",
"public_key",
")",
"}",
"end",
"FileUtils",
".",
"chmod",
"(",
"0600",
",",
"auth_key_file",
")",
"true",
"end"
] | Add public key to ssh authorized_keys file
If the file does not exist, it will be created.
If the key already exists, it will not be added again.
=== Parameters
public_key(String):: public ssh key
=== Return | [
"Add",
"public",
"key",
"to",
"ssh",
"authorized_keys",
"file"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/scripts/system_configurator.rb#L428-L449 | train |
rightscale/right_link | scripts/agent_controller.rb | RightScale.RightLinkAgentController.run_command | def run_command(message, command)
puts message
begin
send_command({ :name => command }, verbose = false, timeout = 100) { |r| puts r }
rescue SystemExit => e
raise e
rescue Exception => e
$stderr.puts Log.format("Failed or else time limit was exceeded, confirm that local instance is still running", e, :trace)
return false
end
true
end | ruby | def run_command(message, command)
puts message
begin
send_command({ :name => command }, verbose = false, timeout = 100) { |r| puts r }
rescue SystemExit => e
raise e
rescue Exception => e
$stderr.puts Log.format("Failed or else time limit was exceeded, confirm that local instance is still running", e, :trace)
return false
end
true
end | [
"def",
"run_command",
"(",
"message",
",",
"command",
")",
"puts",
"message",
"begin",
"send_command",
"(",
"{",
":name",
"=>",
"command",
"}",
",",
"verbose",
"=",
"false",
",",
"timeout",
"=",
"100",
")",
"{",
"|",
"r",
"|",
"puts",
"r",
"}",
"rescue",
"SystemExit",
"=>",
"e",
"raise",
"e",
"rescue",
"Exception",
"=>",
"e",
"$stderr",
".",
"puts",
"Log",
".",
"format",
"(",
"\"Failed or else time limit was exceeded, confirm that local instance is still running\"",
",",
"e",
",",
":trace",
")",
"return",
"false",
"end",
"true",
"end"
] | Trigger execution of given command in instance agent and wait for it to be done
=== Parameters
message(String):: Console display message
command(String):: Command name
=== Return
(Boolean):: true if command executed successfully, otherwise false | [
"Trigger",
"execution",
"of",
"given",
"command",
"in",
"instance",
"agent",
"and",
"wait",
"for",
"it",
"to",
"be",
"done"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/scripts/agent_controller.rb#L162-L173 | train |
rightscale/right_link | lib/clouds/cloud_utilities.rb | RightScale.CloudUtilities.can_contact_metadata_server? | def can_contact_metadata_server?(addr, port, timeout=2)
t = Socket.new(Socket::Constants::AF_INET, Socket::Constants::SOCK_STREAM, 0)
saddr = Socket.pack_sockaddr_in(port, addr)
connected = false
begin
t.connect_nonblock(saddr)
rescue Errno::EINPROGRESS
r, w, e = IO::select(nil, [t], nil, timeout)
if !w.nil?
connected = true
else
begin
t.connect_nonblock(saddr)
rescue Errno::EISCONN
t.close
connected = true
rescue SystemCallError
end
end
rescue SystemCallError
end
connected
end | ruby | def can_contact_metadata_server?(addr, port, timeout=2)
t = Socket.new(Socket::Constants::AF_INET, Socket::Constants::SOCK_STREAM, 0)
saddr = Socket.pack_sockaddr_in(port, addr)
connected = false
begin
t.connect_nonblock(saddr)
rescue Errno::EINPROGRESS
r, w, e = IO::select(nil, [t], nil, timeout)
if !w.nil?
connected = true
else
begin
t.connect_nonblock(saddr)
rescue Errno::EISCONN
t.close
connected = true
rescue SystemCallError
end
end
rescue SystemCallError
end
connected
end | [
"def",
"can_contact_metadata_server?",
"(",
"addr",
",",
"port",
",",
"timeout",
"=",
"2",
")",
"t",
"=",
"Socket",
".",
"new",
"(",
"Socket",
"::",
"Constants",
"::",
"AF_INET",
",",
"Socket",
"::",
"Constants",
"::",
"SOCK_STREAM",
",",
"0",
")",
"saddr",
"=",
"Socket",
".",
"pack_sockaddr_in",
"(",
"port",
",",
"addr",
")",
"connected",
"=",
"false",
"begin",
"t",
".",
"connect_nonblock",
"(",
"saddr",
")",
"rescue",
"Errno",
"::",
"EINPROGRESS",
"r",
",",
"w",
",",
"e",
"=",
"IO",
"::",
"select",
"(",
"nil",
",",
"[",
"t",
"]",
",",
"nil",
",",
"timeout",
")",
"if",
"!",
"w",
".",
"nil?",
"connected",
"=",
"true",
"else",
"begin",
"t",
".",
"connect_nonblock",
"(",
"saddr",
")",
"rescue",
"Errno",
"::",
"EISCONN",
"t",
".",
"close",
"connected",
"=",
"true",
"rescue",
"SystemCallError",
"end",
"end",
"rescue",
"SystemCallError",
"end",
"connected",
"end"
] | Attempt to connect to the given address on the given port as a quick verification
that the metadata service is available.
=== Parameters
addr(String):: address of the metadata service
port(Number):: port of the metadata service
timeout(Number)::Optional - time to wait for a response
=== Return
connected(Boolean):: true if a connection could be made, false otherwise | [
"Attempt",
"to",
"connect",
"to",
"the",
"given",
"address",
"on",
"the",
"given",
"port",
"as",
"a",
"quick",
"verification",
"that",
"the",
"metadata",
"service",
"is",
"available",
"."
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/clouds/cloud_utilities.rb#L48-L72 | train |
rightscale/right_link | lib/clouds/cloud_utilities.rb | RightScale.CloudUtilities.split_metadata | def split_metadata(data, splitter, name_value_delimiter = '=')
hash = {}
data.to_s.split(splitter).each do |pair|
name, value = pair.split(name_value_delimiter, 2)
hash[name.strip] = value.strip if name && value
end
hash
end | ruby | def split_metadata(data, splitter, name_value_delimiter = '=')
hash = {}
data.to_s.split(splitter).each do |pair|
name, value = pair.split(name_value_delimiter, 2)
hash[name.strip] = value.strip if name && value
end
hash
end | [
"def",
"split_metadata",
"(",
"data",
",",
"splitter",
",",
"name_value_delimiter",
"=",
"'='",
")",
"hash",
"=",
"{",
"}",
"data",
".",
"to_s",
".",
"split",
"(",
"splitter",
")",
".",
"each",
"do",
"|",
"pair",
"|",
"name",
",",
"value",
"=",
"pair",
".",
"split",
"(",
"name_value_delimiter",
",",
"2",
")",
"hash",
"[",
"name",
".",
"strip",
"]",
"=",
"value",
".",
"strip",
"if",
"name",
"&&",
"value",
"end",
"hash",
"end"
] | Splits data on the given splitter character and returns hash.
=== Parameters
data(String):: raw data
splitter(String):: splitter character
name_value_delimiter(String):: name/value delimiter (defaults to '=')
=== Return
hash(Hash):: hash result | [
"Splits",
"data",
"on",
"the",
"given",
"splitter",
"character",
"and",
"returns",
"hash",
"."
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/clouds/cloud_utilities.rb#L83-L90 | train |
rightscale/right_link | spec/results_mock.rb | RightScale.ResultsMock.success_results | def success_results(content = nil, reply_to = '*test*1')
Result.new(AgentIdentity.generate, reply_to,
{ @agent_id => OperationResult.success(content) }, @agent_id)
end | ruby | def success_results(content = nil, reply_to = '*test*1')
Result.new(AgentIdentity.generate, reply_to,
{ @agent_id => OperationResult.success(content) }, @agent_id)
end | [
"def",
"success_results",
"(",
"content",
"=",
"nil",
",",
"reply_to",
"=",
"'*test*1'",
")",
"Result",
".",
"new",
"(",
"AgentIdentity",
".",
"generate",
",",
"reply_to",
",",
"{",
"@agent_id",
"=>",
"OperationResult",
".",
"success",
"(",
"content",
")",
"}",
",",
"@agent_id",
")",
"end"
] | Build a valid request results with given content | [
"Build",
"a",
"valid",
"request",
"results",
"with",
"given",
"content"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/spec/results_mock.rb#L33-L36 | train |
nikitachernov/FutureProof | lib/future_proof/thread_pool.rb | FutureProof.ThreadPool.perform | def perform
unless @threads.any? { |t| t.alive? }
@values.start!
@size.times do
@threads << Thread.new do
while job = @queue.pop
if job == :END_OF_WORK
break
else
@values.push *job[1], &job[0]
end
end
end
end
end
end | ruby | def perform
unless @threads.any? { |t| t.alive? }
@values.start!
@size.times do
@threads << Thread.new do
while job = @queue.pop
if job == :END_OF_WORK
break
else
@values.push *job[1], &job[0]
end
end
end
end
end
end | [
"def",
"perform",
"unless",
"@threads",
".",
"any?",
"{",
"|",
"t",
"|",
"t",
".",
"alive?",
"}",
"@values",
".",
"start!",
"@size",
".",
"times",
"do",
"@threads",
"<<",
"Thread",
".",
"new",
"do",
"while",
"job",
"=",
"@queue",
".",
"pop",
"if",
"job",
"==",
":END_OF_WORK",
"break",
"else",
"@values",
".",
"push",
"*",
"job",
"[",
"1",
"]",
",",
"&",
"job",
"[",
"0",
"]",
"end",
"end",
"end",
"end",
"end",
"end"
] | Starts execution of the thread pool.
@note Can be restarted after finalization. | [
"Starts",
"execution",
"of",
"the",
"thread",
"pool",
"."
] | 84102ea0a353e67eef8aceb2c9b0a688e8409724 | https://github.com/nikitachernov/FutureProof/blob/84102ea0a353e67eef8aceb2c9b0a688e8409724/lib/future_proof/thread_pool.rb#L32-L47 | train |
joker1007/proc_to_ast | lib/proc_to_ast.rb | ProcToAst.Parser.parse | def parse(filename, linenum)
@filename, @linenum = filename, linenum
buf = []
File.open(filename, "rb").each_with_index do |line, index|
next if index < linenum - 1
buf << line
begin
return do_parse(buf.join)
rescue ::Parser::SyntaxError
node = trim_and_retry(buf)
return node if node
end
end
fail(::Parser::SyntaxError, 'Unknown error')
end | ruby | def parse(filename, linenum)
@filename, @linenum = filename, linenum
buf = []
File.open(filename, "rb").each_with_index do |line, index|
next if index < linenum - 1
buf << line
begin
return do_parse(buf.join)
rescue ::Parser::SyntaxError
node = trim_and_retry(buf)
return node if node
end
end
fail(::Parser::SyntaxError, 'Unknown error')
end | [
"def",
"parse",
"(",
"filename",
",",
"linenum",
")",
"@filename",
",",
"@linenum",
"=",
"filename",
",",
"linenum",
"buf",
"=",
"[",
"]",
"File",
".",
"open",
"(",
"filename",
",",
"\"rb\"",
")",
".",
"each_with_index",
"do",
"|",
"line",
",",
"index",
"|",
"next",
"if",
"index",
"<",
"linenum",
"-",
"1",
"buf",
"<<",
"line",
"begin",
"return",
"do_parse",
"(",
"buf",
".",
"join",
")",
"rescue",
"::",
"Parser",
"::",
"SyntaxError",
"node",
"=",
"trim_and_retry",
"(",
"buf",
")",
"return",
"node",
"if",
"node",
"end",
"end",
"fail",
"(",
"::",
"Parser",
"::",
"SyntaxError",
",",
"'Unknown error'",
")",
"end"
] | Read file and try parsing
if success parse, find proc AST
@param filename [String] reading file path
@param linenum [Integer] start line number
@return [Parser::AST::Node] Proc AST | [
"Read",
"file",
"and",
"try",
"parsing",
"if",
"success",
"parse",
"find",
"proc",
"AST"
] | 60c95582828edb689d6f701543f8ae1b138139fc | https://github.com/joker1007/proc_to_ast/blob/60c95582828edb689d6f701543f8ae1b138139fc/lib/proc_to_ast.rb#L24-L38 | train |
joker1007/proc_to_ast | lib/proc_to_ast.rb | ProcToAst.Parser.trim_and_retry | def trim_and_retry(buf)
*lines, last = buf
# For inner Array or Hash or Arguments list.
lines << last.gsub(/,\s*$/, "")
do_parse("a(#{lines.join})") # wrap dummy method
rescue ::Parser::SyntaxError
end | ruby | def trim_and_retry(buf)
*lines, last = buf
# For inner Array or Hash or Arguments list.
lines << last.gsub(/,\s*$/, "")
do_parse("a(#{lines.join})") # wrap dummy method
rescue ::Parser::SyntaxError
end | [
"def",
"trim_and_retry",
"(",
"buf",
")",
"*",
"lines",
",",
"last",
"=",
"buf",
"lines",
"<<",
"last",
".",
"gsub",
"(",
"/",
"\\s",
"/",
",",
"\"\"",
")",
"do_parse",
"(",
"\"a(#{lines.join})\"",
")",
"rescue",
"::",
"Parser",
"::",
"SyntaxError",
"end"
] | Remove tail comma and wrap dummy method, and retry parsing
For proc inner Array or Hash | [
"Remove",
"tail",
"comma",
"and",
"wrap",
"dummy",
"method",
"and",
"retry",
"parsing",
"For",
"proc",
"inner",
"Array",
"or",
"Hash"
] | 60c95582828edb689d6f701543f8ae1b138139fc | https://github.com/joker1007/proc_to_ast/blob/60c95582828edb689d6f701543f8ae1b138139fc/lib/proc_to_ast.rb#L59-L66 | train |
brandedcrate/errbit_gitlab_plugin | lib/errbit_gitlab_plugin/issue_tracker.rb | ErrbitGitlabPlugin.IssueTracker.errors | def errors
errs = []
# Make sure that every field is filled out
self.class.fields.except(:project_id).each_with_object({}) do |(field_name, field_options), h|
if options[field_name].blank?
errs << "#{field_options[:label]} must be present"
end
end
# We can only perform the other tests if the necessary values are at least present
return {:base => errs.to_sentence} unless errs.size.zero?
# Check if the given endpoint actually exists
unless gitlab_endpoint_exists?(options[:endpoint])
errs << 'No Gitlab installation was found under the given URL'
return {:base => errs.to_sentence}
end
# Check if a user by the given token exists
unless gitlab_user_exists?(options[:endpoint], options[:api_token])
errs << 'No user with the given API token was found'
return {:base => errs.to_sentence}
end
# Check if there is a project with the given name on the server
unless gitlab_project_id(options[:endpoint], options[:api_token], options[:path_with_namespace])
errs << "A project named '#{options[:path_with_namespace]}' could not be found on the server.
Please make sure to enter it exactly as it appears in your address bar in Gitlab (case sensitive)"
return {:base => errs.to_sentence}
end
{}
end | ruby | def errors
errs = []
# Make sure that every field is filled out
self.class.fields.except(:project_id).each_with_object({}) do |(field_name, field_options), h|
if options[field_name].blank?
errs << "#{field_options[:label]} must be present"
end
end
# We can only perform the other tests if the necessary values are at least present
return {:base => errs.to_sentence} unless errs.size.zero?
# Check if the given endpoint actually exists
unless gitlab_endpoint_exists?(options[:endpoint])
errs << 'No Gitlab installation was found under the given URL'
return {:base => errs.to_sentence}
end
# Check if a user by the given token exists
unless gitlab_user_exists?(options[:endpoint], options[:api_token])
errs << 'No user with the given API token was found'
return {:base => errs.to_sentence}
end
# Check if there is a project with the given name on the server
unless gitlab_project_id(options[:endpoint], options[:api_token], options[:path_with_namespace])
errs << "A project named '#{options[:path_with_namespace]}' could not be found on the server.
Please make sure to enter it exactly as it appears in your address bar in Gitlab (case sensitive)"
return {:base => errs.to_sentence}
end
{}
end | [
"def",
"errors",
"errs",
"=",
"[",
"]",
"self",
".",
"class",
".",
"fields",
".",
"except",
"(",
":project_id",
")",
".",
"each_with_object",
"(",
"{",
"}",
")",
"do",
"|",
"(",
"field_name",
",",
"field_options",
")",
",",
"h",
"|",
"if",
"options",
"[",
"field_name",
"]",
".",
"blank?",
"errs",
"<<",
"\"#{field_options[:label]} must be present\"",
"end",
"end",
"return",
"{",
":base",
"=>",
"errs",
".",
"to_sentence",
"}",
"unless",
"errs",
".",
"size",
".",
"zero?",
"unless",
"gitlab_endpoint_exists?",
"(",
"options",
"[",
":endpoint",
"]",
")",
"errs",
"<<",
"'No Gitlab installation was found under the given URL'",
"return",
"{",
":base",
"=>",
"errs",
".",
"to_sentence",
"}",
"end",
"unless",
"gitlab_user_exists?",
"(",
"options",
"[",
":endpoint",
"]",
",",
"options",
"[",
":api_token",
"]",
")",
"errs",
"<<",
"'No user with the given API token was found'",
"return",
"{",
":base",
"=>",
"errs",
".",
"to_sentence",
"}",
"end",
"unless",
"gitlab_project_id",
"(",
"options",
"[",
":endpoint",
"]",
",",
"options",
"[",
":api_token",
"]",
",",
"options",
"[",
":path_with_namespace",
"]",
")",
"errs",
"<<",
"\"A project named '#{options[:path_with_namespace]}' could not be found on the server. Please make sure to enter it exactly as it appears in your address bar in Gitlab (case sensitive)\"",
"return",
"{",
":base",
"=>",
"errs",
".",
"to_sentence",
"}",
"end",
"{",
"}",
"end"
] | Called to validate user input. Just return a hash of errors if there are any | [
"Called",
"to",
"validate",
"user",
"input",
".",
"Just",
"return",
"a",
"hash",
"of",
"errors",
"if",
"there",
"are",
"any"
] | 22d5af619da4bcbb51b74557176158a6911d04fb | https://github.com/brandedcrate/errbit_gitlab_plugin/blob/22d5af619da4bcbb51b74557176158a6911d04fb/lib/errbit_gitlab_plugin/issue_tracker.rb#L84-L117 | train |
brandedcrate/errbit_gitlab_plugin | lib/errbit_gitlab_plugin/issue_tracker.rb | ErrbitGitlabPlugin.IssueTracker.gitlab_endpoint_exists? | def gitlab_endpoint_exists?(gitlab_url)
with_gitlab(gitlab_url, 'Iamsecret') do |g|
g.user
end
rescue Gitlab::Error::Unauthorized
true
rescue Exception
false
end | ruby | def gitlab_endpoint_exists?(gitlab_url)
with_gitlab(gitlab_url, 'Iamsecret') do |g|
g.user
end
rescue Gitlab::Error::Unauthorized
true
rescue Exception
false
end | [
"def",
"gitlab_endpoint_exists?",
"(",
"gitlab_url",
")",
"with_gitlab",
"(",
"gitlab_url",
",",
"'Iamsecret'",
")",
"do",
"|",
"g",
"|",
"g",
".",
"user",
"end",
"rescue",
"Gitlab",
"::",
"Error",
"::",
"Unauthorized",
"true",
"rescue",
"Exception",
"false",
"end"
] | Checks whether there is a gitlab installation
at the given +gitlab_url+ | [
"Checks",
"whether",
"there",
"is",
"a",
"gitlab",
"installation",
"at",
"the",
"given",
"+",
"gitlab_url",
"+"
] | 22d5af619da4bcbb51b74557176158a6911d04fb | https://github.com/brandedcrate/errbit_gitlab_plugin/blob/22d5af619da4bcbb51b74557176158a6911d04fb/lib/errbit_gitlab_plugin/issue_tracker.rb#L151-L159 | train |
brandedcrate/errbit_gitlab_plugin | lib/errbit_gitlab_plugin/issue_tracker.rb | ErrbitGitlabPlugin.IssueTracker.gitlab_user_exists? | def gitlab_user_exists?(gitlab_url, private_token)
with_gitlab(gitlab_url, private_token) do |g|
g.user
end
true
rescue Gitlab::Error::Unauthorized
false
end | ruby | def gitlab_user_exists?(gitlab_url, private_token)
with_gitlab(gitlab_url, private_token) do |g|
g.user
end
true
rescue Gitlab::Error::Unauthorized
false
end | [
"def",
"gitlab_user_exists?",
"(",
"gitlab_url",
",",
"private_token",
")",
"with_gitlab",
"(",
"gitlab_url",
",",
"private_token",
")",
"do",
"|",
"g",
"|",
"g",
".",
"user",
"end",
"true",
"rescue",
"Gitlab",
"::",
"Error",
"::",
"Unauthorized",
"false",
"end"
] | Checks whether a user with the given +token+ exists
in the gitlab installation located at +gitlab_url+ | [
"Checks",
"whether",
"a",
"user",
"with",
"the",
"given",
"+",
"token",
"+",
"exists",
"in",
"the",
"gitlab",
"installation",
"located",
"at",
"+",
"gitlab_url",
"+"
] | 22d5af619da4bcbb51b74557176158a6911d04fb | https://github.com/brandedcrate/errbit_gitlab_plugin/blob/22d5af619da4bcbb51b74557176158a6911d04fb/lib/errbit_gitlab_plugin/issue_tracker.rb#L165-L173 | train |
brandedcrate/errbit_gitlab_plugin | lib/errbit_gitlab_plugin/issue_tracker.rb | ErrbitGitlabPlugin.IssueTracker.with_gitlab | def with_gitlab(gitlab_url = options[:endpoint], private_token = options[:api_token])
yield Gitlab.client(endpoint: gitlab_endpoint(gitlab_url),
private_token: private_token,
user_agent: 'Errbit User Agent')
end | ruby | def with_gitlab(gitlab_url = options[:endpoint], private_token = options[:api_token])
yield Gitlab.client(endpoint: gitlab_endpoint(gitlab_url),
private_token: private_token,
user_agent: 'Errbit User Agent')
end | [
"def",
"with_gitlab",
"(",
"gitlab_url",
"=",
"options",
"[",
":endpoint",
"]",
",",
"private_token",
"=",
"options",
"[",
":api_token",
"]",
")",
"yield",
"Gitlab",
".",
"client",
"(",
"endpoint",
":",
"gitlab_endpoint",
"(",
"gitlab_url",
")",
",",
"private_token",
":",
"private_token",
",",
"user_agent",
":",
"'Errbit User Agent'",
")",
"end"
] | Connects to the gitlab installation at +gitlab_url+
using the given +private_token+ and executes the given block | [
"Connects",
"to",
"the",
"gitlab",
"installation",
"at",
"+",
"gitlab_url",
"+",
"using",
"the",
"given",
"+",
"private_token",
"+",
"and",
"executes",
"the",
"given",
"block"
] | 22d5af619da4bcbb51b74557176158a6911d04fb | https://github.com/brandedcrate/errbit_gitlab_plugin/blob/22d5af619da4bcbb51b74557176158a6911d04fb/lib/errbit_gitlab_plugin/issue_tracker.rb#L179-L183 | train |
rightscale/right_link | lib/clouds/metadata_writer.rb | RightScale.MetadataWriter.create_full_path | def create_full_path(file_name)
path = full_path(file_name)
FileUtils.mkdir_p(File.dirname(path))
path
end | ruby | def create_full_path(file_name)
path = full_path(file_name)
FileUtils.mkdir_p(File.dirname(path))
path
end | [
"def",
"create_full_path",
"(",
"file_name",
")",
"path",
"=",
"full_path",
"(",
"file_name",
")",
"FileUtils",
".",
"mkdir_p",
"(",
"File",
".",
"dirname",
"(",
"path",
")",
")",
"path",
"end"
] | Creates the parent directory for the full path of generated file.
=== Parameters
file_name(String):: output file name without extension
=== Return
result(String):: full path of generated file | [
"Creates",
"the",
"parent",
"directory",
"for",
"the",
"full",
"path",
"of",
"generated",
"file",
"."
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/clouds/metadata_writer.rb#L95-L99 | train |
rightscale/right_link | lib/clouds/metadata_writer.rb | RightScale.MetadataWriter.write_file | def write_file(metadata)
File.open(create_full_path(@file_name_prefix), "w", DEFAULT_FILE_MODE) { |f| f.write(metadata.to_s) }
end | ruby | def write_file(metadata)
File.open(create_full_path(@file_name_prefix), "w", DEFAULT_FILE_MODE) { |f| f.write(metadata.to_s) }
end | [
"def",
"write_file",
"(",
"metadata",
")",
"File",
".",
"open",
"(",
"create_full_path",
"(",
"@file_name_prefix",
")",
",",
"\"w\"",
",",
"DEFAULT_FILE_MODE",
")",
"{",
"|",
"f",
"|",
"f",
".",
"write",
"(",
"metadata",
".",
"to_s",
")",
"}",
"end"
] | Writes given metadata to file.
=== Parameters
metadata(Hash):: Hash-like metadata to write
subpath(Array|String):: subpath if deeper than root or nil
=== Return
always true | [
"Writes",
"given",
"metadata",
"to",
"file",
"."
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/clouds/metadata_writer.rb#L110-L112 | train |
rightscale/right_link | lib/clouds/cloud.rb | RightScale.Cloud.write_metadata | def write_metadata(kind = WILDCARD)
options = @options.dup
kind = kind.to_sym
if kind == WILDCARD || kind == :user_metadata
# Both "blue-skies" cloud and "wrap instance" behave the same way, they lay down a
# file in a predefined location (/var/spool/rightscale/user-data.txt on linux,
# C:\ProgramData\RightScale\spool\rightscale\user-data.txt on windows. In both
# cases this userdata has *lower* precedence than cloud data. On a start/stop
# action where userdata is updated, we want the NEW userdata, not the old. So
# if cloud-based values exists, than we always use those.
api_source = RightScale::MetadataSources::RightScaleApiMetadataSource.new(options)
cloud_userdata_raw = ""
if api_source.source_exists?
extra_userdata_raw = api_source.get()
if (name == "azure")
# Azure is a special case -- we don't want to run the cloud userdata fetcher again
# as we can't update userdata anyways and it will currently fail as written
extra_userdata_raw = get_updated_userdata(extra_userdata_raw)
cloud_userdata_raw = extra_userdata_raw
elsif (name == "rackspace")
# Rackspace is another type of special case, for different reasons.
# The "wait_for_instance_ready" function on rackspace will get stuck in an
# infinite loops waiting for the userdata file to appear in the wrap instance
# or blue-skies cases. Since we don't support start/stop on rackspace anyways
# we can just skip the whole fetching of updated userdata to avoid this
# infinite loop scenario, instead just always using the blue-skies/wrap
# data that's on disk. The downside is that you better delete that data
# before a rebundle or it won't work. See rackspace/wait_for_instance_ready.rb
# counterpart code as well
cloud_userdata_raw = extra_userdata_raw
else
cloud_userdata_raw = userdata_raw
unless cloud_userdata_raw =~ /RS_rn_id/i
cloud_userdata_raw = extra_userdata_raw
end
end
else
cloud_userdata_raw = userdata_raw
end
cloud_userdata = parse_userdata(cloud_userdata_raw)
# Raw userdata is a special exception and gets its own writer
raw_writer = metadata_writers(:user_metadata).find { |writer| writer.kind_of?(RightScale::MetadataWriters::RawMetadataWriter) }
raw_writer.write(cloud_userdata_raw)
unless cloud_userdata.empty?
metadata_writers(:user_metadata).each { |writer| writer.write(cloud_userdata) }
end
end
if kind == WILDCARD || kind == :cloud_metadata
cloud_metadata = metadata
unless cloud_metadata.empty?
metadata_writers(:cloud_metadata).each { |writer| writer.write(cloud_metadata) }
end
end
return ActionResult.new
rescue Exception => e
return ActionResult.new(:exitstatus => 1, :error => "ERROR: #{e.message}", :exception => e)
ensure
finish()
end | ruby | def write_metadata(kind = WILDCARD)
options = @options.dup
kind = kind.to_sym
if kind == WILDCARD || kind == :user_metadata
# Both "blue-skies" cloud and "wrap instance" behave the same way, they lay down a
# file in a predefined location (/var/spool/rightscale/user-data.txt on linux,
# C:\ProgramData\RightScale\spool\rightscale\user-data.txt on windows. In both
# cases this userdata has *lower* precedence than cloud data. On a start/stop
# action where userdata is updated, we want the NEW userdata, not the old. So
# if cloud-based values exists, than we always use those.
api_source = RightScale::MetadataSources::RightScaleApiMetadataSource.new(options)
cloud_userdata_raw = ""
if api_source.source_exists?
extra_userdata_raw = api_source.get()
if (name == "azure")
# Azure is a special case -- we don't want to run the cloud userdata fetcher again
# as we can't update userdata anyways and it will currently fail as written
extra_userdata_raw = get_updated_userdata(extra_userdata_raw)
cloud_userdata_raw = extra_userdata_raw
elsif (name == "rackspace")
# Rackspace is another type of special case, for different reasons.
# The "wait_for_instance_ready" function on rackspace will get stuck in an
# infinite loops waiting for the userdata file to appear in the wrap instance
# or blue-skies cases. Since we don't support start/stop on rackspace anyways
# we can just skip the whole fetching of updated userdata to avoid this
# infinite loop scenario, instead just always using the blue-skies/wrap
# data that's on disk. The downside is that you better delete that data
# before a rebundle or it won't work. See rackspace/wait_for_instance_ready.rb
# counterpart code as well
cloud_userdata_raw = extra_userdata_raw
else
cloud_userdata_raw = userdata_raw
unless cloud_userdata_raw =~ /RS_rn_id/i
cloud_userdata_raw = extra_userdata_raw
end
end
else
cloud_userdata_raw = userdata_raw
end
cloud_userdata = parse_userdata(cloud_userdata_raw)
# Raw userdata is a special exception and gets its own writer
raw_writer = metadata_writers(:user_metadata).find { |writer| writer.kind_of?(RightScale::MetadataWriters::RawMetadataWriter) }
raw_writer.write(cloud_userdata_raw)
unless cloud_userdata.empty?
metadata_writers(:user_metadata).each { |writer| writer.write(cloud_userdata) }
end
end
if kind == WILDCARD || kind == :cloud_metadata
cloud_metadata = metadata
unless cloud_metadata.empty?
metadata_writers(:cloud_metadata).each { |writer| writer.write(cloud_metadata) }
end
end
return ActionResult.new
rescue Exception => e
return ActionResult.new(:exitstatus => 1, :error => "ERROR: #{e.message}", :exception => e)
ensure
finish()
end | [
"def",
"write_metadata",
"(",
"kind",
"=",
"WILDCARD",
")",
"options",
"=",
"@options",
".",
"dup",
"kind",
"=",
"kind",
".",
"to_sym",
"if",
"kind",
"==",
"WILDCARD",
"||",
"kind",
"==",
":user_metadata",
"api_source",
"=",
"RightScale",
"::",
"MetadataSources",
"::",
"RightScaleApiMetadataSource",
".",
"new",
"(",
"options",
")",
"cloud_userdata_raw",
"=",
"\"\"",
"if",
"api_source",
".",
"source_exists?",
"extra_userdata_raw",
"=",
"api_source",
".",
"get",
"(",
")",
"if",
"(",
"name",
"==",
"\"azure\"",
")",
"extra_userdata_raw",
"=",
"get_updated_userdata",
"(",
"extra_userdata_raw",
")",
"cloud_userdata_raw",
"=",
"extra_userdata_raw",
"elsif",
"(",
"name",
"==",
"\"rackspace\"",
")",
"cloud_userdata_raw",
"=",
"extra_userdata_raw",
"else",
"cloud_userdata_raw",
"=",
"userdata_raw",
"unless",
"cloud_userdata_raw",
"=~",
"/",
"/i",
"cloud_userdata_raw",
"=",
"extra_userdata_raw",
"end",
"end",
"else",
"cloud_userdata_raw",
"=",
"userdata_raw",
"end",
"cloud_userdata",
"=",
"parse_userdata",
"(",
"cloud_userdata_raw",
")",
"raw_writer",
"=",
"metadata_writers",
"(",
":user_metadata",
")",
".",
"find",
"{",
"|",
"writer",
"|",
"writer",
".",
"kind_of?",
"(",
"RightScale",
"::",
"MetadataWriters",
"::",
"RawMetadataWriter",
")",
"}",
"raw_writer",
".",
"write",
"(",
"cloud_userdata_raw",
")",
"unless",
"cloud_userdata",
".",
"empty?",
"metadata_writers",
"(",
":user_metadata",
")",
".",
"each",
"{",
"|",
"writer",
"|",
"writer",
".",
"write",
"(",
"cloud_userdata",
")",
"}",
"end",
"end",
"if",
"kind",
"==",
"WILDCARD",
"||",
"kind",
"==",
":cloud_metadata",
"cloud_metadata",
"=",
"metadata",
"unless",
"cloud_metadata",
".",
"empty?",
"metadata_writers",
"(",
":cloud_metadata",
")",
".",
"each",
"{",
"|",
"writer",
"|",
"writer",
".",
"write",
"(",
"cloud_metadata",
")",
"}",
"end",
"end",
"return",
"ActionResult",
".",
"new",
"rescue",
"Exception",
"=>",
"e",
"return",
"ActionResult",
".",
"new",
"(",
":exitstatus",
"=>",
"1",
",",
":error",
"=>",
"\"ERROR: #{e.message}\"",
",",
":exception",
"=>",
"e",
")",
"ensure",
"finish",
"(",
")",
"end"
] | Queries and writes current metadata to file.
=== Parameters
kind(Symbol):: kind of metadata must be one of [:cloud_metadata, :user_metadata, WILDCARD]
=== Return
result(ActionResult):: action result | [
"Queries",
"and",
"writes",
"current",
"metadata",
"to",
"file",
"."
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/clouds/cloud.rb#L149-L212 | train |
rightscale/right_link | lib/clouds/cloud.rb | RightScale.Cloud.clear_state | def clear_state
output_dir_paths = []
[:user_metadata, :cloud_metadata].each do |kind|
output_dir_paths |= metadata_writers(kind).map { |w| w.output_dir_path }
end
last_exception = nil
output_dir_paths.each do |output_dir_path|
begin
FileUtils.rm_rf(output_dir_path) if File.directory?(output_dir_path)
rescue Exception => e
last_exception = e
end
end
fail(last_exception.message) if last_exception
return ActionResult.new
rescue Exception => e
return ActionResult.new(:exitstatus => 1, :error => "ERROR: #{e.message}", :exception => e)
end | ruby | def clear_state
output_dir_paths = []
[:user_metadata, :cloud_metadata].each do |kind|
output_dir_paths |= metadata_writers(kind).map { |w| w.output_dir_path }
end
last_exception = nil
output_dir_paths.each do |output_dir_path|
begin
FileUtils.rm_rf(output_dir_path) if File.directory?(output_dir_path)
rescue Exception => e
last_exception = e
end
end
fail(last_exception.message) if last_exception
return ActionResult.new
rescue Exception => e
return ActionResult.new(:exitstatus => 1, :error => "ERROR: #{e.message}", :exception => e)
end | [
"def",
"clear_state",
"output_dir_paths",
"=",
"[",
"]",
"[",
":user_metadata",
",",
":cloud_metadata",
"]",
".",
"each",
"do",
"|",
"kind",
"|",
"output_dir_paths",
"|=",
"metadata_writers",
"(",
"kind",
")",
".",
"map",
"{",
"|",
"w",
"|",
"w",
".",
"output_dir_path",
"}",
"end",
"last_exception",
"=",
"nil",
"output_dir_paths",
".",
"each",
"do",
"|",
"output_dir_path",
"|",
"begin",
"FileUtils",
".",
"rm_rf",
"(",
"output_dir_path",
")",
"if",
"File",
".",
"directory?",
"(",
"output_dir_path",
")",
"rescue",
"Exception",
"=>",
"e",
"last_exception",
"=",
"e",
"end",
"end",
"fail",
"(",
"last_exception",
".",
"message",
")",
"if",
"last_exception",
"return",
"ActionResult",
".",
"new",
"rescue",
"Exception",
"=>",
"e",
"return",
"ActionResult",
".",
"new",
"(",
":exitstatus",
"=>",
"1",
",",
":error",
"=>",
"\"ERROR: #{e.message}\"",
",",
":exception",
"=>",
"e",
")",
"end"
] | Attempts to clear any files generated by writers.
=== Return
always true
=== Raise
CloudError:: on failure to clean state | [
"Attempts",
"to",
"clear",
"any",
"files",
"generated",
"by",
"writers",
"."
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/clouds/cloud.rb#L228-L246 | train |
rightscale/right_link | lib/clouds/cloud.rb | RightScale.Cloud.metadata_writers | def metadata_writers(kind)
return @metadata_writers[kind] if @metadata_writers && @metadata_writers[kind]
@metadata_writers ||= {}
@metadata_writers[kind] ||= []
options = @options.dup
options[:kind] = kind
if kind == :user_metadata
options[:formatted_path_prefix] = "RS_"
options[:output_dir_path] ||= RightScale::AgentConfig.cloud_state_dir
options[:file_name_prefix] = "user-data"
options[:generation_command] = nil
elsif kind == :cloud_metadata
options[:formatted_path_prefix] = "#{abbreviation.upcase}_"
options[:output_dir_path] ||= RightScale::AgentConfig.cloud_state_dir
options[:file_name_prefix] = "meta-data"
options[:generation_command] = cloud_metadata_generation_command if generates_metadata_cache?
end
begin
writers_dir_path = File.join(File.dirname(__FILE__), 'metadata_writers')
# dynamically register all clouds using the script name as cloud name.
pattern = File.join(writers_dir_path, '*.rb')
Dir[pattern].each do |writer_script_path|
writer_name = File.basename(writer_script_path, '.rb')
require writer_script_path
writer_class_name = writer_name.split(/[_ ]/).map {|w| w.capitalize}.join
writer_class = eval("RightScale::MetadataWriters::#{writer_class_name}")
@metadata_writers[kind] << writer_class.new(options)
end
end
@metadata_writers[kind]
end | ruby | def metadata_writers(kind)
return @metadata_writers[kind] if @metadata_writers && @metadata_writers[kind]
@metadata_writers ||= {}
@metadata_writers[kind] ||= []
options = @options.dup
options[:kind] = kind
if kind == :user_metadata
options[:formatted_path_prefix] = "RS_"
options[:output_dir_path] ||= RightScale::AgentConfig.cloud_state_dir
options[:file_name_prefix] = "user-data"
options[:generation_command] = nil
elsif kind == :cloud_metadata
options[:formatted_path_prefix] = "#{abbreviation.upcase}_"
options[:output_dir_path] ||= RightScale::AgentConfig.cloud_state_dir
options[:file_name_prefix] = "meta-data"
options[:generation_command] = cloud_metadata_generation_command if generates_metadata_cache?
end
begin
writers_dir_path = File.join(File.dirname(__FILE__), 'metadata_writers')
# dynamically register all clouds using the script name as cloud name.
pattern = File.join(writers_dir_path, '*.rb')
Dir[pattern].each do |writer_script_path|
writer_name = File.basename(writer_script_path, '.rb')
require writer_script_path
writer_class_name = writer_name.split(/[_ ]/).map {|w| w.capitalize}.join
writer_class = eval("RightScale::MetadataWriters::#{writer_class_name}")
@metadata_writers[kind] << writer_class.new(options)
end
end
@metadata_writers[kind]
end | [
"def",
"metadata_writers",
"(",
"kind",
")",
"return",
"@metadata_writers",
"[",
"kind",
"]",
"if",
"@metadata_writers",
"&&",
"@metadata_writers",
"[",
"kind",
"]",
"@metadata_writers",
"||=",
"{",
"}",
"@metadata_writers",
"[",
"kind",
"]",
"||=",
"[",
"]",
"options",
"=",
"@options",
".",
"dup",
"options",
"[",
":kind",
"]",
"=",
"kind",
"if",
"kind",
"==",
":user_metadata",
"options",
"[",
":formatted_path_prefix",
"]",
"=",
"\"RS_\"",
"options",
"[",
":output_dir_path",
"]",
"||=",
"RightScale",
"::",
"AgentConfig",
".",
"cloud_state_dir",
"options",
"[",
":file_name_prefix",
"]",
"=",
"\"user-data\"",
"options",
"[",
":generation_command",
"]",
"=",
"nil",
"elsif",
"kind",
"==",
":cloud_metadata",
"options",
"[",
":formatted_path_prefix",
"]",
"=",
"\"#{abbreviation.upcase}_\"",
"options",
"[",
":output_dir_path",
"]",
"||=",
"RightScale",
"::",
"AgentConfig",
".",
"cloud_state_dir",
"options",
"[",
":file_name_prefix",
"]",
"=",
"\"meta-data\"",
"options",
"[",
":generation_command",
"]",
"=",
"cloud_metadata_generation_command",
"if",
"generates_metadata_cache?",
"end",
"begin",
"writers_dir_path",
"=",
"File",
".",
"join",
"(",
"File",
".",
"dirname",
"(",
"__FILE__",
")",
",",
"'metadata_writers'",
")",
"pattern",
"=",
"File",
".",
"join",
"(",
"writers_dir_path",
",",
"'*.rb'",
")",
"Dir",
"[",
"pattern",
"]",
".",
"each",
"do",
"|",
"writer_script_path",
"|",
"writer_name",
"=",
"File",
".",
"basename",
"(",
"writer_script_path",
",",
"'.rb'",
")",
"require",
"writer_script_path",
"writer_class_name",
"=",
"writer_name",
".",
"split",
"(",
"/",
"/",
")",
".",
"map",
"{",
"|",
"w",
"|",
"w",
".",
"capitalize",
"}",
".",
"join",
"writer_class",
"=",
"eval",
"(",
"\"RightScale::MetadataWriters::#{writer_class_name}\"",
")",
"@metadata_writers",
"[",
"kind",
"]",
"<<",
"writer_class",
".",
"new",
"(",
"options",
")",
"end",
"end",
"@metadata_writers",
"[",
"kind",
"]",
"end"
] | Gets the option given by path, if it exists.
=== Parameters
kind(Symbol):: :user_metadata or :cloud_metadata
=== Return
result(Array(MetadataWriter)):: responds to write | [
"Gets",
"the",
"option",
"given",
"by",
"path",
"if",
"it",
"exists",
"."
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/clouds/cloud.rb#L254-L287 | train |
rightscale/right_link | lib/clouds/cloud.rb | RightScale.Cloud.cloud_metadata_generation_command | def cloud_metadata_generation_command
ruby_path = File.normalize_path(AgentConfig.ruby_cmd)
rs_cloud_path = File.normalize_path(Gem.bin_path('right_link', 'cloud'))
return "#{ruby_path} #{rs_cloud_path} --action write_cloud_metadata"
end | ruby | def cloud_metadata_generation_command
ruby_path = File.normalize_path(AgentConfig.ruby_cmd)
rs_cloud_path = File.normalize_path(Gem.bin_path('right_link', 'cloud'))
return "#{ruby_path} #{rs_cloud_path} --action write_cloud_metadata"
end | [
"def",
"cloud_metadata_generation_command",
"ruby_path",
"=",
"File",
".",
"normalize_path",
"(",
"AgentConfig",
".",
"ruby_cmd",
")",
"rs_cloud_path",
"=",
"File",
".",
"normalize_path",
"(",
"Gem",
".",
"bin_path",
"(",
"'right_link'",
",",
"'cloud'",
")",
")",
"return",
"\"#{ruby_path} #{rs_cloud_path} --action write_cloud_metadata\"",
"end"
] | Assembles the command line needed to regenerate cloud metadata on demand. | [
"Assembles",
"the",
"command",
"line",
"needed",
"to",
"regenerate",
"cloud",
"metadata",
"on",
"demand",
"."
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/clouds/cloud.rb#L298-L302 | train |
rightscale/right_link | lib/clouds/cloud.rb | RightScale.Cloud.relative_to_script_path | def relative_to_script_path(path)
path = path.gsub("\\", '/')
unless path == File.expand_path(path)
path = File.normalize_path(File.join(File.dirname(@script_path), path))
end
path
end | ruby | def relative_to_script_path(path)
path = path.gsub("\\", '/')
unless path == File.expand_path(path)
path = File.normalize_path(File.join(File.dirname(@script_path), path))
end
path
end | [
"def",
"relative_to_script_path",
"(",
"path",
")",
"path",
"=",
"path",
".",
"gsub",
"(",
"\"\\\\\"",
",",
"'/'",
")",
"unless",
"path",
"==",
"File",
".",
"expand_path",
"(",
"path",
")",
"path",
"=",
"File",
".",
"normalize_path",
"(",
"File",
".",
"join",
"(",
"File",
".",
"dirname",
"(",
"@script_path",
")",
",",
"path",
")",
")",
"end",
"path",
"end"
] | make the given path relative to this cloud's DSL script path only if the
path is not already absolute.
=== Parameters
path(String):: absolute or relative path
=== Return
result(String):: absolute path | [
"make",
"the",
"given",
"path",
"relative",
"to",
"this",
"cloud",
"s",
"DSL",
"script",
"path",
"only",
"if",
"the",
"path",
"is",
"not",
"already",
"absolute",
"."
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/clouds/cloud.rb#L343-L349 | train |
rightscale/right_link | lib/instance/cook/cook_state.rb | RightScale.CookState.dev_log_level | def dev_log_level
if value = tag_value(LOG_LEVEL_TAG)
value = value.downcase.to_sym
value = nil unless [:debug, :info, :warn, :error, :fatal].include?(value)
end
value
end | ruby | def dev_log_level
if value = tag_value(LOG_LEVEL_TAG)
value = value.downcase.to_sym
value = nil unless [:debug, :info, :warn, :error, :fatal].include?(value)
end
value
end | [
"def",
"dev_log_level",
"if",
"value",
"=",
"tag_value",
"(",
"LOG_LEVEL_TAG",
")",
"value",
"=",
"value",
".",
"downcase",
".",
"to_sym",
"value",
"=",
"nil",
"unless",
"[",
":debug",
",",
":info",
",",
":warn",
",",
":error",
",",
":fatal",
"]",
".",
"include?",
"(",
"value",
")",
"end",
"value",
"end"
] | Determines the developer log level, if any, which forces and supercedes
all other log level configurations.
=== Return
level(Token):: developer log level or nil | [
"Determines",
"the",
"developer",
"log",
"level",
"if",
"any",
"which",
"forces",
"and",
"supercedes",
"all",
"other",
"log",
"level",
"configurations",
"."
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/cook_state.rb#L120-L126 | train |
rightscale/right_link | lib/instance/cook/cook_state.rb | RightScale.CookState.use_cookbooks_path? | def use_cookbooks_path?
res = !!(paths = cookbooks_path)
return false unless res
paths.each do |path|
res = path && File.directory?(path) && Dir.entries(path) != ['.', '..']
break unless res
end
res
end | ruby | def use_cookbooks_path?
res = !!(paths = cookbooks_path)
return false unless res
paths.each do |path|
res = path && File.directory?(path) && Dir.entries(path) != ['.', '..']
break unless res
end
res
end | [
"def",
"use_cookbooks_path?",
"res",
"=",
"!",
"!",
"(",
"paths",
"=",
"cookbooks_path",
")",
"return",
"false",
"unless",
"res",
"paths",
".",
"each",
"do",
"|",
"path",
"|",
"res",
"=",
"path",
"&&",
"File",
".",
"directory?",
"(",
"path",
")",
"&&",
"Dir",
".",
"entries",
"(",
"path",
")",
"!=",
"[",
"'.'",
",",
"'..'",
"]",
"break",
"unless",
"res",
"end",
"res",
"end"
] | Whether dev cookbooks path should be used instead of standard
cookbooks repositories location
True if in dev mode and all dev cookbooks repos directories are not empty
=== Return
true:: If dev cookbooks repositories path should be used
false:: Otherwise | [
"Whether",
"dev",
"cookbooks",
"path",
"should",
"be",
"used",
"instead",
"of",
"standard",
"cookbooks",
"repositories",
"location",
"True",
"if",
"in",
"dev",
"mode",
"and",
"all",
"dev",
"cookbooks",
"repos",
"directories",
"are",
"not",
"empty"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/cook_state.rb#L154-L162 | train |
rightscale/right_link | lib/instance/cook/cook_state.rb | RightScale.CookState.update | def update(state_to_merge, overrides = {})
# only merge state if state to be merged has values
@startup_tags = state_to_merge.startup_tags if state_to_merge.respond_to?(:startup_tags)
@reboot = state_to_merge.reboot? if state_to_merge.respond_to?(:reboot?)
@log_level = state_to_merge.log_level if state_to_merge.respond_to?(:log_level)
if state_to_merge.respond_to?(:log_file) && state_to_merge.respond_to?(:value)
@log_file = state_to_merge.log_file(state_to_merge.value)
end
@startup_tags = overrides[:startup_tags] if overrides.has_key?(:startup_tags)
@reboot = overrides[:reboot] if overrides.has_key?(:reboot)
@log_file = overrides[:log_file] if overrides.has_key?(:log_file)
# check the log level again after the startup_tags have been updated or
# overridden.
if overrides.has_key?(:log_level)
@log_level = overrides[:log_level]
elsif tagged_log_level = dev_log_level
@log_level = tagged_log_level
end
save_state
true
end | ruby | def update(state_to_merge, overrides = {})
# only merge state if state to be merged has values
@startup_tags = state_to_merge.startup_tags if state_to_merge.respond_to?(:startup_tags)
@reboot = state_to_merge.reboot? if state_to_merge.respond_to?(:reboot?)
@log_level = state_to_merge.log_level if state_to_merge.respond_to?(:log_level)
if state_to_merge.respond_to?(:log_file) && state_to_merge.respond_to?(:value)
@log_file = state_to_merge.log_file(state_to_merge.value)
end
@startup_tags = overrides[:startup_tags] if overrides.has_key?(:startup_tags)
@reboot = overrides[:reboot] if overrides.has_key?(:reboot)
@log_file = overrides[:log_file] if overrides.has_key?(:log_file)
# check the log level again after the startup_tags have been updated or
# overridden.
if overrides.has_key?(:log_level)
@log_level = overrides[:log_level]
elsif tagged_log_level = dev_log_level
@log_level = tagged_log_level
end
save_state
true
end | [
"def",
"update",
"(",
"state_to_merge",
",",
"overrides",
"=",
"{",
"}",
")",
"@startup_tags",
"=",
"state_to_merge",
".",
"startup_tags",
"if",
"state_to_merge",
".",
"respond_to?",
"(",
":startup_tags",
")",
"@reboot",
"=",
"state_to_merge",
".",
"reboot?",
"if",
"state_to_merge",
".",
"respond_to?",
"(",
":reboot?",
")",
"@log_level",
"=",
"state_to_merge",
".",
"log_level",
"if",
"state_to_merge",
".",
"respond_to?",
"(",
":log_level",
")",
"if",
"state_to_merge",
".",
"respond_to?",
"(",
":log_file",
")",
"&&",
"state_to_merge",
".",
"respond_to?",
"(",
":value",
")",
"@log_file",
"=",
"state_to_merge",
".",
"log_file",
"(",
"state_to_merge",
".",
"value",
")",
"end",
"@startup_tags",
"=",
"overrides",
"[",
":startup_tags",
"]",
"if",
"overrides",
".",
"has_key?",
"(",
":startup_tags",
")",
"@reboot",
"=",
"overrides",
"[",
":reboot",
"]",
"if",
"overrides",
".",
"has_key?",
"(",
":reboot",
")",
"@log_file",
"=",
"overrides",
"[",
":log_file",
"]",
"if",
"overrides",
".",
"has_key?",
"(",
":log_file",
")",
"if",
"overrides",
".",
"has_key?",
"(",
":log_level",
")",
"@log_level",
"=",
"overrides",
"[",
":log_level",
"]",
"elsif",
"tagged_log_level",
"=",
"dev_log_level",
"@log_level",
"=",
"tagged_log_level",
"end",
"save_state",
"true",
"end"
] | Re-initialize then merge given state
=== Parameters
state_to_merge(RightScale::InstanceState):: InstanceState to be passed on to Cook
overrides(Hash):: Hash keyed by state name that will override state_to_merge
=== Return
true:: Always | [
"Re",
"-",
"initialize",
"then",
"merge",
"given",
"state"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/cook_state.rb#L209-L233 | train |
rightscale/right_link | lib/instance/cook/cook_state.rb | RightScale.CookState.save_state | def save_state
# start will al state to be saved
state_to_save = { 'startup_tags' => startup_tags,
'reboot' => reboot?,
'log_level' => log_level }
# only save a log file one is defined
if log_file
state_to_save['log_file'] = log_file
end
# only save persist the fact we downloaded cookbooks if we are in dev mode
if download_once?
state_to_save['has_downloaded_cookbooks'] = has_downloaded_cookbooks?
end
RightScale::JsonUtilities::write_json(RightScale::CookState::STATE_FILE, state_to_save)
true
end | ruby | def save_state
# start will al state to be saved
state_to_save = { 'startup_tags' => startup_tags,
'reboot' => reboot?,
'log_level' => log_level }
# only save a log file one is defined
if log_file
state_to_save['log_file'] = log_file
end
# only save persist the fact we downloaded cookbooks if we are in dev mode
if download_once?
state_to_save['has_downloaded_cookbooks'] = has_downloaded_cookbooks?
end
RightScale::JsonUtilities::write_json(RightScale::CookState::STATE_FILE, state_to_save)
true
end | [
"def",
"save_state",
"state_to_save",
"=",
"{",
"'startup_tags'",
"=>",
"startup_tags",
",",
"'reboot'",
"=>",
"reboot?",
",",
"'log_level'",
"=>",
"log_level",
"}",
"if",
"log_file",
"state_to_save",
"[",
"'log_file'",
"]",
"=",
"log_file",
"end",
"if",
"download_once?",
"state_to_save",
"[",
"'has_downloaded_cookbooks'",
"]",
"=",
"has_downloaded_cookbooks?",
"end",
"RightScale",
"::",
"JsonUtilities",
"::",
"write_json",
"(",
"RightScale",
"::",
"CookState",
"::",
"STATE_FILE",
",",
"state_to_save",
")",
"true",
"end"
] | Save dev state to file
=== Return
true:: Always return true | [
"Save",
"dev",
"state",
"to",
"file"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/cook_state.rb#L255-L273 | train |
rightscale/right_link | lib/instance/cook/cook_state.rb | RightScale.CookState.load_state | def load_state
if File.file?(STATE_FILE)
state = RightScale::JsonUtilities::read_json(STATE_FILE)
@log_level = state['log_level'] || Logger::INFO
Log.info("Initializing CookState from #{STATE_FILE} with #{state.inspect}") if @log_level == Logger::DEBUG
@has_downloaded_cookbooks = state['has_downloaded_cookbooks']
@startup_tags = state['startup_tags'] || []
@reboot = state['reboot']
@log_file = state['log_file'] # nil if not in state loaded from disk
end
true
end | ruby | def load_state
if File.file?(STATE_FILE)
state = RightScale::JsonUtilities::read_json(STATE_FILE)
@log_level = state['log_level'] || Logger::INFO
Log.info("Initializing CookState from #{STATE_FILE} with #{state.inspect}") if @log_level == Logger::DEBUG
@has_downloaded_cookbooks = state['has_downloaded_cookbooks']
@startup_tags = state['startup_tags'] || []
@reboot = state['reboot']
@log_file = state['log_file'] # nil if not in state loaded from disk
end
true
end | [
"def",
"load_state",
"if",
"File",
".",
"file?",
"(",
"STATE_FILE",
")",
"state",
"=",
"RightScale",
"::",
"JsonUtilities",
"::",
"read_json",
"(",
"STATE_FILE",
")",
"@log_level",
"=",
"state",
"[",
"'log_level'",
"]",
"||",
"Logger",
"::",
"INFO",
"Log",
".",
"info",
"(",
"\"Initializing CookState from #{STATE_FILE} with #{state.inspect}\"",
")",
"if",
"@log_level",
"==",
"Logger",
"::",
"DEBUG",
"@has_downloaded_cookbooks",
"=",
"state",
"[",
"'has_downloaded_cookbooks'",
"]",
"@startup_tags",
"=",
"state",
"[",
"'startup_tags'",
"]",
"||",
"[",
"]",
"@reboot",
"=",
"state",
"[",
"'reboot'",
"]",
"@log_file",
"=",
"state",
"[",
"'log_file'",
"]",
"end",
"true",
"end"
] | load dev state from disk
=== Return
true:: Always return true | [
"load",
"dev",
"state",
"from",
"disk"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/cook_state.rb#L279-L291 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.