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 | lib/clouds/cloud_factory.rb | RightScale.CloudFactory.register | def register(cloud_name, cloud_script_path)
cloud_script_path = File.normalize_path(cloud_script_path)
registered_type(cloud_name.to_s, cloud_script_path)
true
end | ruby | def register(cloud_name, cloud_script_path)
cloud_script_path = File.normalize_path(cloud_script_path)
registered_type(cloud_name.to_s, cloud_script_path)
true
end | [
"def",
"register",
"(",
"cloud_name",
",",
"cloud_script_path",
")",
"cloud_script_path",
"=",
"File",
".",
"normalize_path",
"(",
"cloud_script_path",
")",
"registered_type",
"(",
"cloud_name",
".",
"to_s",
",",
"cloud_script_path",
")",
"true",
"end"
] | Registry method for a dynamic metadata type.
=== Parameters
cloud_name(String):: name of one or more clouds (which may include DEFAULT_CLOUD) that use the given type
cloud_script_path(String):: path to script used to describe cloud on creation
=== Return
always true | [
"Registry",
"method",
"for",
"a",
"dynamic",
"metadata",
"type",
"."
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/clouds/cloud_factory.rb#L47-L51 | train |
rightscale/right_link | lib/clouds/cloud_factory.rb | RightScale.CloudFactory.registered_script_path | def registered_script_path(cloud_name)
cloud_script_path = registered_type(cloud_name)
raise UnknownCloud.new("Unknown cloud: #{cloud_name}") unless cloud_script_path
return cloud_script_path
end | ruby | def registered_script_path(cloud_name)
cloud_script_path = registered_type(cloud_name)
raise UnknownCloud.new("Unknown cloud: #{cloud_name}") unless cloud_script_path
return cloud_script_path
end | [
"def",
"registered_script_path",
"(",
"cloud_name",
")",
"cloud_script_path",
"=",
"registered_type",
"(",
"cloud_name",
")",
"raise",
"UnknownCloud",
".",
"new",
"(",
"\"Unknown cloud: #{cloud_name}\"",
")",
"unless",
"cloud_script_path",
"return",
"cloud_script_path",
"end"
] | Gets the path to the script describing a cloud.
=== Parameters
cloud_name(String):: a registered_type cloud name
=== Return
cloud_script_path(String):: path to script used to describe cloud on creation
=== Raise
UnknownCloud:: on error | [
"Gets",
"the",
"path",
"to",
"the",
"script",
"describing",
"a",
"cloud",
"."
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/clouds/cloud_factory.rb#L73-L77 | train |
rightscale/right_link | lib/clouds/cloud_factory.rb | RightScale.CloudFactory.create | def create(cloud_name, options)
raise ArgumentError.new("cloud_name is required") if cloud_name.to_s.empty?
raise ArgumentError.new("options[:logger] is required") unless logger = options[:logger]
raise UnknownCloud.new("No cloud definitions available.") unless @names_to_script_paths
cloud_name = cloud_name.to_sym
cloud_name = default_cloud_name if UNKNOWN_CLOUD_NAME == cloud_name
raise UnknownCloud.new("Unable to determine a default cloud") if UNKNOWN_CLOUD_NAME == cloud_name
cloud_script_path = registered_script_path(cloud_name)
options = options.dup
options[:name] ||= cloud_name.to_s
options[:script_path] = cloud_script_path
cloud = nil
begin
require cloud_script_path
cloud_classname = cloud_name.to_s.capitalize
cloud_class = eval("RightScale::Clouds::#{cloud_classname}")
cloud = cloud_class.new(options)
rescue LoadError => e
raise ArgumentError, "Could not load Cloud class for #{cloud_name}, #{e}"
end
extend_cloud_by_scripts(cloud, logger)
return cloud
end | ruby | def create(cloud_name, options)
raise ArgumentError.new("cloud_name is required") if cloud_name.to_s.empty?
raise ArgumentError.new("options[:logger] is required") unless logger = options[:logger]
raise UnknownCloud.new("No cloud definitions available.") unless @names_to_script_paths
cloud_name = cloud_name.to_sym
cloud_name = default_cloud_name if UNKNOWN_CLOUD_NAME == cloud_name
raise UnknownCloud.new("Unable to determine a default cloud") if UNKNOWN_CLOUD_NAME == cloud_name
cloud_script_path = registered_script_path(cloud_name)
options = options.dup
options[:name] ||= cloud_name.to_s
options[:script_path] = cloud_script_path
cloud = nil
begin
require cloud_script_path
cloud_classname = cloud_name.to_s.capitalize
cloud_class = eval("RightScale::Clouds::#{cloud_classname}")
cloud = cloud_class.new(options)
rescue LoadError => e
raise ArgumentError, "Could not load Cloud class for #{cloud_name}, #{e}"
end
extend_cloud_by_scripts(cloud, logger)
return cloud
end | [
"def",
"create",
"(",
"cloud_name",
",",
"options",
")",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"cloud_name is required\"",
")",
"if",
"cloud_name",
".",
"to_s",
".",
"empty?",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"options[:logger] is required\"",
")",
"unless",
"logger",
"=",
"options",
"[",
":logger",
"]",
"raise",
"UnknownCloud",
".",
"new",
"(",
"\"No cloud definitions available.\"",
")",
"unless",
"@names_to_script_paths",
"cloud_name",
"=",
"cloud_name",
".",
"to_sym",
"cloud_name",
"=",
"default_cloud_name",
"if",
"UNKNOWN_CLOUD_NAME",
"==",
"cloud_name",
"raise",
"UnknownCloud",
".",
"new",
"(",
"\"Unable to determine a default cloud\"",
")",
"if",
"UNKNOWN_CLOUD_NAME",
"==",
"cloud_name",
"cloud_script_path",
"=",
"registered_script_path",
"(",
"cloud_name",
")",
"options",
"=",
"options",
".",
"dup",
"options",
"[",
":name",
"]",
"||=",
"cloud_name",
".",
"to_s",
"options",
"[",
":script_path",
"]",
"=",
"cloud_script_path",
"cloud",
"=",
"nil",
"begin",
"require",
"cloud_script_path",
"cloud_classname",
"=",
"cloud_name",
".",
"to_s",
".",
"capitalize",
"cloud_class",
"=",
"eval",
"(",
"\"RightScale::Clouds::#{cloud_classname}\"",
")",
"cloud",
"=",
"cloud_class",
".",
"new",
"(",
"options",
")",
"rescue",
"LoadError",
"=>",
"e",
"raise",
"ArgumentError",
",",
"\"Could not load Cloud class for #{cloud_name}, #{e}\"",
"end",
"extend_cloud_by_scripts",
"(",
"cloud",
",",
"logger",
")",
"return",
"cloud",
"end"
] | Factory method for dynamic metadata types.
=== Parameters
cloud(String):: a registered_type cloud name
options(Hash):: options for creation
=== Return
result(Object):: new instance of registered_type metadata type
=== Raise
UnknownCloud:: on error | [
"Factory",
"method",
"for",
"dynamic",
"metadata",
"types",
"."
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/clouds/cloud_factory.rb#L90-L115 | train |
rightscale/right_link | lib/clouds/cloud_factory.rb | RightScale.CloudFactory.default_cloud_name | def default_cloud_name
cloud_file_path = RightScale::AgentConfig.cloud_file_path
value = File.read(cloud_file_path).strip if File.file?(cloud_file_path)
value.to_s.empty? ? UNKNOWN_CLOUD_NAME : value
end | ruby | def default_cloud_name
cloud_file_path = RightScale::AgentConfig.cloud_file_path
value = File.read(cloud_file_path).strip if File.file?(cloud_file_path)
value.to_s.empty? ? UNKNOWN_CLOUD_NAME : value
end | [
"def",
"default_cloud_name",
"cloud_file_path",
"=",
"RightScale",
"::",
"AgentConfig",
".",
"cloud_file_path",
"value",
"=",
"File",
".",
"read",
"(",
"cloud_file_path",
")",
".",
"strip",
"if",
"File",
".",
"file?",
"(",
"cloud_file_path",
")",
"value",
".",
"to_s",
".",
"empty?",
"?",
"UNKNOWN_CLOUD_NAME",
":",
"value",
"end"
] | Getter for the default cloud name. This currently relies on a
'cloud file' which must be present in an expected RightScale location.
=== Return
result(String):: content of the 'cloud file' or UNKNOWN_CLOUD_NAME | [
"Getter",
"for",
"the",
"default",
"cloud",
"name",
".",
"This",
"currently",
"relies",
"on",
"a",
"cloud",
"file",
"which",
"must",
"be",
"present",
"in",
"an",
"expected",
"RightScale",
"location",
"."
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/clouds/cloud_factory.rb#L122-L126 | train |
rightscale/right_link | lib/instance/multi_thread_bundle_queue.rb | RightScale.MultiThreadBundleQueue.busy? | def busy?
busy = false
@mutex.synchronize { busy = @thread_name_to_queue.any? { |_, q| q.busy? } }
busy
end | ruby | def busy?
busy = false
@mutex.synchronize { busy = @thread_name_to_queue.any? { |_, q| q.busy? } }
busy
end | [
"def",
"busy?",
"busy",
"=",
"false",
"@mutex",
".",
"synchronize",
"{",
"busy",
"=",
"@thread_name_to_queue",
".",
"any?",
"{",
"|",
"_",
",",
"q",
"|",
"q",
".",
"busy?",
"}",
"}",
"busy",
"end"
] | Determines if queue is busy
=== Return
active(Boolean):: true if queue is busy | [
"Determines",
"if",
"queue",
"is",
"busy"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/multi_thread_bundle_queue.rb#L71-L75 | train |
rightscale/right_link | lib/instance/multi_thread_bundle_queue.rb | RightScale.MultiThreadBundleQueue.push_to_thread_queue | def push_to_thread_queue(context)
thread_name = context.respond_to?(:thread_name) ? context.thread_name : ::RightScale::AgentConfig.default_thread_name
queue = nil
@mutex.synchronize do
queue = @thread_name_to_queue[thread_name]
unless queue
# continuation for when thread-named queue is finally closed.
queue = create_thread_queue(thread_name) { push(THREAD_QUEUE_CLOSED_BUNDLE) }
@thread_name_to_queue[thread_name] = queue
end
end
# push context to selected thread queue
queue.push(context)
# always (re)activate in case an individual thread queue died unexpectedly.
# has no effect if already active.
queue.activate
true
end | ruby | def push_to_thread_queue(context)
thread_name = context.respond_to?(:thread_name) ? context.thread_name : ::RightScale::AgentConfig.default_thread_name
queue = nil
@mutex.synchronize do
queue = @thread_name_to_queue[thread_name]
unless queue
# continuation for when thread-named queue is finally closed.
queue = create_thread_queue(thread_name) { push(THREAD_QUEUE_CLOSED_BUNDLE) }
@thread_name_to_queue[thread_name] = queue
end
end
# push context to selected thread queue
queue.push(context)
# always (re)activate in case an individual thread queue died unexpectedly.
# has no effect if already active.
queue.activate
true
end | [
"def",
"push_to_thread_queue",
"(",
"context",
")",
"thread_name",
"=",
"context",
".",
"respond_to?",
"(",
":thread_name",
")",
"?",
"context",
".",
"thread_name",
":",
"::",
"RightScale",
"::",
"AgentConfig",
".",
"default_thread_name",
"queue",
"=",
"nil",
"@mutex",
".",
"synchronize",
"do",
"queue",
"=",
"@thread_name_to_queue",
"[",
"thread_name",
"]",
"unless",
"queue",
"queue",
"=",
"create_thread_queue",
"(",
"thread_name",
")",
"{",
"push",
"(",
"THREAD_QUEUE_CLOSED_BUNDLE",
")",
"}",
"@thread_name_to_queue",
"[",
"thread_name",
"]",
"=",
"queue",
"end",
"end",
"queue",
".",
"push",
"(",
"context",
")",
"queue",
".",
"activate",
"true",
"end"
] | Pushes a context to a thread based on a name determined from the context.
=== Parameters
context(Object):: any kind of context object
=== Return
true:: always true | [
"Pushes",
"a",
"context",
"to",
"a",
"thread",
"based",
"on",
"a",
"name",
"determined",
"from",
"the",
"context",
"."
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/multi_thread_bundle_queue.rb#L167-L186 | train |
rightscale/right_link | lib/instance/multi_thread_bundle_queue.rb | RightScale.MultiThreadBundleQueue.groom_thread_queues | def groom_thread_queues
still_active = false
@mutex.synchronize do
@thread_name_to_queue.delete_if { |_, queue| false == queue.active? }
still_active = false == @thread_name_to_queue.empty?
end
return still_active
end | ruby | def groom_thread_queues
still_active = false
@mutex.synchronize do
@thread_name_to_queue.delete_if { |_, queue| false == queue.active? }
still_active = false == @thread_name_to_queue.empty?
end
return still_active
end | [
"def",
"groom_thread_queues",
"still_active",
"=",
"false",
"@mutex",
".",
"synchronize",
"do",
"@thread_name_to_queue",
".",
"delete_if",
"{",
"|",
"_",
",",
"queue",
"|",
"false",
"==",
"queue",
".",
"active?",
"}",
"still_active",
"=",
"false",
"==",
"@thread_name_to_queue",
".",
"empty?",
"end",
"return",
"still_active",
"end"
] | Deletes any inactive queues from the hash of known queues.
=== Return
still_active(Boolean):: true if any queues are still active | [
"Deletes",
"any",
"inactive",
"queues",
"from",
"the",
"hash",
"of",
"known",
"queues",
"."
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/multi_thread_bundle_queue.rb#L204-L211 | train |
rightscale/right_link | lib/instance/multi_thread_bundle_queue.rb | RightScale.MultiThreadBundleQueue.close_thread_queues | def close_thread_queues
still_active = false
@mutex.synchronize do
@thread_name_to_queue.each_value do |queue|
if queue.active?
queue.close
still_active = true
end
end
end
return still_active
end | ruby | def close_thread_queues
still_active = false
@mutex.synchronize do
@thread_name_to_queue.each_value do |queue|
if queue.active?
queue.close
still_active = true
end
end
end
return still_active
end | [
"def",
"close_thread_queues",
"still_active",
"=",
"false",
"@mutex",
".",
"synchronize",
"do",
"@thread_name_to_queue",
".",
"each_value",
"do",
"|",
"queue",
"|",
"if",
"queue",
".",
"active?",
"queue",
".",
"close",
"still_active",
"=",
"true",
"end",
"end",
"end",
"return",
"still_active",
"end"
] | Closes all thread queues.
=== Return
result(Boolean):: true if any queues are still active (and stopping) | [
"Closes",
"all",
"thread",
"queues",
"."
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/multi_thread_bundle_queue.rb#L217-L228 | train |
rightscale/right_link | lib/instance/instance_auth_client.rb | RightScale.InstanceAuthClient.create_http_client | def create_http_client
options = {
:api_version => API_VERSION,
:open_timeout => DEFAULT_OPEN_TIMEOUT,
:request_timeout => DEFAULT_REQUEST_TIMEOUT,
:non_blocking => @non_blocking }
auth_url = URI.parse(@api_url)
auth_url.user = @token_id.to_s
auth_url.password = @token
@http_client = RightScale::BalancedHttpClient.new(auth_url.to_s, options)
end | ruby | def create_http_client
options = {
:api_version => API_VERSION,
:open_timeout => DEFAULT_OPEN_TIMEOUT,
:request_timeout => DEFAULT_REQUEST_TIMEOUT,
:non_blocking => @non_blocking }
auth_url = URI.parse(@api_url)
auth_url.user = @token_id.to_s
auth_url.password = @token
@http_client = RightScale::BalancedHttpClient.new(auth_url.to_s, options)
end | [
"def",
"create_http_client",
"options",
"=",
"{",
":api_version",
"=>",
"API_VERSION",
",",
":open_timeout",
"=>",
"DEFAULT_OPEN_TIMEOUT",
",",
":request_timeout",
"=>",
"DEFAULT_REQUEST_TIMEOUT",
",",
":non_blocking",
"=>",
"@non_blocking",
"}",
"auth_url",
"=",
"URI",
".",
"parse",
"(",
"@api_url",
")",
"auth_url",
".",
"user",
"=",
"@token_id",
".",
"to_s",
"auth_url",
".",
"password",
"=",
"@token",
"@http_client",
"=",
"RightScale",
"::",
"BalancedHttpClient",
".",
"new",
"(",
"auth_url",
".",
"to_s",
",",
"options",
")",
"end"
] | Create health-checked HTTP client for performing authorization
@return [RightSupport::Net::BalancedHttpClient] client | [
"Create",
"health",
"-",
"checked",
"HTTP",
"client",
"for",
"performing",
"authorization"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/instance_auth_client.rb#L154-L164 | train |
rightscale/right_link | lib/instance/instance_auth_client.rb | RightScale.InstanceAuthClient.get_authorized | def get_authorized
retries = redirects = 0
api_url = @api_url
begin
Log.info("Getting authorized via #{@api_url}")
params = {
:grant_type => "client_credentials",
:account_id => @account_id,
:r_s_version => AgentConfig.protocol_version,
:right_link_version => RightLink.version }
response = @http_client.post("/oauth2", params,
:headers => @other_headers,
:open_timeout => DEFAULT_OPEN_TIMEOUT,
:request_timeout => DEFAULT_REQUEST_TIMEOUT)
response = SerializationHelper.symbolize_keys(response)
@access_token = response[:access_token]
@expires_at = Time.now + response[:expires_in]
update_urls(response)
self.state = :authorized
@communicated_callbacks.each { |callback| callback.call } if @communicated_callbacks
rescue BalancedHttpClient::NotResponding
if (retries += 1) > MAX_RETRIES
ErrorTracker.log(self, "Exceeded maximum authorization retries (#{MAX_RETRIES})")
else
sleep(RETRY_INTERVAL)
retry
end
raise
rescue HttpExceptions::MovedPermanently, HttpExceptions::Found => e
if (redirects += 1) > MAX_REDIRECTS
ErrorTracker.log(self, "Exceeded maximum redirects (#{MAX_REDIRECTS})")
elsif redirected(e)
retry
end
@api_url = api_url
raise
rescue HttpExceptions::Unauthorized => e
self.state = :unauthorized
@access_token = nil
@expires_at = Time.now
raise Exceptions::Unauthorized.new(e.http_body, e)
end
true
rescue BalancedHttpClient::NotResponding, Exceptions::Unauthorized, CommunicationModeSwitch, Exceptions::ConnectivityFailure
raise
rescue StandardError => e
ErrorTracker.log(self, "Failed authorizing", e)
self.state = :failed
raise
end | ruby | def get_authorized
retries = redirects = 0
api_url = @api_url
begin
Log.info("Getting authorized via #{@api_url}")
params = {
:grant_type => "client_credentials",
:account_id => @account_id,
:r_s_version => AgentConfig.protocol_version,
:right_link_version => RightLink.version }
response = @http_client.post("/oauth2", params,
:headers => @other_headers,
:open_timeout => DEFAULT_OPEN_TIMEOUT,
:request_timeout => DEFAULT_REQUEST_TIMEOUT)
response = SerializationHelper.symbolize_keys(response)
@access_token = response[:access_token]
@expires_at = Time.now + response[:expires_in]
update_urls(response)
self.state = :authorized
@communicated_callbacks.each { |callback| callback.call } if @communicated_callbacks
rescue BalancedHttpClient::NotResponding
if (retries += 1) > MAX_RETRIES
ErrorTracker.log(self, "Exceeded maximum authorization retries (#{MAX_RETRIES})")
else
sleep(RETRY_INTERVAL)
retry
end
raise
rescue HttpExceptions::MovedPermanently, HttpExceptions::Found => e
if (redirects += 1) > MAX_REDIRECTS
ErrorTracker.log(self, "Exceeded maximum redirects (#{MAX_REDIRECTS})")
elsif redirected(e)
retry
end
@api_url = api_url
raise
rescue HttpExceptions::Unauthorized => e
self.state = :unauthorized
@access_token = nil
@expires_at = Time.now
raise Exceptions::Unauthorized.new(e.http_body, e)
end
true
rescue BalancedHttpClient::NotResponding, Exceptions::Unauthorized, CommunicationModeSwitch, Exceptions::ConnectivityFailure
raise
rescue StandardError => e
ErrorTracker.log(self, "Failed authorizing", e)
self.state = :failed
raise
end | [
"def",
"get_authorized",
"retries",
"=",
"redirects",
"=",
"0",
"api_url",
"=",
"@api_url",
"begin",
"Log",
".",
"info",
"(",
"\"Getting authorized via #{@api_url}\"",
")",
"params",
"=",
"{",
":grant_type",
"=>",
"\"client_credentials\"",
",",
":account_id",
"=>",
"@account_id",
",",
":r_s_version",
"=>",
"AgentConfig",
".",
"protocol_version",
",",
":right_link_version",
"=>",
"RightLink",
".",
"version",
"}",
"response",
"=",
"@http_client",
".",
"post",
"(",
"\"/oauth2\"",
",",
"params",
",",
":headers",
"=>",
"@other_headers",
",",
":open_timeout",
"=>",
"DEFAULT_OPEN_TIMEOUT",
",",
":request_timeout",
"=>",
"DEFAULT_REQUEST_TIMEOUT",
")",
"response",
"=",
"SerializationHelper",
".",
"symbolize_keys",
"(",
"response",
")",
"@access_token",
"=",
"response",
"[",
":access_token",
"]",
"@expires_at",
"=",
"Time",
".",
"now",
"+",
"response",
"[",
":expires_in",
"]",
"update_urls",
"(",
"response",
")",
"self",
".",
"state",
"=",
":authorized",
"@communicated_callbacks",
".",
"each",
"{",
"|",
"callback",
"|",
"callback",
".",
"call",
"}",
"if",
"@communicated_callbacks",
"rescue",
"BalancedHttpClient",
"::",
"NotResponding",
"if",
"(",
"retries",
"+=",
"1",
")",
">",
"MAX_RETRIES",
"ErrorTracker",
".",
"log",
"(",
"self",
",",
"\"Exceeded maximum authorization retries (#{MAX_RETRIES})\"",
")",
"else",
"sleep",
"(",
"RETRY_INTERVAL",
")",
"retry",
"end",
"raise",
"rescue",
"HttpExceptions",
"::",
"MovedPermanently",
",",
"HttpExceptions",
"::",
"Found",
"=>",
"e",
"if",
"(",
"redirects",
"+=",
"1",
")",
">",
"MAX_REDIRECTS",
"ErrorTracker",
".",
"log",
"(",
"self",
",",
"\"Exceeded maximum redirects (#{MAX_REDIRECTS})\"",
")",
"elsif",
"redirected",
"(",
"e",
")",
"retry",
"end",
"@api_url",
"=",
"api_url",
"raise",
"rescue",
"HttpExceptions",
"::",
"Unauthorized",
"=>",
"e",
"self",
".",
"state",
"=",
":unauthorized",
"@access_token",
"=",
"nil",
"@expires_at",
"=",
"Time",
".",
"now",
"raise",
"Exceptions",
"::",
"Unauthorized",
".",
"new",
"(",
"e",
".",
"http_body",
",",
"e",
")",
"end",
"true",
"rescue",
"BalancedHttpClient",
"::",
"NotResponding",
",",
"Exceptions",
"::",
"Unauthorized",
",",
"CommunicationModeSwitch",
",",
"Exceptions",
"::",
"ConnectivityFailure",
"raise",
"rescue",
"StandardError",
"=>",
"e",
"ErrorTracker",
".",
"log",
"(",
"self",
",",
"\"Failed authorizing\"",
",",
"e",
")",
"self",
".",
"state",
"=",
":failed",
"raise",
"end"
] | Get authorized with RightApi using OAuth2
As an extension to OAuth2 receive URLs needed for other servers
Retry authorization if RightApi not responding or if get redirected
@return [TrueClass] always true
@raise [Exceptions::Unauthorized] authorization failed
@raise [BalancedHttpClient::NotResponding] cannot access RightApi
@raise [CommunicationModeSwitch] changing communication mode | [
"Get",
"authorized",
"with",
"RightApi",
"using",
"OAuth2",
"As",
"an",
"extension",
"to",
"OAuth2",
"receive",
"URLs",
"needed",
"for",
"other",
"servers",
"Retry",
"authorization",
"if",
"RightApi",
"not",
"responding",
"or",
"if",
"get",
"redirected"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/instance_auth_client.rb#L175-L224 | train |
rightscale/right_link | lib/instance/instance_auth_client.rb | RightScale.InstanceAuthClient.renew_authorization | def renew_authorization(wait = nil)
wait ||= (state == :authorized) ? ((@expires_at - Time.now).to_i / RENEW_FACTOR) : 0
if @renew_timer && wait == 0
@renew_timer.cancel
@renew_timer = nil
end
unless @renew_timer
@renew_timer = EM_S::Timer.new(wait) do
@renew_timer = nil
previous_state = state
begin
get_authorized
renew_authorization
rescue Exceptions::ConnectivityFailure => e
if wait > 0
renew_authorization([(wait * RENEW_FACTOR), MAX_RENEW_TIME].min)
else
renew_authorization(MIN_RENEW_TIME)
end
rescue BalancedHttpClient::NotResponding => e
if (expires_in = (@expires_at - Time.now).to_i) > MIN_RENEW_TIME
renew_authorization(expires_in / RENEW_FACTOR)
else
self.state = :expired
reconnect
end
rescue Exceptions::Unauthorized => e
if previous_state == :unauthorized && wait > 0
renew_authorization([(wait * RENEW_FACTOR), MAX_UNAUTHORIZED_RENEW_INTERVAL].min)
else
renew_authorization(UNAUTHORIZED_RENEW_INTERVAL)
end
rescue CommunicationModeSwitch => e
ErrorTracker.log(self, "Failed authorization renewal", e, nil, :no_trace)
self.state = :failed
rescue Exception => e
ErrorTracker.log(self, "Failed authorization renewal", e)
self.state = :failed
end
end
end
true
end | ruby | def renew_authorization(wait = nil)
wait ||= (state == :authorized) ? ((@expires_at - Time.now).to_i / RENEW_FACTOR) : 0
if @renew_timer && wait == 0
@renew_timer.cancel
@renew_timer = nil
end
unless @renew_timer
@renew_timer = EM_S::Timer.new(wait) do
@renew_timer = nil
previous_state = state
begin
get_authorized
renew_authorization
rescue Exceptions::ConnectivityFailure => e
if wait > 0
renew_authorization([(wait * RENEW_FACTOR), MAX_RENEW_TIME].min)
else
renew_authorization(MIN_RENEW_TIME)
end
rescue BalancedHttpClient::NotResponding => e
if (expires_in = (@expires_at - Time.now).to_i) > MIN_RENEW_TIME
renew_authorization(expires_in / RENEW_FACTOR)
else
self.state = :expired
reconnect
end
rescue Exceptions::Unauthorized => e
if previous_state == :unauthorized && wait > 0
renew_authorization([(wait * RENEW_FACTOR), MAX_UNAUTHORIZED_RENEW_INTERVAL].min)
else
renew_authorization(UNAUTHORIZED_RENEW_INTERVAL)
end
rescue CommunicationModeSwitch => e
ErrorTracker.log(self, "Failed authorization renewal", e, nil, :no_trace)
self.state = :failed
rescue Exception => e
ErrorTracker.log(self, "Failed authorization renewal", e)
self.state = :failed
end
end
end
true
end | [
"def",
"renew_authorization",
"(",
"wait",
"=",
"nil",
")",
"wait",
"||=",
"(",
"state",
"==",
":authorized",
")",
"?",
"(",
"(",
"@expires_at",
"-",
"Time",
".",
"now",
")",
".",
"to_i",
"/",
"RENEW_FACTOR",
")",
":",
"0",
"if",
"@renew_timer",
"&&",
"wait",
"==",
"0",
"@renew_timer",
".",
"cancel",
"@renew_timer",
"=",
"nil",
"end",
"unless",
"@renew_timer",
"@renew_timer",
"=",
"EM_S",
"::",
"Timer",
".",
"new",
"(",
"wait",
")",
"do",
"@renew_timer",
"=",
"nil",
"previous_state",
"=",
"state",
"begin",
"get_authorized",
"renew_authorization",
"rescue",
"Exceptions",
"::",
"ConnectivityFailure",
"=>",
"e",
"if",
"wait",
">",
"0",
"renew_authorization",
"(",
"[",
"(",
"wait",
"*",
"RENEW_FACTOR",
")",
",",
"MAX_RENEW_TIME",
"]",
".",
"min",
")",
"else",
"renew_authorization",
"(",
"MIN_RENEW_TIME",
")",
"end",
"rescue",
"BalancedHttpClient",
"::",
"NotResponding",
"=>",
"e",
"if",
"(",
"expires_in",
"=",
"(",
"@expires_at",
"-",
"Time",
".",
"now",
")",
".",
"to_i",
")",
">",
"MIN_RENEW_TIME",
"renew_authorization",
"(",
"expires_in",
"/",
"RENEW_FACTOR",
")",
"else",
"self",
".",
"state",
"=",
":expired",
"reconnect",
"end",
"rescue",
"Exceptions",
"::",
"Unauthorized",
"=>",
"e",
"if",
"previous_state",
"==",
":unauthorized",
"&&",
"wait",
">",
"0",
"renew_authorization",
"(",
"[",
"(",
"wait",
"*",
"RENEW_FACTOR",
")",
",",
"MAX_UNAUTHORIZED_RENEW_INTERVAL",
"]",
".",
"min",
")",
"else",
"renew_authorization",
"(",
"UNAUTHORIZED_RENEW_INTERVAL",
")",
"end",
"rescue",
"CommunicationModeSwitch",
"=>",
"e",
"ErrorTracker",
".",
"log",
"(",
"self",
",",
"\"Failed authorization renewal\"",
",",
"e",
",",
"nil",
",",
":no_trace",
")",
"self",
".",
"state",
"=",
":failed",
"rescue",
"Exception",
"=>",
"e",
"ErrorTracker",
".",
"log",
"(",
"self",
",",
"\"Failed authorization renewal\"",
",",
"e",
")",
"self",
".",
"state",
"=",
":failed",
"end",
"end",
"end",
"true",
"end"
] | Get authorized and then continuously renew authorization before it expires
@param [Integer, NilClass] wait time before attempt to renew; defaults to
have the expiry time if authorized, otherwise 0
@return [TrueClass] always true | [
"Get",
"authorized",
"and",
"then",
"continuously",
"renew",
"authorization",
"before",
"it",
"expires"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/instance_auth_client.rb#L232-L276 | train |
rightscale/right_link | lib/instance/instance_auth_client.rb | RightScale.InstanceAuthClient.update_urls | def update_urls(response)
mode = response[:mode].to_sym
raise CommunicationModeSwitch, "RightNet communication mode switching from #{@mode.inspect} to #{mode.inspect}" if @mode && @mode != mode
@mode = mode
@shard_id = response[:shard_id].to_i
if (new_url = response[:router_url]) != @router_url
Log.info("Updating RightNet router URL to #{new_url.inspect}")
@router_url = new_url
end
if (new_url = response[:api_url]) != @api_url
Log.info("Updating RightApi URL to #{new_url.inspect}")
@api_url = new_url
create_http_client
end
true
end | ruby | def update_urls(response)
mode = response[:mode].to_sym
raise CommunicationModeSwitch, "RightNet communication mode switching from #{@mode.inspect} to #{mode.inspect}" if @mode && @mode != mode
@mode = mode
@shard_id = response[:shard_id].to_i
if (new_url = response[:router_url]) != @router_url
Log.info("Updating RightNet router URL to #{new_url.inspect}")
@router_url = new_url
end
if (new_url = response[:api_url]) != @api_url
Log.info("Updating RightApi URL to #{new_url.inspect}")
@api_url = new_url
create_http_client
end
true
end | [
"def",
"update_urls",
"(",
"response",
")",
"mode",
"=",
"response",
"[",
":mode",
"]",
".",
"to_sym",
"raise",
"CommunicationModeSwitch",
",",
"\"RightNet communication mode switching from #{@mode.inspect} to #{mode.inspect}\"",
"if",
"@mode",
"&&",
"@mode",
"!=",
"mode",
"@mode",
"=",
"mode",
"@shard_id",
"=",
"response",
"[",
":shard_id",
"]",
".",
"to_i",
"if",
"(",
"new_url",
"=",
"response",
"[",
":router_url",
"]",
")",
"!=",
"@router_url",
"Log",
".",
"info",
"(",
"\"Updating RightNet router URL to #{new_url.inspect}\"",
")",
"@router_url",
"=",
"new_url",
"end",
"if",
"(",
"new_url",
"=",
"response",
"[",
":api_url",
"]",
")",
"!=",
"@api_url",
"Log",
".",
"info",
"(",
"\"Updating RightApi URL to #{new_url.inspect}\"",
")",
"@api_url",
"=",
"new_url",
"create_http_client",
"end",
"true",
"end"
] | Update URLs and other data returned from authorization
Recreate client if API URL has changed
@param [Hash] response containing URLs with keys as symbols
@return [TrueClass] always true
@raise [CommunicationModeSwitch] changing communication mode | [
"Update",
"URLs",
"and",
"other",
"data",
"returned",
"from",
"authorization",
"Recreate",
"client",
"if",
"API",
"URL",
"has",
"changed"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/instance_auth_client.rb#L286-L301 | train |
rightscale/right_link | lib/instance/instance_auth_client.rb | RightScale.InstanceAuthClient.redirected | def redirected(exception)
redirected = false
location = exception.response.headers[:location]
if location.nil? || location.empty?
ErrorTracker.log(self, "Redirect exception does contain a redirect location")
else
new_url = URI.parse(location)
if new_url.scheme !~ /http/ || new_url.host.empty?
ErrorTracker.log(self, "Failed redirect because location is invalid: #{location.inspect}")
else
# Apply scheme and host from new URL to existing URL, but not path
new_url.path = URI.parse(@api_url).path
@api_url = new_url.to_s
Log.info("Updating RightApi URL to #{@api_url.inspect} due to redirect to #{location.inspect}")
@stats["state"].update("redirect")
create_http_client
redirected = true
end
end
redirected
end | ruby | def redirected(exception)
redirected = false
location = exception.response.headers[:location]
if location.nil? || location.empty?
ErrorTracker.log(self, "Redirect exception does contain a redirect location")
else
new_url = URI.parse(location)
if new_url.scheme !~ /http/ || new_url.host.empty?
ErrorTracker.log(self, "Failed redirect because location is invalid: #{location.inspect}")
else
# Apply scheme and host from new URL to existing URL, but not path
new_url.path = URI.parse(@api_url).path
@api_url = new_url.to_s
Log.info("Updating RightApi URL to #{@api_url.inspect} due to redirect to #{location.inspect}")
@stats["state"].update("redirect")
create_http_client
redirected = true
end
end
redirected
end | [
"def",
"redirected",
"(",
"exception",
")",
"redirected",
"=",
"false",
"location",
"=",
"exception",
".",
"response",
".",
"headers",
"[",
":location",
"]",
"if",
"location",
".",
"nil?",
"||",
"location",
".",
"empty?",
"ErrorTracker",
".",
"log",
"(",
"self",
",",
"\"Redirect exception does contain a redirect location\"",
")",
"else",
"new_url",
"=",
"URI",
".",
"parse",
"(",
"location",
")",
"if",
"new_url",
".",
"scheme",
"!~",
"/",
"/",
"||",
"new_url",
".",
"host",
".",
"empty?",
"ErrorTracker",
".",
"log",
"(",
"self",
",",
"\"Failed redirect because location is invalid: #{location.inspect}\"",
")",
"else",
"new_url",
".",
"path",
"=",
"URI",
".",
"parse",
"(",
"@api_url",
")",
".",
"path",
"@api_url",
"=",
"new_url",
".",
"to_s",
"Log",
".",
"info",
"(",
"\"Updating RightApi URL to #{@api_url.inspect} due to redirect to #{location.inspect}\"",
")",
"@stats",
"[",
"\"state\"",
"]",
".",
"update",
"(",
"\"redirect\"",
")",
"create_http_client",
"redirected",
"=",
"true",
"end",
"end",
"redirected",
"end"
] | Handle redirect by adjusting URLs to requested location and recreating HTTP client
@param [RightScale::BalancedHttpClient::Redirect] exception containing redirect location,
which is required to be a full URL
@return [Boolean] whether successfully redirected | [
"Handle",
"redirect",
"by",
"adjusting",
"URLs",
"to",
"requested",
"location",
"and",
"recreating",
"HTTP",
"client"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/instance_auth_client.rb#L309-L329 | train |
rightscale/right_link | lib/instance/instance_auth_client.rb | RightScale.InstanceAuthClient.reconnect | def reconnect
unless @reconnecting
@reconnecting = true
@stats["reconnects"].update("initiate")
@reconnect_timer = EM_S::PeriodicTimer.new(rand(HEALTH_CHECK_INTERVAL)) do
begin
@http_client.check_health
@stats["reconnects"].update("success")
@reconnect_timer.cancel if @reconnect_timer # only need 'if' for test purposes
@reconnect_timer = @reconnecting = nil
renew_authorization(0)
rescue BalancedHttpClient::NotResponding => e
@stats["reconnects"].update("no response")
rescue Exception => e
ErrorTracker.log(self, "Failed authorization reconnect", e)
@stats["reconnects"].update("failure")
end
@reconnect_timer.interval = HEALTH_CHECK_INTERVAL if @reconnect_timer
end
end
true
end | ruby | def reconnect
unless @reconnecting
@reconnecting = true
@stats["reconnects"].update("initiate")
@reconnect_timer = EM_S::PeriodicTimer.new(rand(HEALTH_CHECK_INTERVAL)) do
begin
@http_client.check_health
@stats["reconnects"].update("success")
@reconnect_timer.cancel if @reconnect_timer # only need 'if' for test purposes
@reconnect_timer = @reconnecting = nil
renew_authorization(0)
rescue BalancedHttpClient::NotResponding => e
@stats["reconnects"].update("no response")
rescue Exception => e
ErrorTracker.log(self, "Failed authorization reconnect", e)
@stats["reconnects"].update("failure")
end
@reconnect_timer.interval = HEALTH_CHECK_INTERVAL if @reconnect_timer
end
end
true
end | [
"def",
"reconnect",
"unless",
"@reconnecting",
"@reconnecting",
"=",
"true",
"@stats",
"[",
"\"reconnects\"",
"]",
".",
"update",
"(",
"\"initiate\"",
")",
"@reconnect_timer",
"=",
"EM_S",
"::",
"PeriodicTimer",
".",
"new",
"(",
"rand",
"(",
"HEALTH_CHECK_INTERVAL",
")",
")",
"do",
"begin",
"@http_client",
".",
"check_health",
"@stats",
"[",
"\"reconnects\"",
"]",
".",
"update",
"(",
"\"success\"",
")",
"@reconnect_timer",
".",
"cancel",
"if",
"@reconnect_timer",
"@reconnect_timer",
"=",
"@reconnecting",
"=",
"nil",
"renew_authorization",
"(",
"0",
")",
"rescue",
"BalancedHttpClient",
"::",
"NotResponding",
"=>",
"e",
"@stats",
"[",
"\"reconnects\"",
"]",
".",
"update",
"(",
"\"no response\"",
")",
"rescue",
"Exception",
"=>",
"e",
"ErrorTracker",
".",
"log",
"(",
"self",
",",
"\"Failed authorization reconnect\"",
",",
"e",
")",
"@stats",
"[",
"\"reconnects\"",
"]",
".",
"update",
"(",
"\"failure\"",
")",
"end",
"@reconnect_timer",
".",
"interval",
"=",
"HEALTH_CHECK_INTERVAL",
"if",
"@reconnect_timer",
"end",
"end",
"true",
"end"
] | Reconnect with authorization server by periodically checking health
Delay random interval before starting to check to reduce server spiking
When again healthy, renew authorization
@return [TrueClass] always true | [
"Reconnect",
"with",
"authorization",
"server",
"by",
"periodically",
"checking",
"health",
"Delay",
"random",
"interval",
"before",
"starting",
"to",
"check",
"to",
"reduce",
"server",
"spiking",
"When",
"again",
"healthy",
"renew",
"authorization"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/instance_auth_client.rb#L336-L357 | train |
nikitachernov/FutureProof | lib/future_proof/future_queue.rb | FutureProof.FutureQueue.push | def push(*values, &block)
raise_future_proof_exception if finished?
value = if block_given?
begin
block.call(*values)
rescue => e
e
end
else
values.size == 1 ? values[0] : values
end
super(value)
end | ruby | def push(*values, &block)
raise_future_proof_exception if finished?
value = if block_given?
begin
block.call(*values)
rescue => e
e
end
else
values.size == 1 ? values[0] : values
end
super(value)
end | [
"def",
"push",
"(",
"*",
"values",
",",
"&",
"block",
")",
"raise_future_proof_exception",
"if",
"finished?",
"value",
"=",
"if",
"block_given?",
"begin",
"block",
".",
"call",
"(",
"*",
"values",
")",
"rescue",
"=>",
"e",
"e",
"end",
"else",
"values",
".",
"size",
"==",
"1",
"?",
"values",
"[",
"0",
"]",
":",
"values",
"end",
"super",
"(",
"value",
")",
"end"
] | Pushes value into a queue by executing it.
If execution results in an exception
then exception is stored itself.
@note allowed only when queue is running. | [
"Pushes",
"value",
"into",
"a",
"queue",
"by",
"executing",
"it",
".",
"If",
"execution",
"results",
"in",
"an",
"exception",
"then",
"exception",
"is",
"stored",
"itself",
"."
] | 84102ea0a353e67eef8aceb2c9b0a688e8409724 | https://github.com/nikitachernov/FutureProof/blob/84102ea0a353e67eef8aceb2c9b0a688e8409724/lib/future_proof/future_queue.rb#L19-L31 | train |
rightscale/right_link | lib/instance/network_configurator/windows_network_configurator.rb | RightScale.WindowsNetworkConfigurator.get_device_ip | def get_device_ip(device)
ip_addr = device_config_show(device).lines("\n").grep(/IP Address/).shift
return nil unless ip_addr
ip_addr.strip.split.last
end | ruby | def get_device_ip(device)
ip_addr = device_config_show(device).lines("\n").grep(/IP Address/).shift
return nil unless ip_addr
ip_addr.strip.split.last
end | [
"def",
"get_device_ip",
"(",
"device",
")",
"ip_addr",
"=",
"device_config_show",
"(",
"device",
")",
".",
"lines",
"(",
"\"\\n\"",
")",
".",
"grep",
"(",
"/",
"/",
")",
".",
"shift",
"return",
"nil",
"unless",
"ip_addr",
"ip_addr",
".",
"strip",
".",
"split",
".",
"last",
"end"
] | Gets IP address for specified device
=== Parameters
device(String):: target device name
=== Return
result(String):: current IP for specified device or nil | [
"Gets",
"IP",
"address",
"for",
"specified",
"device"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/network_configurator/windows_network_configurator.rb#L138-L142 | train |
rightscale/right_link | scripts/thunker.rb | RightScale.Thunker.run | def run(options)
@log_sink = StringIO.new
@log = Logger.new(@log_sink)
RightScale::Log.force_logger(@log)
check_privileges if right_agent_running?
username = options.delete(:username)
email = options.delete(:email)
uuid = options.delete(:uuid)
superuser = options.delete(:superuser)
profile = options.delete(:profile)
force = options.delete(:force)
fail(1) if missing_argument(username, "USERNAME") || missing_argument(email, "EMAIL") || missing_argument(uuid, "UUID")
# Fetch some information about the client's intentions and origin
orig = ENV['SSH2_ORIGINAL_COMMAND'] || ENV['SSH_ORIGINAL_COMMAND']
client_ip = ENV['SSH_CLIENT'].split(/\s+/).first if ENV.has_key?('SSH_CLIENT')
if orig =~ SCP_COMMAND
access = :scp
elsif orig =~ SFTP_COMMAND
access = :sftp
elsif (orig != nil) && (!orig.empty?)
access = :command
else
access = :shell
end
# Create user just-in-time; idempotent if user already exists
# Note that username == chosen here, they just get used in two different contexts
username = LoginUserManager.create_user(username, uuid, superuser ? true : false) do |chosen|
puts "Creating your user profile (#{chosen}) on this machine." if (:shell == access)
end
create_audit_entry(email, username, access, orig, client_ip) if right_agent_running?
chown_tty(username)
# Note that when execing sudo we use the N-argument form of Kernel.exec,
# which does not invoke a shell, but rather directly invokes the command specified
# by argv[0] and uses argv[1..N] as the command line. This protects us against shell
# escape characters and other badness.
#
# Unfortunately, this means that file globs and other 'useful' shell escape characters
# do not get parsed.
#
# As a workaround, for non-interactive access types, we tell sudo to invoke a shell and
# use the shell's '-c' argument to specify the command to run. We also use the -H
# argument to sudo, which forces it to set HOME to the user's homedir. We attempt to
# set some other environment variables to make the user feel more at home, but we
# are at the mercy of sudo.
#
# For interactive logins, we don't need to perform any trickiness since our goal is
# simply to get the user into a shell, with no command line args to parse.
case access
when :scp, :sftp, :command
LoginUserManager.simulate_login(username)
Kernel.exec('sudo', '-H', '-u', username, '/bin/sh', '-c', "cd $HOME ; #{orig}")
when :shell
if right_agent_running?
display_motd
else
display_right_link_is_not_running_warning
end
Kernel.exec('sudo', '-i', '-u', username)
end
rescue SystemExit => e
raise e
rescue Exception => e
fail(e)
end | ruby | def run(options)
@log_sink = StringIO.new
@log = Logger.new(@log_sink)
RightScale::Log.force_logger(@log)
check_privileges if right_agent_running?
username = options.delete(:username)
email = options.delete(:email)
uuid = options.delete(:uuid)
superuser = options.delete(:superuser)
profile = options.delete(:profile)
force = options.delete(:force)
fail(1) if missing_argument(username, "USERNAME") || missing_argument(email, "EMAIL") || missing_argument(uuid, "UUID")
# Fetch some information about the client's intentions and origin
orig = ENV['SSH2_ORIGINAL_COMMAND'] || ENV['SSH_ORIGINAL_COMMAND']
client_ip = ENV['SSH_CLIENT'].split(/\s+/).first if ENV.has_key?('SSH_CLIENT')
if orig =~ SCP_COMMAND
access = :scp
elsif orig =~ SFTP_COMMAND
access = :sftp
elsif (orig != nil) && (!orig.empty?)
access = :command
else
access = :shell
end
# Create user just-in-time; idempotent if user already exists
# Note that username == chosen here, they just get used in two different contexts
username = LoginUserManager.create_user(username, uuid, superuser ? true : false) do |chosen|
puts "Creating your user profile (#{chosen}) on this machine." if (:shell == access)
end
create_audit_entry(email, username, access, orig, client_ip) if right_agent_running?
chown_tty(username)
# Note that when execing sudo we use the N-argument form of Kernel.exec,
# which does not invoke a shell, but rather directly invokes the command specified
# by argv[0] and uses argv[1..N] as the command line. This protects us against shell
# escape characters and other badness.
#
# Unfortunately, this means that file globs and other 'useful' shell escape characters
# do not get parsed.
#
# As a workaround, for non-interactive access types, we tell sudo to invoke a shell and
# use the shell's '-c' argument to specify the command to run. We also use the -H
# argument to sudo, which forces it to set HOME to the user's homedir. We attempt to
# set some other environment variables to make the user feel more at home, but we
# are at the mercy of sudo.
#
# For interactive logins, we don't need to perform any trickiness since our goal is
# simply to get the user into a shell, with no command line args to parse.
case access
when :scp, :sftp, :command
LoginUserManager.simulate_login(username)
Kernel.exec('sudo', '-H', '-u', username, '/bin/sh', '-c', "cd $HOME ; #{orig}")
when :shell
if right_agent_running?
display_motd
else
display_right_link_is_not_running_warning
end
Kernel.exec('sudo', '-i', '-u', username)
end
rescue SystemExit => e
raise e
rescue Exception => e
fail(e)
end | [
"def",
"run",
"(",
"options",
")",
"@log_sink",
"=",
"StringIO",
".",
"new",
"@log",
"=",
"Logger",
".",
"new",
"(",
"@log_sink",
")",
"RightScale",
"::",
"Log",
".",
"force_logger",
"(",
"@log",
")",
"check_privileges",
"if",
"right_agent_running?",
"username",
"=",
"options",
".",
"delete",
"(",
":username",
")",
"email",
"=",
"options",
".",
"delete",
"(",
":email",
")",
"uuid",
"=",
"options",
".",
"delete",
"(",
":uuid",
")",
"superuser",
"=",
"options",
".",
"delete",
"(",
":superuser",
")",
"profile",
"=",
"options",
".",
"delete",
"(",
":profile",
")",
"force",
"=",
"options",
".",
"delete",
"(",
":force",
")",
"fail",
"(",
"1",
")",
"if",
"missing_argument",
"(",
"username",
",",
"\"USERNAME\"",
")",
"||",
"missing_argument",
"(",
"email",
",",
"\"EMAIL\"",
")",
"||",
"missing_argument",
"(",
"uuid",
",",
"\"UUID\"",
")",
"orig",
"=",
"ENV",
"[",
"'SSH2_ORIGINAL_COMMAND'",
"]",
"||",
"ENV",
"[",
"'SSH_ORIGINAL_COMMAND'",
"]",
"client_ip",
"=",
"ENV",
"[",
"'SSH_CLIENT'",
"]",
".",
"split",
"(",
"/",
"\\s",
"/",
")",
".",
"first",
"if",
"ENV",
".",
"has_key?",
"(",
"'SSH_CLIENT'",
")",
"if",
"orig",
"=~",
"SCP_COMMAND",
"access",
"=",
":scp",
"elsif",
"orig",
"=~",
"SFTP_COMMAND",
"access",
"=",
":sftp",
"elsif",
"(",
"orig",
"!=",
"nil",
")",
"&&",
"(",
"!",
"orig",
".",
"empty?",
")",
"access",
"=",
":command",
"else",
"access",
"=",
":shell",
"end",
"username",
"=",
"LoginUserManager",
".",
"create_user",
"(",
"username",
",",
"uuid",
",",
"superuser",
"?",
"true",
":",
"false",
")",
"do",
"|",
"chosen",
"|",
"puts",
"\"Creating your user profile (#{chosen}) on this machine.\"",
"if",
"(",
":shell",
"==",
"access",
")",
"end",
"create_audit_entry",
"(",
"email",
",",
"username",
",",
"access",
",",
"orig",
",",
"client_ip",
")",
"if",
"right_agent_running?",
"chown_tty",
"(",
"username",
")",
"case",
"access",
"when",
":scp",
",",
":sftp",
",",
":command",
"LoginUserManager",
".",
"simulate_login",
"(",
"username",
")",
"Kernel",
".",
"exec",
"(",
"'sudo'",
",",
"'-H'",
",",
"'-u'",
",",
"username",
",",
"'/bin/sh'",
",",
"'-c'",
",",
"\"cd $HOME ; #{orig}\"",
")",
"when",
":shell",
"if",
"right_agent_running?",
"display_motd",
"else",
"display_right_link_is_not_running_warning",
"end",
"Kernel",
".",
"exec",
"(",
"'sudo'",
",",
"'-i'",
",",
"'-u'",
",",
"username",
")",
"end",
"rescue",
"SystemExit",
"=>",
"e",
"raise",
"e",
"rescue",
"Exception",
"=>",
"e",
"fail",
"(",
"e",
")",
"end"
] | best-effort auditing, but try not to block user
Manage individual user SSH logins
=== Parameters
options(Hash):: Hash of options as defined in +parse_args+
=== Return
true:: Always return true | [
"best",
"-",
"effort",
"auditing",
"but",
"try",
"not",
"to",
"block",
"user",
"Manage",
"individual",
"user",
"SSH",
"logins"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/scripts/thunker.rb#L55-L126 | train |
rightscale/right_link | scripts/thunker.rb | RightScale.Thunker.create_audit_entry | def create_audit_entry(email, username, access, command, client_ip=nil)
begin
hostname = `hostname`.strip
rescue Exception => e
hostname = 'localhost'
end
case access
when :scp then
summary = 'SSH file copy'
detail = "User copied files copied (scp) to/from host."
when :sftp then
summary = 'SSH interactive file transfer'
detail = "User initiated an SFTP session."
when :command
summary = 'SSH command'
detail = "User invoked an interactive program."
when :shell
summary = 'SSH interactive login'
detail = "User connected and invoked a login shell."
end
detail += "\nLogin: #{username}@#{hostname}" if username
detail += "\nClient IP: #{client_ip}" if client_ip
detail += "\nCommand: #{command}" if command
log_detail = detail.gsub("\n", '; ')
Log.info("#{summary} - #{log_detail}")
options = {
:name => 'audit_create_entry',
:user_email => email,
:summary => summary,
:detail => detail,
:category => RightScale::EventCategories::CATEGORY_SECURITY
}
send_command(options, false, AUDIT_REQUEST_TIMEOUT)
true
rescue Exception => e
Log.error("#{e.class.name}:#{e.message}")
Log.error(e.backtrace.join("\n"))
false
end | ruby | def create_audit_entry(email, username, access, command, client_ip=nil)
begin
hostname = `hostname`.strip
rescue Exception => e
hostname = 'localhost'
end
case access
when :scp then
summary = 'SSH file copy'
detail = "User copied files copied (scp) to/from host."
when :sftp then
summary = 'SSH interactive file transfer'
detail = "User initiated an SFTP session."
when :command
summary = 'SSH command'
detail = "User invoked an interactive program."
when :shell
summary = 'SSH interactive login'
detail = "User connected and invoked a login shell."
end
detail += "\nLogin: #{username}@#{hostname}" if username
detail += "\nClient IP: #{client_ip}" if client_ip
detail += "\nCommand: #{command}" if command
log_detail = detail.gsub("\n", '; ')
Log.info("#{summary} - #{log_detail}")
options = {
:name => 'audit_create_entry',
:user_email => email,
:summary => summary,
:detail => detail,
:category => RightScale::EventCategories::CATEGORY_SECURITY
}
send_command(options, false, AUDIT_REQUEST_TIMEOUT)
true
rescue Exception => e
Log.error("#{e.class.name}:#{e.message}")
Log.error(e.backtrace.join("\n"))
false
end | [
"def",
"create_audit_entry",
"(",
"email",
",",
"username",
",",
"access",
",",
"command",
",",
"client_ip",
"=",
"nil",
")",
"begin",
"hostname",
"=",
"`",
"`",
".",
"strip",
"rescue",
"Exception",
"=>",
"e",
"hostname",
"=",
"'localhost'",
"end",
"case",
"access",
"when",
":scp",
"then",
"summary",
"=",
"'SSH file copy'",
"detail",
"=",
"\"User copied files copied (scp) to/from host.\"",
"when",
":sftp",
"then",
"summary",
"=",
"'SSH interactive file transfer'",
"detail",
"=",
"\"User initiated an SFTP session.\"",
"when",
":command",
"summary",
"=",
"'SSH command'",
"detail",
"=",
"\"User invoked an interactive program.\"",
"when",
":shell",
"summary",
"=",
"'SSH interactive login'",
"detail",
"=",
"\"User connected and invoked a login shell.\"",
"end",
"detail",
"+=",
"\"\\nLogin: #{username}@#{hostname}\"",
"if",
"username",
"detail",
"+=",
"\"\\nClient IP: #{client_ip}\"",
"if",
"client_ip",
"detail",
"+=",
"\"\\nCommand: #{command}\"",
"if",
"command",
"log_detail",
"=",
"detail",
".",
"gsub",
"(",
"\"\\n\"",
",",
"'; '",
")",
"Log",
".",
"info",
"(",
"\"#{summary} - #{log_detail}\"",
")",
"options",
"=",
"{",
":name",
"=>",
"'audit_create_entry'",
",",
":user_email",
"=>",
"email",
",",
":summary",
"=>",
"summary",
",",
":detail",
"=>",
"detail",
",",
":category",
"=>",
"RightScale",
"::",
"EventCategories",
"::",
"CATEGORY_SECURITY",
"}",
"send_command",
"(",
"options",
",",
"false",
",",
"AUDIT_REQUEST_TIMEOUT",
")",
"true",
"rescue",
"Exception",
"=>",
"e",
"Log",
".",
"error",
"(",
"\"#{e.class.name}:#{e.message}\"",
")",
"Log",
".",
"error",
"(",
"e",
".",
"backtrace",
".",
"join",
"(",
"\"\\n\"",
")",
")",
"false",
"end"
] | Create an audit entry to record this user's access. The entry is created
asynchronously and this method never raises exceptions even if the
request fails or times out. Thus, this is "best-effort" auditing and
should not be relied upon!
=== Parameters
email(String):: the user's email address
username(String):: the user's email address
access(Symbol):: mode of access; one of :scp, :sftp, :command or :shell
command(String):: exact command that is being executed via SSH
client_ip(String):: origin IP address
=== Return
Returns true on success, false otherwise | [
"Create",
"an",
"audit",
"entry",
"to",
"record",
"this",
"user",
"s",
"access",
".",
"The",
"entry",
"is",
"created",
"asynchronously",
"and",
"this",
"method",
"never",
"raises",
"exceptions",
"even",
"if",
"the",
"request",
"fails",
"or",
"times",
"out",
".",
"Thus",
"this",
"is",
"best",
"-",
"effort",
"auditing",
"and",
"should",
"not",
"be",
"relied",
"upon!"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/scripts/thunker.rb#L218-L261 | train |
rightscale/right_link | scripts/thunker.rb | RightScale.Thunker.display_motd | def display_motd
if ::File.exists?("/var/run/motd.dynamic")
# Ubuntu 14.04+ motd location
puts ::File.read("/var/run/motd.dynamic")
elsif ::File.exists?("/var/run/motd")
# Ubuntu 12.04 motd location
puts ::File.read("/var/run/motd")
elsif ::File.exists?("/etc/motd")
# Legacy (CentOS 6 style)
puts ::File.read("/etc/motd")
end
rescue
nil
end | ruby | def display_motd
if ::File.exists?("/var/run/motd.dynamic")
# Ubuntu 14.04+ motd location
puts ::File.read("/var/run/motd.dynamic")
elsif ::File.exists?("/var/run/motd")
# Ubuntu 12.04 motd location
puts ::File.read("/var/run/motd")
elsif ::File.exists?("/etc/motd")
# Legacy (CentOS 6 style)
puts ::File.read("/etc/motd")
end
rescue
nil
end | [
"def",
"display_motd",
"if",
"::",
"File",
".",
"exists?",
"(",
"\"/var/run/motd.dynamic\"",
")",
"puts",
"::",
"File",
".",
"read",
"(",
"\"/var/run/motd.dynamic\"",
")",
"elsif",
"::",
"File",
".",
"exists?",
"(",
"\"/var/run/motd\"",
")",
"puts",
"::",
"File",
".",
"read",
"(",
"\"/var/run/motd\"",
")",
"elsif",
"::",
"File",
".",
"exists?",
"(",
"\"/etc/motd\"",
")",
"puts",
"::",
"File",
".",
"read",
"(",
"\"/etc/motd\"",
")",
"end",
"rescue",
"nil",
"end"
] | Display the Message of the Day if it exists. | [
"Display",
"the",
"Message",
"of",
"the",
"Day",
"if",
"it",
"exists",
"."
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/scripts/thunker.rb#L271-L284 | train |
OpenBEL/bel.rb | lib/bel/quoting.rb | BEL.Quoting.quote | def quote(value)
string = value.to_s
unquoted = unquote(string)
escaped = unquoted.gsub(QuoteNotEscapedMatcher, "\\\"")
%Q{"#{escaped}"}
end | ruby | def quote(value)
string = value.to_s
unquoted = unquote(string)
escaped = unquoted.gsub(QuoteNotEscapedMatcher, "\\\"")
%Q{"#{escaped}"}
end | [
"def",
"quote",
"(",
"value",
")",
"string",
"=",
"value",
".",
"to_s",
"unquoted",
"=",
"unquote",
"(",
"string",
")",
"escaped",
"=",
"unquoted",
".",
"gsub",
"(",
"QuoteNotEscapedMatcher",
",",
"\"\\\\\\\"\"",
")",
"%Q{\"#{escaped}\"}",
"end"
] | Returns +value+ surrounded by double quotes. This method is idempotent
so +value+ will only be quoted once regardless of how may times the
method is called on it.
@example Quoting a BEL parameter.
quote("apoptotic process")
# => "\"apoptotic process\""
@example Escaping quotes within a value.
quote("vesicle fusion with \"Golgi apparatus\"")
# => "\"vesicle fusion with \\\"Golgi apparatus\\\"\""
@parameter [#to_s] value a value to be quoted
@return [String] value surrounded by double quotes | [
"Returns",
"+",
"value",
"+",
"surrounded",
"by",
"double",
"quotes",
".",
"This",
"method",
"is",
"idempotent",
"so",
"+",
"value",
"+",
"will",
"only",
"be",
"quoted",
"once",
"regardless",
"of",
"how",
"may",
"times",
"the",
"method",
"is",
"called",
"on",
"it",
"."
] | 8a6d30bda6569d6810ef596dd094247ef18fbdda | https://github.com/OpenBEL/bel.rb/blob/8a6d30bda6569d6810ef596dd094247ef18fbdda/lib/bel/quoting.rb#L54-L59 | train |
rightscale/right_link | scripts/cloud_controller.rb | RightScale.CloudController.control | def control(options)
fail("No action specified on the command line.") unless (options[:action] || options[:requires_network_config])
name = options[:name]
parameters = options[:parameters] || []
only_if = options[:only_if]
verbose = options[:verbose]
# support either single or a comma-delimited list of actions to execute
# sequentially (e.g. "--action clear_state,wait_for_instance_ready,write_user_metadata")
# (because we need to split bootstrap actions up in Windows case).
actions = options[:action].to_s.split(',').inject([]) do |result, action|
unless (action = action.strip).empty?
action = action.to_sym
case action
when :bootstrap
# bootstrap is shorthand for all standard actions performed on boot
result += [:clear_state, :wait_for_instance_ready, :write_cloud_metadata, :write_user_metadata, :wait_for_eip]
only_if = true
else
result << action
end
end
result
end
cloud = CloudFactory.instance.create(name, :logger => default_logger(verbose))
actions.each do |action|
if cloud.respond_to?(action)
# Expect most methods to return ActionResult, but a cloud can expose any
# custom method so we can't assume return type
result = cloud.send(action, *parameters)
$stderr.puts result.error if result.respond_to?(:error) && result.error
$stdout.puts result.output if verbose && result.respond_to?(:output) && result.output
if result.respond_to?(:exitstatus) && (result.exitstatus != 0)
raise StandardError, "Action #{action} failed with status #{result.exitstatus}"
end
elsif only_if
next
else
raise ArgumentError, "ERROR: Unknown cloud action: #{action}"
end
end
if options[:requires_network_config]
exit(cloud.requires_network_config? ? 0 : 1)
end
end | ruby | def control(options)
fail("No action specified on the command line.") unless (options[:action] || options[:requires_network_config])
name = options[:name]
parameters = options[:parameters] || []
only_if = options[:only_if]
verbose = options[:verbose]
# support either single or a comma-delimited list of actions to execute
# sequentially (e.g. "--action clear_state,wait_for_instance_ready,write_user_metadata")
# (because we need to split bootstrap actions up in Windows case).
actions = options[:action].to_s.split(',').inject([]) do |result, action|
unless (action = action.strip).empty?
action = action.to_sym
case action
when :bootstrap
# bootstrap is shorthand for all standard actions performed on boot
result += [:clear_state, :wait_for_instance_ready, :write_cloud_metadata, :write_user_metadata, :wait_for_eip]
only_if = true
else
result << action
end
end
result
end
cloud = CloudFactory.instance.create(name, :logger => default_logger(verbose))
actions.each do |action|
if cloud.respond_to?(action)
# Expect most methods to return ActionResult, but a cloud can expose any
# custom method so we can't assume return type
result = cloud.send(action, *parameters)
$stderr.puts result.error if result.respond_to?(:error) && result.error
$stdout.puts result.output if verbose && result.respond_to?(:output) && result.output
if result.respond_to?(:exitstatus) && (result.exitstatus != 0)
raise StandardError, "Action #{action} failed with status #{result.exitstatus}"
end
elsif only_if
next
else
raise ArgumentError, "ERROR: Unknown cloud action: #{action}"
end
end
if options[:requires_network_config]
exit(cloud.requires_network_config? ? 0 : 1)
end
end | [
"def",
"control",
"(",
"options",
")",
"fail",
"(",
"\"No action specified on the command line.\"",
")",
"unless",
"(",
"options",
"[",
":action",
"]",
"||",
"options",
"[",
":requires_network_config",
"]",
")",
"name",
"=",
"options",
"[",
":name",
"]",
"parameters",
"=",
"options",
"[",
":parameters",
"]",
"||",
"[",
"]",
"only_if",
"=",
"options",
"[",
":only_if",
"]",
"verbose",
"=",
"options",
"[",
":verbose",
"]",
"actions",
"=",
"options",
"[",
":action",
"]",
".",
"to_s",
".",
"split",
"(",
"','",
")",
".",
"inject",
"(",
"[",
"]",
")",
"do",
"|",
"result",
",",
"action",
"|",
"unless",
"(",
"action",
"=",
"action",
".",
"strip",
")",
".",
"empty?",
"action",
"=",
"action",
".",
"to_sym",
"case",
"action",
"when",
":bootstrap",
"result",
"+=",
"[",
":clear_state",
",",
":wait_for_instance_ready",
",",
":write_cloud_metadata",
",",
":write_user_metadata",
",",
":wait_for_eip",
"]",
"only_if",
"=",
"true",
"else",
"result",
"<<",
"action",
"end",
"end",
"result",
"end",
"cloud",
"=",
"CloudFactory",
".",
"instance",
".",
"create",
"(",
"name",
",",
":logger",
"=>",
"default_logger",
"(",
"verbose",
")",
")",
"actions",
".",
"each",
"do",
"|",
"action",
"|",
"if",
"cloud",
".",
"respond_to?",
"(",
"action",
")",
"result",
"=",
"cloud",
".",
"send",
"(",
"action",
",",
"*",
"parameters",
")",
"$stderr",
".",
"puts",
"result",
".",
"error",
"if",
"result",
".",
"respond_to?",
"(",
":error",
")",
"&&",
"result",
".",
"error",
"$stdout",
".",
"puts",
"result",
".",
"output",
"if",
"verbose",
"&&",
"result",
".",
"respond_to?",
"(",
":output",
")",
"&&",
"result",
".",
"output",
"if",
"result",
".",
"respond_to?",
"(",
":exitstatus",
")",
"&&",
"(",
"result",
".",
"exitstatus",
"!=",
"0",
")",
"raise",
"StandardError",
",",
"\"Action #{action} failed with status #{result.exitstatus}\"",
"end",
"elsif",
"only_if",
"next",
"else",
"raise",
"ArgumentError",
",",
"\"ERROR: Unknown cloud action: #{action}\"",
"end",
"end",
"if",
"options",
"[",
":requires_network_config",
"]",
"exit",
"(",
"cloud",
".",
"requires_network_config?",
"?",
"0",
":",
"1",
")",
"end",
"end"
] | Parse arguments and run | [
"Parse",
"arguments",
"and",
"run"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/scripts/cloud_controller.rb#L62-L109 | train |
ruby-journal/nguyen | lib/nguyen/fdf.rb | Nguyen.Fdf.to_fdf | def to_fdf
fdf = header
@data.each do |key, value|
if Hash === value
value.each do |sub_key, sub_value|
fdf << field("#{key}_#{sub_key}", sub_value)
end
else
fdf << field(key, value)
end
end
fdf << footer
return fdf
end | ruby | def to_fdf
fdf = header
@data.each do |key, value|
if Hash === value
value.each do |sub_key, sub_value|
fdf << field("#{key}_#{sub_key}", sub_value)
end
else
fdf << field(key, value)
end
end
fdf << footer
return fdf
end | [
"def",
"to_fdf",
"fdf",
"=",
"header",
"@data",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"if",
"Hash",
"===",
"value",
"value",
".",
"each",
"do",
"|",
"sub_key",
",",
"sub_value",
"|",
"fdf",
"<<",
"field",
"(",
"\"#{key}_#{sub_key}\"",
",",
"sub_value",
")",
"end",
"else",
"fdf",
"<<",
"field",
"(",
"key",
",",
"value",
")",
"end",
"end",
"fdf",
"<<",
"footer",
"return",
"fdf",
"end"
] | generate FDF content | [
"generate",
"FDF",
"content"
] | 6c7661bb2a975a5269fa71f3a0a63fe262932e7e | https://github.com/ruby-journal/nguyen/blob/6c7661bb2a975a5269fa71f3a0a63fe262932e7e/lib/nguyen/fdf.rb#L21-L36 | train |
ruby-journal/nguyen | lib/nguyen/xfdf.rb | Nguyen.Xfdf.to_xfdf | def to_xfdf
builder = Nokogiri::XML::Builder.new(encoding: 'UTF-8') do |xml|
xml.xfdf('xmlns' => 'http://ns.adobe.com/xfdf/', 'xml:space' => 'preserve') {
xml.f(href: options[:file]) if options[:file]
xml.ids(original: options[:id], modified: options[:id]) if options[:id]
xml.fields {
@fields.each do |field, value|
xml.field(name: field) {
if value.is_a? Array
value.each { |item| xml.value(item.to_s) }
else
xml.value(value.to_s)
end
}
end
}
}
end
builder.to_xml(save_with: Nokogiri::XML::Node::SaveOptions::AS_XML)
end | ruby | def to_xfdf
builder = Nokogiri::XML::Builder.new(encoding: 'UTF-8') do |xml|
xml.xfdf('xmlns' => 'http://ns.adobe.com/xfdf/', 'xml:space' => 'preserve') {
xml.f(href: options[:file]) if options[:file]
xml.ids(original: options[:id], modified: options[:id]) if options[:id]
xml.fields {
@fields.each do |field, value|
xml.field(name: field) {
if value.is_a? Array
value.each { |item| xml.value(item.to_s) }
else
xml.value(value.to_s)
end
}
end
}
}
end
builder.to_xml(save_with: Nokogiri::XML::Node::SaveOptions::AS_XML)
end | [
"def",
"to_xfdf",
"builder",
"=",
"Nokogiri",
"::",
"XML",
"::",
"Builder",
".",
"new",
"(",
"encoding",
":",
"'UTF-8'",
")",
"do",
"|",
"xml",
"|",
"xml",
".",
"xfdf",
"(",
"'xmlns'",
"=>",
"'http://ns.adobe.com/xfdf/'",
",",
"'xml:space'",
"=>",
"'preserve'",
")",
"{",
"xml",
".",
"f",
"(",
"href",
":",
"options",
"[",
":file",
"]",
")",
"if",
"options",
"[",
":file",
"]",
"xml",
".",
"ids",
"(",
"original",
":",
"options",
"[",
":id",
"]",
",",
"modified",
":",
"options",
"[",
":id",
"]",
")",
"if",
"options",
"[",
":id",
"]",
"xml",
".",
"fields",
"{",
"@fields",
".",
"each",
"do",
"|",
"field",
",",
"value",
"|",
"xml",
".",
"field",
"(",
"name",
":",
"field",
")",
"{",
"if",
"value",
".",
"is_a?",
"Array",
"value",
".",
"each",
"{",
"|",
"item",
"|",
"xml",
".",
"value",
"(",
"item",
".",
"to_s",
")",
"}",
"else",
"xml",
".",
"value",
"(",
"value",
".",
"to_s",
")",
"end",
"}",
"end",
"}",
"}",
"end",
"builder",
".",
"to_xml",
"(",
"save_with",
":",
"Nokogiri",
"::",
"XML",
"::",
"Node",
"::",
"SaveOptions",
"::",
"AS_XML",
")",
"end"
] | generate XFDF content | [
"generate",
"XFDF",
"content"
] | 6c7661bb2a975a5269fa71f3a0a63fe262932e7e | https://github.com/ruby-journal/nguyen/blob/6c7661bb2a975a5269fa71f3a0a63fe262932e7e/lib/nguyen/xfdf.rb#L17-L36 | train |
rightscale/right_link | lib/instance/network_configurator.rb | RightScale.NetworkConfigurator.configure_routes | def configure_routes
# required metadata values
routes = ENV.keys.select { |k| k =~ /^RS_ROUTE(\d+)$/ }
seen_route = {}
routes.each do |route|
begin
nat_server_ip, cidr = ENV[route].strip.split(/[,:]/)
if seen_route[cidr]
seen_nat_server_ip = seen_route[cidr]
logger.warn "Already added route #{cidr} to gateway #{seen_nat_server_ip}, skipping adding it to #{nat_server_ip}"
else
seen_route[cidr] = nat_server_ip
network_route_add(cidr.to_s.strip, nat_server_ip.to_s.strip)
end
rescue Exception => e
logger.error "Detected an error while adding route to NAT #{e.class}: #{e.message}"
end
end
true
end | ruby | def configure_routes
# required metadata values
routes = ENV.keys.select { |k| k =~ /^RS_ROUTE(\d+)$/ }
seen_route = {}
routes.each do |route|
begin
nat_server_ip, cidr = ENV[route].strip.split(/[,:]/)
if seen_route[cidr]
seen_nat_server_ip = seen_route[cidr]
logger.warn "Already added route #{cidr} to gateway #{seen_nat_server_ip}, skipping adding it to #{nat_server_ip}"
else
seen_route[cidr] = nat_server_ip
network_route_add(cidr.to_s.strip, nat_server_ip.to_s.strip)
end
rescue Exception => e
logger.error "Detected an error while adding route to NAT #{e.class}: #{e.message}"
end
end
true
end | [
"def",
"configure_routes",
"routes",
"=",
"ENV",
".",
"keys",
".",
"select",
"{",
"|",
"k",
"|",
"k",
"=~",
"/",
"\\d",
"/",
"}",
"seen_route",
"=",
"{",
"}",
"routes",
".",
"each",
"do",
"|",
"route",
"|",
"begin",
"nat_server_ip",
",",
"cidr",
"=",
"ENV",
"[",
"route",
"]",
".",
"strip",
".",
"split",
"(",
"/",
"/",
")",
"if",
"seen_route",
"[",
"cidr",
"]",
"seen_nat_server_ip",
"=",
"seen_route",
"[",
"cidr",
"]",
"logger",
".",
"warn",
"\"Already added route #{cidr} to gateway #{seen_nat_server_ip}, skipping adding it to #{nat_server_ip}\"",
"else",
"seen_route",
"[",
"cidr",
"]",
"=",
"nat_server_ip",
"network_route_add",
"(",
"cidr",
".",
"to_s",
".",
"strip",
",",
"nat_server_ip",
".",
"to_s",
".",
"strip",
")",
"end",
"rescue",
"Exception",
"=>",
"e",
"logger",
".",
"error",
"\"Detected an error while adding route to NAT #{e.class}: #{e.message}\"",
"end",
"end",
"true",
"end"
] | NAT Routing Support
Add routes to external networks via local NAT server
no-op if no RS_ROUTE<N> variables are defined
=== Return
result(True):: Always true | [
"NAT",
"Routing",
"Support"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/network_configurator.rb#L85-L104 | train |
rightscale/right_link | lib/instance/network_configurator.rb | RightScale.NetworkConfigurator.network_route_add | def network_route_add(network, nat_server_ip)
raise "ERROR: invalid nat_server_ip : '#{nat_server_ip}'" unless valid_ipv4?(nat_server_ip)
raise "ERROR: invalid CIDR network : '#{network}'" unless valid_ipv4_cidr?(network)
true
end | ruby | def network_route_add(network, nat_server_ip)
raise "ERROR: invalid nat_server_ip : '#{nat_server_ip}'" unless valid_ipv4?(nat_server_ip)
raise "ERROR: invalid CIDR network : '#{network}'" unless valid_ipv4_cidr?(network)
true
end | [
"def",
"network_route_add",
"(",
"network",
",",
"nat_server_ip",
")",
"raise",
"\"ERROR: invalid nat_server_ip : '#{nat_server_ip}'\"",
"unless",
"valid_ipv4?",
"(",
"nat_server_ip",
")",
"raise",
"\"ERROR: invalid CIDR network : '#{network}'\"",
"unless",
"valid_ipv4_cidr?",
"(",
"network",
")",
"true",
"end"
] | Add route to network through NAT server
Will not add if route already exists
=== Parameters
network(String):: target network in CIDR notation
nat_server_ip(String):: the IP address of the NAT "router"
=== Raise
StandardError:: Route command fails
=== Return
result(True):: Always returns true | [
"Add",
"route",
"to",
"network",
"through",
"NAT",
"server"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/network_configurator.rb#L119-L123 | train |
rightscale/right_link | lib/instance/network_configurator.rb | RightScale.NetworkConfigurator.network_route_exists? | def network_route_exists?(network, nat_server_ip)
routes = routes_show()
matchdata = routes.match(route_regex(network, nat_server_ip))
matchdata != nil
end | ruby | def network_route_exists?(network, nat_server_ip)
routes = routes_show()
matchdata = routes.match(route_regex(network, nat_server_ip))
matchdata != nil
end | [
"def",
"network_route_exists?",
"(",
"network",
",",
"nat_server_ip",
")",
"routes",
"=",
"routes_show",
"(",
")",
"matchdata",
"=",
"routes",
".",
"match",
"(",
"route_regex",
"(",
"network",
",",
"nat_server_ip",
")",
")",
"matchdata",
"!=",
"nil",
"end"
] | Is a route defined to network via NAT "router"?
=== Parameters
network(String):: target network in CIDR notation
nat_server_ip(String):: the IP address of the NAT "router"
=== Return
result(Boolean):: true if route exists, else false | [
"Is",
"a",
"route",
"defined",
"to",
"network",
"via",
"NAT",
"router",
"?"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/network_configurator.rb#L139-L143 | train |
rightscale/right_link | lib/instance/network_configurator.rb | RightScale.NetworkConfigurator.add_static_ip | def add_static_ip(n_ip=0)
begin
# required metadata values
ipaddr = ENV["RS_IP#{n_ip}_ADDR"]
netmask = ENV["RS_IP#{n_ip}_NETMASK"]
# optional
gateway = ENV["RS_IP#{n_ip}_GATEWAY"]
device = shell_escape_if_necessary(device_name_from_mac(ENV["RS_IP#{n_ip}_MAC"]))
if ipaddr
# configure network adaptor
attached_nameservers = nameservers_for_device(n_ip)
logger.info "Setting up static IP address '#{ipaddr}' for '#{device}'"
logger.debug "Netmask: '#{netmask}' ; Gateway: '#{gateway}'"
logger.debug "Nameservers: '#{attached_nameservers.join(' ')}'" if attached_nameservers
raise "FATAL: RS_IP#{n_ip}_NETMASK not defined ; Cannot configure static IP address" unless netmask
ip = configure_network_adaptor(device, ipaddr, netmask, gateway, attached_nameservers)
end
rescue Exception => e
logger.error "Detected an error while configuring static IP#{n_ip}: #{e.message}"
raise e
end
end | ruby | def add_static_ip(n_ip=0)
begin
# required metadata values
ipaddr = ENV["RS_IP#{n_ip}_ADDR"]
netmask = ENV["RS_IP#{n_ip}_NETMASK"]
# optional
gateway = ENV["RS_IP#{n_ip}_GATEWAY"]
device = shell_escape_if_necessary(device_name_from_mac(ENV["RS_IP#{n_ip}_MAC"]))
if ipaddr
# configure network adaptor
attached_nameservers = nameservers_for_device(n_ip)
logger.info "Setting up static IP address '#{ipaddr}' for '#{device}'"
logger.debug "Netmask: '#{netmask}' ; Gateway: '#{gateway}'"
logger.debug "Nameservers: '#{attached_nameservers.join(' ')}'" if attached_nameservers
raise "FATAL: RS_IP#{n_ip}_NETMASK not defined ; Cannot configure static IP address" unless netmask
ip = configure_network_adaptor(device, ipaddr, netmask, gateway, attached_nameservers)
end
rescue Exception => e
logger.error "Detected an error while configuring static IP#{n_ip}: #{e.message}"
raise e
end
end | [
"def",
"add_static_ip",
"(",
"n_ip",
"=",
"0",
")",
"begin",
"ipaddr",
"=",
"ENV",
"[",
"\"RS_IP#{n_ip}_ADDR\"",
"]",
"netmask",
"=",
"ENV",
"[",
"\"RS_IP#{n_ip}_NETMASK\"",
"]",
"gateway",
"=",
"ENV",
"[",
"\"RS_IP#{n_ip}_GATEWAY\"",
"]",
"device",
"=",
"shell_escape_if_necessary",
"(",
"device_name_from_mac",
"(",
"ENV",
"[",
"\"RS_IP#{n_ip}_MAC\"",
"]",
")",
")",
"if",
"ipaddr",
"attached_nameservers",
"=",
"nameservers_for_device",
"(",
"n_ip",
")",
"logger",
".",
"info",
"\"Setting up static IP address '#{ipaddr}' for '#{device}'\"",
"logger",
".",
"debug",
"\"Netmask: '#{netmask}' ; Gateway: '#{gateway}'\"",
"logger",
".",
"debug",
"\"Nameservers: '#{attached_nameservers.join(' ')}'\"",
"if",
"attached_nameservers",
"raise",
"\"FATAL: RS_IP#{n_ip}_NETMASK not defined ; Cannot configure static IP address\"",
"unless",
"netmask",
"ip",
"=",
"configure_network_adaptor",
"(",
"device",
",",
"ipaddr",
",",
"netmask",
",",
"gateway",
",",
"attached_nameservers",
")",
"end",
"rescue",
"Exception",
"=>",
"e",
"logger",
".",
"error",
"\"Detected an error while configuring static IP#{n_ip}: #{e.message}\"",
"raise",
"e",
"end",
"end"
] | Sets single network adapter static IP addresse and nameservers
Parameters
n_ip(Fixnum):: network adapter index | [
"Sets",
"single",
"network",
"adapter",
"static",
"IP",
"addresse",
"and",
"nameservers"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/network_configurator.rb#L191-L215 | train |
rightscale/right_link | lib/instance/network_configurator.rb | RightScale.NetworkConfigurator.configure_network_adaptor | def configure_network_adaptor(device, ip, netmask, gateway, nameservers)
raise "ERROR: invalid IP address: '#{ip}'" unless valid_ipv4?(ip)
raise "ERROR: invalid netmask: '#{netmask}'" unless valid_ipv4?(netmask)
# gateway is optional
if gateway
raise "ERROR: invalid gateway IP address: '#{gateway}'" unless valid_ipv4?(gateway)
end
end | ruby | def configure_network_adaptor(device, ip, netmask, gateway, nameservers)
raise "ERROR: invalid IP address: '#{ip}'" unless valid_ipv4?(ip)
raise "ERROR: invalid netmask: '#{netmask}'" unless valid_ipv4?(netmask)
# gateway is optional
if gateway
raise "ERROR: invalid gateway IP address: '#{gateway}'" unless valid_ipv4?(gateway)
end
end | [
"def",
"configure_network_adaptor",
"(",
"device",
",",
"ip",
",",
"netmask",
",",
"gateway",
",",
"nameservers",
")",
"raise",
"\"ERROR: invalid IP address: '#{ip}'\"",
"unless",
"valid_ipv4?",
"(",
"ip",
")",
"raise",
"\"ERROR: invalid netmask: '#{netmask}'\"",
"unless",
"valid_ipv4?",
"(",
"netmask",
")",
"if",
"gateway",
"raise",
"\"ERROR: invalid gateway IP address: '#{gateway}'\"",
"unless",
"valid_ipv4?",
"(",
"gateway",
")",
"end",
"end"
] | Configures a single network adapter with a static IP address
Parameters
device(String):: device to be configured
ip(String):: static IP to be set
netmask(String):: netmask to be set
gateway(String):: default gateway IP to be set
nameservers(Array):: array of nameservers to be set | [
"Configures",
"a",
"single",
"network",
"adapter",
"with",
"a",
"static",
"IP",
"address"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/network_configurator.rb#L227-L235 | train |
rightscale/right_link | lib/instance/network_configurator.rb | RightScale.NetworkConfigurator.nameservers_for_device | def nameservers_for_device(n_ip)
nameservers = []
raw_nameservers = ENV["RS_IP#{n_ip}_NAMESERVERS"].to_s.strip.split(/[, ]+/)
raw_nameservers.each do |nameserver|
if valid_ipv4?(nameserver)
nameservers << nameserver
else
# Non-fatal error, we only need one working
logger.error("Invalid nameserver #{nameserver} for interface##{n_ip}")
end
end
# Also a non-fatal error, DHCP or another interface specify nameservers and we're still good
logger.warn("No valid nameservers specified for static interface##{n_ip}") unless nameservers.length > 0
nameservers
end | ruby | def nameservers_for_device(n_ip)
nameservers = []
raw_nameservers = ENV["RS_IP#{n_ip}_NAMESERVERS"].to_s.strip.split(/[, ]+/)
raw_nameservers.each do |nameserver|
if valid_ipv4?(nameserver)
nameservers << nameserver
else
# Non-fatal error, we only need one working
logger.error("Invalid nameserver #{nameserver} for interface##{n_ip}")
end
end
# Also a non-fatal error, DHCP or another interface specify nameservers and we're still good
logger.warn("No valid nameservers specified for static interface##{n_ip}") unless nameservers.length > 0
nameservers
end | [
"def",
"nameservers_for_device",
"(",
"n_ip",
")",
"nameservers",
"=",
"[",
"]",
"raw_nameservers",
"=",
"ENV",
"[",
"\"RS_IP#{n_ip}_NAMESERVERS\"",
"]",
".",
"to_s",
".",
"strip",
".",
"split",
"(",
"/",
"/",
")",
"raw_nameservers",
".",
"each",
"do",
"|",
"nameserver",
"|",
"if",
"valid_ipv4?",
"(",
"nameserver",
")",
"nameservers",
"<<",
"nameserver",
"else",
"logger",
".",
"error",
"(",
"\"Invalid nameserver #{nameserver} for interface##{n_ip}\"",
")",
"end",
"end",
"logger",
".",
"warn",
"(",
"\"No valid nameservers specified for static interface##{n_ip}\"",
")",
"unless",
"nameservers",
".",
"length",
">",
"0",
"nameservers",
"end"
] | Returns a validated list of nameservers
== Parameters
none | [
"Returns",
"a",
"validated",
"list",
"of",
"nameservers"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/network_configurator.rb#L241-L255 | train |
rightscale/right_link | scripts/tagger.rb | RightScale.Tagger.run | def run(options)
fail_if_right_agent_is_not_running
check_privileges
set_logger(options)
missing_argument unless options.include?(:action)
# Don't use send_command callback as it swallows exceptions by design
res = send_command(build_cmd(options), options[:verbose], options[:timeout])
case options[:action]
when :get_tags
get_tags(res, options)
when :query_tags
query_tags(res, options)
when :add_tag
add_tag(res, options)
when :remove_tag
remove_tag(res, options)
else
write_error(res)
end
rescue SystemExit => e
raise e
rescue Exception => e
fail(e)
end | ruby | def run(options)
fail_if_right_agent_is_not_running
check_privileges
set_logger(options)
missing_argument unless options.include?(:action)
# Don't use send_command callback as it swallows exceptions by design
res = send_command(build_cmd(options), options[:verbose], options[:timeout])
case options[:action]
when :get_tags
get_tags(res, options)
when :query_tags
query_tags(res, options)
when :add_tag
add_tag(res, options)
when :remove_tag
remove_tag(res, options)
else
write_error(res)
end
rescue SystemExit => e
raise e
rescue Exception => e
fail(e)
end | [
"def",
"run",
"(",
"options",
")",
"fail_if_right_agent_is_not_running",
"check_privileges",
"set_logger",
"(",
"options",
")",
"missing_argument",
"unless",
"options",
".",
"include?",
"(",
":action",
")",
"res",
"=",
"send_command",
"(",
"build_cmd",
"(",
"options",
")",
",",
"options",
"[",
":verbose",
"]",
",",
"options",
"[",
":timeout",
"]",
")",
"case",
"options",
"[",
":action",
"]",
"when",
":get_tags",
"get_tags",
"(",
"res",
",",
"options",
")",
"when",
":query_tags",
"query_tags",
"(",
"res",
",",
"options",
")",
"when",
":add_tag",
"add_tag",
"(",
"res",
",",
"options",
")",
"when",
":remove_tag",
"remove_tag",
"(",
"res",
",",
"options",
")",
"else",
"write_error",
"(",
"res",
")",
"end",
"rescue",
"SystemExit",
"=>",
"e",
"raise",
"e",
"rescue",
"Exception",
"=>",
"e",
"fail",
"(",
"e",
")",
"end"
] | Manage instance tags
=== Parameters
options(Hash):: Hash of options as defined in +parse_args+
=== Return
true:: Always return true | [
"Manage",
"instance",
"tags"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/scripts/tagger.rb#L144-L168 | train |
rightscale/right_link | scripts/tagger.rb | RightScale.Tagger.format_output | def format_output(result, format)
case format
when :json
JSON.pretty_generate(result)
when :yaml
YAML.dump(result)
when :text
result = result.keys if result.respond_to?(:keys)
result.join(" ")
else
raise ArgumentError, "Unknown output format #{format}"
end
end | ruby | def format_output(result, format)
case format
when :json
JSON.pretty_generate(result)
when :yaml
YAML.dump(result)
when :text
result = result.keys if result.respond_to?(:keys)
result.join(" ")
else
raise ArgumentError, "Unknown output format #{format}"
end
end | [
"def",
"format_output",
"(",
"result",
",",
"format",
")",
"case",
"format",
"when",
":json",
"JSON",
".",
"pretty_generate",
"(",
"result",
")",
"when",
":yaml",
"YAML",
".",
"dump",
"(",
"result",
")",
"when",
":text",
"result",
"=",
"result",
".",
"keys",
"if",
"result",
".",
"respond_to?",
"(",
":keys",
")",
"result",
".",
"join",
"(",
"\" \"",
")",
"else",
"raise",
"ArgumentError",
",",
"\"Unknown output format #{format}\"",
"end",
"end"
] | Format output for display to user
=== Parameter
result(Object):: JSON-compatible data structure (array, hash, etc)
format(String):: how to print output - json, yaml, text
=== Return
a String containing the specified output format | [
"Format",
"output",
"for",
"display",
"to",
"user"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/scripts/tagger.rb#L234-L246 | train |
rightscale/right_link | lib/instance/audit_cook_stub.rb | RightScale.AuditCookStub.forward_audit | def forward_audit(kind, text, thread_name, options)
auditor = @auditors[thread_name]
return unless auditor
if kind == :append_output
auditor.append_output(text)
else
auditor.__send__(kind, text, options)
end
end | ruby | def forward_audit(kind, text, thread_name, options)
auditor = @auditors[thread_name]
return unless auditor
if kind == :append_output
auditor.append_output(text)
else
auditor.__send__(kind, text, options)
end
end | [
"def",
"forward_audit",
"(",
"kind",
",",
"text",
",",
"thread_name",
",",
"options",
")",
"auditor",
"=",
"@auditors",
"[",
"thread_name",
"]",
"return",
"unless",
"auditor",
"if",
"kind",
"==",
":append_output",
"auditor",
".",
"append_output",
"(",
"text",
")",
"else",
"auditor",
".",
"__send__",
"(",
"kind",
",",
"text",
",",
"options",
")",
"end",
"end"
] | Forward audit command received from cook using audit proxy
=== Parameters
kind(Symbol):: Kind of audit, one of :append_info, :append_error, :create_new_section, :update_status and :append_output
text(String):: Audit content
thread_name(String):: thread name for audit or default
options[:category]:: Optional, associated event category, one of RightScale::EventCategories
=== Raise
RuntimeError:: If audit_proxy is not set prior to calling this | [
"Forward",
"audit",
"command",
"received",
"from",
"cook",
"using",
"audit",
"proxy"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/audit_cook_stub.rb#L59-L67 | train |
rightscale/right_link | lib/instance/audit_cook_stub.rb | RightScale.AuditCookStub.close | def close(thread_name)
close_callback = @close_callbacks[thread_name]
close_callback.call if close_callback
true
ensure
@auditors[thread_name] = nil
@close_callbacks[thread_name] = nil
end | ruby | def close(thread_name)
close_callback = @close_callbacks[thread_name]
close_callback.call if close_callback
true
ensure
@auditors[thread_name] = nil
@close_callbacks[thread_name] = nil
end | [
"def",
"close",
"(",
"thread_name",
")",
"close_callback",
"=",
"@close_callbacks",
"[",
"thread_name",
"]",
"close_callback",
".",
"call",
"if",
"close_callback",
"true",
"ensure",
"@auditors",
"[",
"thread_name",
"]",
"=",
"nil",
"@close_callbacks",
"[",
"thread_name",
"]",
"=",
"nil",
"end"
] | Reset proxy object and notify close event listener
=== Parameters
thread_name(String):: execution thread name or default
=== Return
true:: Always return true | [
"Reset",
"proxy",
"object",
"and",
"notify",
"close",
"event",
"listener"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/audit_cook_stub.rb#L93-L100 | train |
rightscale/right_link | lib/instance/cook/repose_downloader.rb | RightScale.ReposeDownloader.download | def download(resource)
client = get_http_client
@size = 0
@speed = 0
@sanitized_resource = sanitize_resource(resource)
resource = parse_resource(resource)
attempts = 0
begin
balancer.request do |endpoint|
RightSupport::Net::SSL.with_expected_hostname(ips[endpoint]) do
logger.info("Requesting '#{sanitized_resource}' from '#{endpoint}'")
attempts += 1
t0 = Time.now
# Previously we accessed RestClient directly and used it's wrapper method to instantiate
# a RestClient::Request object. This wrapper was not passing all options down the stack
# so now we invoke the RestClient::Request object directly, passing it our desired options
client.execute(:method => :get, :url => "https://#{endpoint}:443#{resource}", :timeout => calculate_timeout(attempts),
:verify_ssl => OpenSSL::SSL::VERIFY_PEER, :ssl_ca_file => get_ca_file,
:ssl_version => RightSupport::Net::HTTPClient::DEFAULT_OPTIONS[:ssl_version],
:headers => {:user_agent => "RightLink v#{AgentConfig.protocol_version}",
'X-RightLink-Version' => RightLink.version }) do |response, request, result|
if result.kind_of?(Net::HTTPSuccess)
@size = result.content_length || response.size || 0
@speed = @size / (Time.now - t0)
yield response
else
response.return!(request, result)
end
end
end
end
rescue Exception => e
list = parse_exception_message(e)
message = list.join(", ")
logger.error("Request '#{sanitized_resource}' failed - #{message}")
raise ConnectionException, message unless (list & CONNECTION_EXCEPTIONS).empty?
raise DownloadException, message
end
end | ruby | def download(resource)
client = get_http_client
@size = 0
@speed = 0
@sanitized_resource = sanitize_resource(resource)
resource = parse_resource(resource)
attempts = 0
begin
balancer.request do |endpoint|
RightSupport::Net::SSL.with_expected_hostname(ips[endpoint]) do
logger.info("Requesting '#{sanitized_resource}' from '#{endpoint}'")
attempts += 1
t0 = Time.now
# Previously we accessed RestClient directly and used it's wrapper method to instantiate
# a RestClient::Request object. This wrapper was not passing all options down the stack
# so now we invoke the RestClient::Request object directly, passing it our desired options
client.execute(:method => :get, :url => "https://#{endpoint}:443#{resource}", :timeout => calculate_timeout(attempts),
:verify_ssl => OpenSSL::SSL::VERIFY_PEER, :ssl_ca_file => get_ca_file,
:ssl_version => RightSupport::Net::HTTPClient::DEFAULT_OPTIONS[:ssl_version],
:headers => {:user_agent => "RightLink v#{AgentConfig.protocol_version}",
'X-RightLink-Version' => RightLink.version }) do |response, request, result|
if result.kind_of?(Net::HTTPSuccess)
@size = result.content_length || response.size || 0
@speed = @size / (Time.now - t0)
yield response
else
response.return!(request, result)
end
end
end
end
rescue Exception => e
list = parse_exception_message(e)
message = list.join(", ")
logger.error("Request '#{sanitized_resource}' failed - #{message}")
raise ConnectionException, message unless (list & CONNECTION_EXCEPTIONS).empty?
raise DownloadException, message
end
end | [
"def",
"download",
"(",
"resource",
")",
"client",
"=",
"get_http_client",
"@size",
"=",
"0",
"@speed",
"=",
"0",
"@sanitized_resource",
"=",
"sanitize_resource",
"(",
"resource",
")",
"resource",
"=",
"parse_resource",
"(",
"resource",
")",
"attempts",
"=",
"0",
"begin",
"balancer",
".",
"request",
"do",
"|",
"endpoint",
"|",
"RightSupport",
"::",
"Net",
"::",
"SSL",
".",
"with_expected_hostname",
"(",
"ips",
"[",
"endpoint",
"]",
")",
"do",
"logger",
".",
"info",
"(",
"\"Requesting '#{sanitized_resource}' from '#{endpoint}'\"",
")",
"attempts",
"+=",
"1",
"t0",
"=",
"Time",
".",
"now",
"client",
".",
"execute",
"(",
":method",
"=>",
":get",
",",
":url",
"=>",
"\"https://#{endpoint}:443#{resource}\"",
",",
":timeout",
"=>",
"calculate_timeout",
"(",
"attempts",
")",
",",
":verify_ssl",
"=>",
"OpenSSL",
"::",
"SSL",
"::",
"VERIFY_PEER",
",",
":ssl_ca_file",
"=>",
"get_ca_file",
",",
":ssl_version",
"=>",
"RightSupport",
"::",
"Net",
"::",
"HTTPClient",
"::",
"DEFAULT_OPTIONS",
"[",
":ssl_version",
"]",
",",
":headers",
"=>",
"{",
":user_agent",
"=>",
"\"RightLink v#{AgentConfig.protocol_version}\"",
",",
"'X-RightLink-Version'",
"=>",
"RightLink",
".",
"version",
"}",
")",
"do",
"|",
"response",
",",
"request",
",",
"result",
"|",
"if",
"result",
".",
"kind_of?",
"(",
"Net",
"::",
"HTTPSuccess",
")",
"@size",
"=",
"result",
".",
"content_length",
"||",
"response",
".",
"size",
"||",
"0",
"@speed",
"=",
"@size",
"/",
"(",
"Time",
".",
"now",
"-",
"t0",
")",
"yield",
"response",
"else",
"response",
".",
"return!",
"(",
"request",
",",
"result",
")",
"end",
"end",
"end",
"end",
"rescue",
"Exception",
"=>",
"e",
"list",
"=",
"parse_exception_message",
"(",
"e",
")",
"message",
"=",
"list",
".",
"join",
"(",
"\", \"",
")",
"logger",
".",
"error",
"(",
"\"Request '#{sanitized_resource}' failed - #{message}\"",
")",
"raise",
"ConnectionException",
",",
"message",
"unless",
"(",
"list",
"&",
"CONNECTION_EXCEPTIONS",
")",
".",
"empty?",
"raise",
"DownloadException",
",",
"message",
"end",
"end"
] | Initializes a Downloader with a list of hostnames
The purpose of this method is to instantiate a Downloader.
It will perform DNS resolution on the hostnames provided
and will configure a proxy if necessary
=== Parameters
@param <[String]> Hostnames to resolve
=== Return
@return [Downloader]
Downloads an attachment from Repose
The purpose of this method is to download the specified attachment from Repose
If a failure is encountered it will provide proper feedback regarding the nature
of the failure
=== Parameters
@param [String] Resource URI to parse and fetch
=== Block
@yield [] A block is mandatory
@yieldreturn [String] The stream that is being fetched | [
"Initializes",
"a",
"Downloader",
"with",
"a",
"list",
"of",
"hostnames"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/repose_downloader.rb#L96-L137 | train |
rightscale/right_link | lib/instance/cook/repose_downloader.rb | RightScale.ReposeDownloader.resolve | def resolve(hostnames)
ips = {}
hostnames.each do |hostname|
infos = nil
attempts = RETRY_MAX_ATTEMPTS
begin
infos = Socket.getaddrinfo(hostname, 443, Socket::AF_INET, Socket::SOCK_STREAM, Socket::IPPROTO_TCP)
rescue Exception => e
if attempts > 0
attempts -= 1
retry
else
logger.error "Failed to resolve hostnames (#{e.class.name}: #{e.message})"
raise e
end
end
# Randomly permute the addrinfos of each hostname to help spread load.
infos.shuffle.each do |info|
ip = info[3]
ips[ip] = hostname
end
end
ips
end | ruby | def resolve(hostnames)
ips = {}
hostnames.each do |hostname|
infos = nil
attempts = RETRY_MAX_ATTEMPTS
begin
infos = Socket.getaddrinfo(hostname, 443, Socket::AF_INET, Socket::SOCK_STREAM, Socket::IPPROTO_TCP)
rescue Exception => e
if attempts > 0
attempts -= 1
retry
else
logger.error "Failed to resolve hostnames (#{e.class.name}: #{e.message})"
raise e
end
end
# Randomly permute the addrinfos of each hostname to help spread load.
infos.shuffle.each do |info|
ip = info[3]
ips[ip] = hostname
end
end
ips
end | [
"def",
"resolve",
"(",
"hostnames",
")",
"ips",
"=",
"{",
"}",
"hostnames",
".",
"each",
"do",
"|",
"hostname",
"|",
"infos",
"=",
"nil",
"attempts",
"=",
"RETRY_MAX_ATTEMPTS",
"begin",
"infos",
"=",
"Socket",
".",
"getaddrinfo",
"(",
"hostname",
",",
"443",
",",
"Socket",
"::",
"AF_INET",
",",
"Socket",
"::",
"SOCK_STREAM",
",",
"Socket",
"::",
"IPPROTO_TCP",
")",
"rescue",
"Exception",
"=>",
"e",
"if",
"attempts",
">",
"0",
"attempts",
"-=",
"1",
"retry",
"else",
"logger",
".",
"error",
"\"Failed to resolve hostnames (#{e.class.name}: #{e.message})\"",
"raise",
"e",
"end",
"end",
"infos",
".",
"shuffle",
".",
"each",
"do",
"|",
"info",
"|",
"ip",
"=",
"info",
"[",
"3",
"]",
"ips",
"[",
"ip",
"]",
"=",
"hostname",
"end",
"end",
"ips",
"end"
] | Resolve a list of hostnames to a hash of Hostname => IP Addresses
The purpose of this method is to lookup all IP addresses per hostname and
build a lookup hash that maps IP addresses back to their original hostname
so we can perform TLS hostname verification.
=== Parameters
@param <[String]> Hostnames to resolve
=== Return
@return [Hash]
* :key [<String>] a key (IP Address) that accepts a hostname string as it's value | [
"Resolve",
"a",
"list",
"of",
"hostnames",
"to",
"a",
"hash",
"of",
"Hostname",
"=",
">",
"IP",
"Addresses"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/repose_downloader.rb#L163-L187 | train |
rightscale/right_link | lib/instance/cook/repose_downloader.rb | RightScale.ReposeDownloader.parse_exception_message | def parse_exception_message(e)
if e.kind_of?(RightSupport::Net::NoResult)
# Expected format of exception message: "... endpoints: ('<ip address>' => <exception class name array>, ...)""
i = 0
e.message.split(/\[|\]/).select {((i += 1) % 2) == 0 }.map { |s| s.split(/,\s*/) }.flatten
else
[e.class.name]
end
end | ruby | def parse_exception_message(e)
if e.kind_of?(RightSupport::Net::NoResult)
# Expected format of exception message: "... endpoints: ('<ip address>' => <exception class name array>, ...)""
i = 0
e.message.split(/\[|\]/).select {((i += 1) % 2) == 0 }.map { |s| s.split(/,\s*/) }.flatten
else
[e.class.name]
end
end | [
"def",
"parse_exception_message",
"(",
"e",
")",
"if",
"e",
".",
"kind_of?",
"(",
"RightSupport",
"::",
"Net",
"::",
"NoResult",
")",
"i",
"=",
"0",
"e",
".",
"message",
".",
"split",
"(",
"/",
"\\[",
"\\]",
"/",
")",
".",
"select",
"{",
"(",
"(",
"i",
"+=",
"1",
")",
"%",
"2",
")",
"==",
"0",
"}",
".",
"map",
"{",
"|",
"s",
"|",
"s",
".",
"split",
"(",
"/",
"\\s",
"/",
")",
"}",
".",
"flatten",
"else",
"[",
"e",
".",
"class",
".",
"name",
"]",
"end",
"end"
] | Parse Exception message and return it
The purpose of this method is to parse the message portion of RequestBalancer
Exceptions to determine the actual Exceptions that resulted in all endpoints
failing to return a non-Exception.
=== Parameters
@param [Exception] Exception to parse
=== Return
@return [Array] List of exception class names | [
"Parse",
"Exception",
"message",
"and",
"return",
"it"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/repose_downloader.rb#L218-L226 | train |
rightscale/right_link | lib/instance/cook/repose_downloader.rb | RightScale.ReposeDownloader.hostnames_ips | def hostnames_ips
@hostnames.map do |hostname|
ips.select { |ip, host| host == hostname }.keys
end.flatten
end | ruby | def hostnames_ips
@hostnames.map do |hostname|
ips.select { |ip, host| host == hostname }.keys
end.flatten
end | [
"def",
"hostnames_ips",
"@hostnames",
".",
"map",
"do",
"|",
"hostname",
"|",
"ips",
".",
"select",
"{",
"|",
"ip",
",",
"host",
"|",
"host",
"==",
"hostname",
"}",
".",
"keys",
"end",
".",
"flatten",
"end"
] | Orders ips by hostnames
The purpose of this method is to sort ips of hostnames so it tries all IPs of hostname 1,
then all IPs of hostname 2, etc
== Return
@return [Array] array of ips ordered by hostnames | [
"Orders",
"ips",
"by",
"hostnames"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/repose_downloader.rb#L236-L240 | train |
rightscale/right_link | lib/instance/cook/repose_downloader.rb | RightScale.ReposeDownloader.balancer | def balancer
@balancer ||= RightSupport::Net::RequestBalancer.new(
hostnames_ips,
:policy => RightSupport::Net::LB::Sticky,
:retry => RETRY_MAX_ATTEMPTS,
:fatal => lambda do |e|
if RightSupport::Net::RequestBalancer::DEFAULT_FATAL_EXCEPTIONS.any? { |c| e.is_a?(c) }
true
elsif e.respond_to?(:http_code) && (e.http_code != nil)
(e.http_code >= 400 && e.http_code < 500) && (e.http_code != 408 && e.http_code != 500 )
else
false
end
end
)
end | ruby | def balancer
@balancer ||= RightSupport::Net::RequestBalancer.new(
hostnames_ips,
:policy => RightSupport::Net::LB::Sticky,
:retry => RETRY_MAX_ATTEMPTS,
:fatal => lambda do |e|
if RightSupport::Net::RequestBalancer::DEFAULT_FATAL_EXCEPTIONS.any? { |c| e.is_a?(c) }
true
elsif e.respond_to?(:http_code) && (e.http_code != nil)
(e.http_code >= 400 && e.http_code < 500) && (e.http_code != 408 && e.http_code != 500 )
else
false
end
end
)
end | [
"def",
"balancer",
"@balancer",
"||=",
"RightSupport",
"::",
"Net",
"::",
"RequestBalancer",
".",
"new",
"(",
"hostnames_ips",
",",
":policy",
"=>",
"RightSupport",
"::",
"Net",
"::",
"LB",
"::",
"Sticky",
",",
":retry",
"=>",
"RETRY_MAX_ATTEMPTS",
",",
":fatal",
"=>",
"lambda",
"do",
"|",
"e",
"|",
"if",
"RightSupport",
"::",
"Net",
"::",
"RequestBalancer",
"::",
"DEFAULT_FATAL_EXCEPTIONS",
".",
"any?",
"{",
"|",
"c",
"|",
"e",
".",
"is_a?",
"(",
"c",
")",
"}",
"true",
"elsif",
"e",
".",
"respond_to?",
"(",
":http_code",
")",
"&&",
"(",
"e",
".",
"http_code",
"!=",
"nil",
")",
"(",
"e",
".",
"http_code",
">=",
"400",
"&&",
"e",
".",
"http_code",
"<",
"500",
")",
"&&",
"(",
"e",
".",
"http_code",
"!=",
"408",
"&&",
"e",
".",
"http_code",
"!=",
"500",
")",
"else",
"false",
"end",
"end",
")",
"end"
] | Create and return a RequestBalancer instance
The purpose of this method is to create a RequestBalancer that will be used
to service all 'download' requests. Once a valid endpoint is found, the
balancer will 'stick' with it. It will consider a response of '408: RequestTimeout' and
'500: InternalServerError' as retryable exceptions and all other HTTP error codes to
indicate a fatal exception that should abort the load-balanced request
=== Return
@return [RightSupport::Net::RequestBalancer] | [
"Create",
"and",
"return",
"a",
"RequestBalancer",
"instance"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/repose_downloader.rb#L253-L268 | train |
piotrmurach/verse | lib/verse/padding.rb | Verse.Padding.pad | def pad(padding = (not_set = true), options = {})
return text if @padding.empty? && not_set
if !not_set
@padding = Padder.parse(padding)
end
text_copy = text.dup
column_width = maximum_length(text)
elements = []
if @padding.top > 0
elements << (SPACE * column_width + NEWLINE) * @padding.top
end
elements << text_copy
if @padding.bottom > 0
elements << (SPACE * column_width + NEWLINE) * @padding.bottom
end
elements.map { |el| pad_multi_line(el) }.join(NEWLINE)
end | ruby | def pad(padding = (not_set = true), options = {})
return text if @padding.empty? && not_set
if !not_set
@padding = Padder.parse(padding)
end
text_copy = text.dup
column_width = maximum_length(text)
elements = []
if @padding.top > 0
elements << (SPACE * column_width + NEWLINE) * @padding.top
end
elements << text_copy
if @padding.bottom > 0
elements << (SPACE * column_width + NEWLINE) * @padding.bottom
end
elements.map { |el| pad_multi_line(el) }.join(NEWLINE)
end | [
"def",
"pad",
"(",
"padding",
"=",
"(",
"not_set",
"=",
"true",
")",
",",
"options",
"=",
"{",
"}",
")",
"return",
"text",
"if",
"@padding",
".",
"empty?",
"&&",
"not_set",
"if",
"!",
"not_set",
"@padding",
"=",
"Padder",
".",
"parse",
"(",
"padding",
")",
"end",
"text_copy",
"=",
"text",
".",
"dup",
"column_width",
"=",
"maximum_length",
"(",
"text",
")",
"elements",
"=",
"[",
"]",
"if",
"@padding",
".",
"top",
">",
"0",
"elements",
"<<",
"(",
"SPACE",
"*",
"column_width",
"+",
"NEWLINE",
")",
"*",
"@padding",
".",
"top",
"end",
"elements",
"<<",
"text_copy",
"if",
"@padding",
".",
"bottom",
">",
"0",
"elements",
"<<",
"(",
"SPACE",
"*",
"column_width",
"+",
"NEWLINE",
")",
"*",
"@padding",
".",
"bottom",
"end",
"elements",
".",
"map",
"{",
"|",
"el",
"|",
"pad_multi_line",
"(",
"el",
")",
"}",
".",
"join",
"(",
"NEWLINE",
")",
"end"
] | Apply padding to text
@param [String] text
@return [String]
@api private | [
"Apply",
"padding",
"to",
"text"
] | 4e3b9e4b3741600ee58e24478d463bfc553786f2 | https://github.com/piotrmurach/verse/blob/4e3b9e4b3741600ee58e24478d463bfc553786f2/lib/verse/padding.rb#L30-L46 | train |
rightscale/right_link | lib/instance/single_thread_bundle_queue.rb | RightScale.SingleThreadBundleQueue.create_sequence | def create_sequence(context)
pid_callback = lambda do |sequence|
@mutex.synchronize { @pid = sequence.pid }
end
return RightScale::ExecutableSequenceProxy.new(context, :pid_callback => pid_callback )
end | ruby | def create_sequence(context)
pid_callback = lambda do |sequence|
@mutex.synchronize { @pid = sequence.pid }
end
return RightScale::ExecutableSequenceProxy.new(context, :pid_callback => pid_callback )
end | [
"def",
"create_sequence",
"(",
"context",
")",
"pid_callback",
"=",
"lambda",
"do",
"|",
"sequence",
"|",
"@mutex",
".",
"synchronize",
"{",
"@pid",
"=",
"sequence",
".",
"pid",
"}",
"end",
"return",
"RightScale",
"::",
"ExecutableSequenceProxy",
".",
"new",
"(",
"context",
",",
":pid_callback",
"=>",
"pid_callback",
")",
"end"
] | Factory method for a new sequence.
context(RightScale::OperationContext) | [
"Factory",
"method",
"for",
"a",
"new",
"sequence",
"."
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/single_thread_bundle_queue.rb#L157-L162 | train |
rightscale/right_link | lib/instance/single_thread_bundle_queue.rb | RightScale.SingleThreadBundleQueue.audit_status | def audit_status(sequence)
context = sequence.context
title = context.decommission? ? 'decommission ' : ''
title += context.succeeded ? 'completed' : 'failed'
context.audit.update_status("#{title}: #{context.payload}")
true
rescue Exception => e
Log.error(Log.format("SingleThreadBundleQueue.audit_status failed for #{@thread_name} thread", e, :trace))
ensure
# release queue thread to wait on next bundle in queue. we must ensure
# that we are not currently on the queue thread so next-tick the signal.
EM.next_tick { @mutex.synchronize { @sequence_finished.signal } }
end | ruby | def audit_status(sequence)
context = sequence.context
title = context.decommission? ? 'decommission ' : ''
title += context.succeeded ? 'completed' : 'failed'
context.audit.update_status("#{title}: #{context.payload}")
true
rescue Exception => e
Log.error(Log.format("SingleThreadBundleQueue.audit_status failed for #{@thread_name} thread", e, :trace))
ensure
# release queue thread to wait on next bundle in queue. we must ensure
# that we are not currently on the queue thread so next-tick the signal.
EM.next_tick { @mutex.synchronize { @sequence_finished.signal } }
end | [
"def",
"audit_status",
"(",
"sequence",
")",
"context",
"=",
"sequence",
".",
"context",
"title",
"=",
"context",
".",
"decommission?",
"?",
"'decommission '",
":",
"''",
"title",
"+=",
"context",
".",
"succeeded",
"?",
"'completed'",
":",
"'failed'",
"context",
".",
"audit",
".",
"update_status",
"(",
"\"#{title}: #{context.payload}\"",
")",
"true",
"rescue",
"Exception",
"=>",
"e",
"Log",
".",
"error",
"(",
"Log",
".",
"format",
"(",
"\"SingleThreadBundleQueue.audit_status failed for #{@thread_name} thread\"",
",",
"e",
",",
":trace",
")",
")",
"ensure",
"EM",
".",
"next_tick",
"{",
"@mutex",
".",
"synchronize",
"{",
"@sequence_finished",
".",
"signal",
"}",
"}",
"end"
] | Audit executable sequence status after it ran
=== Parameters
sequence(RightScale::ExecutableSequence):: finished sequence being audited
=== Return
true:: Always return true | [
"Audit",
"executable",
"sequence",
"status",
"after",
"it",
"ran"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/single_thread_bundle_queue.rb#L171-L183 | train |
rightscale/right_link | spec/clouds/fetch_runner.rb | RightScale.FetchRunner.setup_log | def setup_log(type=:memory)
case type
when :memory
@log_content = StringIO.new
@logger = Logger.new(@log_content)
else
unless defined?(@@log_file_base_name)
@@log_file_base_name = File.normalize_path(File.join(Dir.tmpdir, "#{File.basename(__FILE__, '.rb')}_#{Time.now.strftime("%Y-%m-%d-%H%M%S")}"))
@@log_file_index = 0
end
@@log_file_index += 1
@log_file_name = "#{@@log_file_base_name}_#{@@log_file_index}.log"
@log_file = File.open(@log_file_name, 'w')
@logger = Logger.new(@log_file)
end
@logger.level = is_debug? ? Logger::DEBUG : Logger::INFO
return @logger
end | ruby | def setup_log(type=:memory)
case type
when :memory
@log_content = StringIO.new
@logger = Logger.new(@log_content)
else
unless defined?(@@log_file_base_name)
@@log_file_base_name = File.normalize_path(File.join(Dir.tmpdir, "#{File.basename(__FILE__, '.rb')}_#{Time.now.strftime("%Y-%m-%d-%H%M%S")}"))
@@log_file_index = 0
end
@@log_file_index += 1
@log_file_name = "#{@@log_file_base_name}_#{@@log_file_index}.log"
@log_file = File.open(@log_file_name, 'w')
@logger = Logger.new(@log_file)
end
@logger.level = is_debug? ? Logger::DEBUG : Logger::INFO
return @logger
end | [
"def",
"setup_log",
"(",
"type",
"=",
":memory",
")",
"case",
"type",
"when",
":memory",
"@log_content",
"=",
"StringIO",
".",
"new",
"@logger",
"=",
"Logger",
".",
"new",
"(",
"@log_content",
")",
"else",
"unless",
"defined?",
"(",
"@@log_file_base_name",
")",
"@@log_file_base_name",
"=",
"File",
".",
"normalize_path",
"(",
"File",
".",
"join",
"(",
"Dir",
".",
"tmpdir",
",",
"\"#{File.basename(__FILE__, '.rb')}_#{Time.now.strftime(\"%Y-%m-%d-%H%M%S\")}\"",
")",
")",
"@@log_file_index",
"=",
"0",
"end",
"@@log_file_index",
"+=",
"1",
"@log_file_name",
"=",
"\"#{@@log_file_base_name}_#{@@log_file_index}.log\"",
"@log_file",
"=",
"File",
".",
"open",
"(",
"@log_file_name",
",",
"'w'",
")",
"@logger",
"=",
"Logger",
".",
"new",
"(",
"@log_file",
")",
"end",
"@logger",
".",
"level",
"=",
"is_debug?",
"?",
"Logger",
"::",
"DEBUG",
":",
"Logger",
"::",
"INFO",
"return",
"@logger",
"end"
] | Setup log for test. | [
"Setup",
"log",
"for",
"test",
"."
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/spec/clouds/fetch_runner.rb#L126-L144 | train |
rightscale/right_link | spec/clouds/fetch_runner.rb | RightScale.FetchRunner.run_fetcher | def run_fetcher(*args, &block)
server = nil
done = false
last_exception = nil
results = []
EM.run do
begin
server = MockHTTPServer.new({:Logger => @logger}, &block)
EM.defer do
begin
args.each do |source|
results << source.call()
end
rescue Exception => e
last_exception = e
end
done = true
end
timer = EM.add_periodic_timer(0.1) do
if done
timer.cancel
timer = nil
EM.next_tick do
EM.stop
end
end
end
EM.add_timer(FETCH_TEST_TIMEOUT_SECS) { @logger.error("timeout"); raise "timeout" }
rescue Exception => e
last_exception = e
end
end
# stop server, if any.
(server.shutdown rescue nil) if server
# reraise with full backtrace for debugging purposes. this assumes the
# exception class accepts a single string on construction.
if last_exception
message = "#{last_exception.message}\n#{last_exception.backtrace.join("\n")}"
if last_exception.class == ArgumentError
raise ArgumentError, message
else
begin
raise last_exception.class, message
rescue ArgumentError
# exception class does not support single string construction.
message = "#{last_exception.class}: #{message}"
raise message
end
end
end
return 1 == results.size ? results[0] : results
end | ruby | def run_fetcher(*args, &block)
server = nil
done = false
last_exception = nil
results = []
EM.run do
begin
server = MockHTTPServer.new({:Logger => @logger}, &block)
EM.defer do
begin
args.each do |source|
results << source.call()
end
rescue Exception => e
last_exception = e
end
done = true
end
timer = EM.add_periodic_timer(0.1) do
if done
timer.cancel
timer = nil
EM.next_tick do
EM.stop
end
end
end
EM.add_timer(FETCH_TEST_TIMEOUT_SECS) { @logger.error("timeout"); raise "timeout" }
rescue Exception => e
last_exception = e
end
end
# stop server, if any.
(server.shutdown rescue nil) if server
# reraise with full backtrace for debugging purposes. this assumes the
# exception class accepts a single string on construction.
if last_exception
message = "#{last_exception.message}\n#{last_exception.backtrace.join("\n")}"
if last_exception.class == ArgumentError
raise ArgumentError, message
else
begin
raise last_exception.class, message
rescue ArgumentError
# exception class does not support single string construction.
message = "#{last_exception.class}: #{message}"
raise message
end
end
end
return 1 == results.size ? results[0] : results
end | [
"def",
"run_fetcher",
"(",
"*",
"args",
",",
"&",
"block",
")",
"server",
"=",
"nil",
"done",
"=",
"false",
"last_exception",
"=",
"nil",
"results",
"=",
"[",
"]",
"EM",
".",
"run",
"do",
"begin",
"server",
"=",
"MockHTTPServer",
".",
"new",
"(",
"{",
":Logger",
"=>",
"@logger",
"}",
",",
"&",
"block",
")",
"EM",
".",
"defer",
"do",
"begin",
"args",
".",
"each",
"do",
"|",
"source",
"|",
"results",
"<<",
"source",
".",
"call",
"(",
")",
"end",
"rescue",
"Exception",
"=>",
"e",
"last_exception",
"=",
"e",
"end",
"done",
"=",
"true",
"end",
"timer",
"=",
"EM",
".",
"add_periodic_timer",
"(",
"0.1",
")",
"do",
"if",
"done",
"timer",
".",
"cancel",
"timer",
"=",
"nil",
"EM",
".",
"next_tick",
"do",
"EM",
".",
"stop",
"end",
"end",
"end",
"EM",
".",
"add_timer",
"(",
"FETCH_TEST_TIMEOUT_SECS",
")",
"{",
"@logger",
".",
"error",
"(",
"\"timeout\"",
")",
";",
"raise",
"\"timeout\"",
"}",
"rescue",
"Exception",
"=>",
"e",
"last_exception",
"=",
"e",
"end",
"end",
"(",
"server",
".",
"shutdown",
"rescue",
"nil",
")",
"if",
"server",
"if",
"last_exception",
"message",
"=",
"\"#{last_exception.message}\\n#{last_exception.backtrace.join(\"\\n\")}\"",
"if",
"last_exception",
".",
"class",
"==",
"ArgumentError",
"raise",
"ArgumentError",
",",
"message",
"else",
"begin",
"raise",
"last_exception",
".",
"class",
",",
"message",
"rescue",
"ArgumentError",
"message",
"=",
"\"#{last_exception.class}: #{message}\"",
"raise",
"message",
"end",
"end",
"end",
"return",
"1",
"==",
"results",
".",
"size",
"?",
"results",
"[",
"0",
"]",
":",
"results",
"end"
] | Runs the metadata provider after starting a server to respond to fetch
requests.
=== Parameters
metadata_provider(MetadataProvider):: metadata_provider to test
metadata_formatter(MetadataFormatter):: metadata_formatter to test
block(callback):: handler for server requests
=== Returns
metadata(Hash):: flat metadata hash | [
"Runs",
"the",
"metadata",
"provider",
"after",
"starting",
"a",
"server",
"to",
"respond",
"to",
"fetch",
"requests",
"."
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/spec/clouds/fetch_runner.rb#L173-L227 | train |
greyblake/mago | lib/mago/sexp_processor.rb | Mago.SexpProcessor.process_lit | def process_lit(exp)
exp.shift
value = exp.shift
if value.is_a?(Numeric) && [email protected]?(value)
@file.magic_numbers << MagicNumber.new(:value => value, :line => exp.line)
end
s()
end | ruby | def process_lit(exp)
exp.shift
value = exp.shift
if value.is_a?(Numeric) && [email protected]?(value)
@file.magic_numbers << MagicNumber.new(:value => value, :line => exp.line)
end
s()
end | [
"def",
"process_lit",
"(",
"exp",
")",
"exp",
".",
"shift",
"value",
"=",
"exp",
".",
"shift",
"if",
"value",
".",
"is_a?",
"(",
"Numeric",
")",
"&&",
"!",
"@ignore",
".",
"include?",
"(",
"value",
")",
"@file",
".",
"magic_numbers",
"<<",
"MagicNumber",
".",
"new",
"(",
":value",
"=>",
"value",
",",
":line",
"=>",
"exp",
".",
"line",
")",
"end",
"s",
"(",
")",
"end"
] | Process literal node. If a literal is a number and add it to the
collection of magic numbers.
@param exp [Sexp]
@return [Sexp] | [
"Process",
"literal",
"node",
".",
"If",
"a",
"literal",
"is",
"a",
"number",
"and",
"add",
"it",
"to",
"the",
"collection",
"of",
"magic",
"numbers",
"."
] | ed75d35200cbce2b43e3413eb5aed4736d940577 | https://github.com/greyblake/mago/blob/ed75d35200cbce2b43e3413eb5aed4736d940577/lib/mago/sexp_processor.rb#L32-L41 | train |
OpenBEL/bel.rb | lib/bel/json/adapter/oj.rb | BEL::JSON.Implementation.write | def write(data, output_io, options = {})
options = {
:mode => :compat
}.merge!(options)
if output_io
# write json and return IO
Oj.to_stream(output_io, data, options)
output_io
else
# return json string
string_io = StringIO.new
Oj.to_stream(string_io, data, options)
string_io.string
end
end | ruby | def write(data, output_io, options = {})
options = {
:mode => :compat
}.merge!(options)
if output_io
# write json and return IO
Oj.to_stream(output_io, data, options)
output_io
else
# return json string
string_io = StringIO.new
Oj.to_stream(string_io, data, options)
string_io.string
end
end | [
"def",
"write",
"(",
"data",
",",
"output_io",
",",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
":mode",
"=>",
":compat",
"}",
".",
"merge!",
"(",
"options",
")",
"if",
"output_io",
"Oj",
".",
"to_stream",
"(",
"output_io",
",",
"data",
",",
"options",
")",
"output_io",
"else",
"string_io",
"=",
"StringIO",
".",
"new",
"Oj",
".",
"to_stream",
"(",
"string_io",
",",
"data",
",",
"options",
")",
"string_io",
".",
"string",
"end",
"end"
] | Writes objects to JSON using a streaming mechanism in Oj.
If an IO is provided as +output_io+ then the encoded JSON will be written
directly to it and returned from the method.
If an IO is not provided (i.e. `nil`) then the encoded JSON {String} will
be returned.
@param [Hash, Array, Object] data the objects to encode as JSON
@param [IO] output_io the IO to write the encoded JSON
to
@param [Hash] options supplemental options to Oj; default
is to set the +:mode+ option to +:compat+
@return [IO, String] an {IO} of encoded JSON is returned if it
was provided as an argument, otherwise a JSON-encoded {String} is
returned | [
"Writes",
"objects",
"to",
"JSON",
"using",
"a",
"streaming",
"mechanism",
"in",
"Oj",
"."
] | 8a6d30bda6569d6810ef596dd094247ef18fbdda | https://github.com/OpenBEL/bel.rb/blob/8a6d30bda6569d6810ef596dd094247ef18fbdda/lib/bel/json/adapter/oj.rb#L49-L64 | train |
rightscale/right_link | lib/instance/cook/executable_sequence.rb | RightScale.ExecutableSequence.sensitive_inputs | def sensitive_inputs
inputs = {}
if @attributes
@attributes.values.select { |attr| attr.respond_to?(:has_key?) && attr.has_key?("parameters") }.each do |has_params|
has_params.each_pair do |_, params|
sensitive = params.select { |name, _| @sensitive_inputs.include?(name) }
inputs.merge!(sensitive) { |key, old, new| [old].flatten.push(new) }
end
end
end
inputs
end | ruby | def sensitive_inputs
inputs = {}
if @attributes
@attributes.values.select { |attr| attr.respond_to?(:has_key?) && attr.has_key?("parameters") }.each do |has_params|
has_params.each_pair do |_, params|
sensitive = params.select { |name, _| @sensitive_inputs.include?(name) }
inputs.merge!(sensitive) { |key, old, new| [old].flatten.push(new) }
end
end
end
inputs
end | [
"def",
"sensitive_inputs",
"inputs",
"=",
"{",
"}",
"if",
"@attributes",
"@attributes",
".",
"values",
".",
"select",
"{",
"|",
"attr",
"|",
"attr",
".",
"respond_to?",
"(",
":has_key?",
")",
"&&",
"attr",
".",
"has_key?",
"(",
"\"parameters\"",
")",
"}",
".",
"each",
"do",
"|",
"has_params",
"|",
"has_params",
".",
"each_pair",
"do",
"|",
"_",
",",
"params",
"|",
"sensitive",
"=",
"params",
".",
"select",
"{",
"|",
"name",
",",
"_",
"|",
"@sensitive_inputs",
".",
"include?",
"(",
"name",
")",
"}",
"inputs",
".",
"merge!",
"(",
"sensitive",
")",
"{",
"|",
"key",
",",
"old",
",",
"new",
"|",
"[",
"old",
"]",
".",
"flatten",
".",
"push",
"(",
"new",
")",
"}",
"end",
"end",
"end",
"inputs",
"end"
] | Determine inputs that need special security treatment.
@return [Hash] map of sensitive input names to various values; good for filtering. | [
"Determine",
"inputs",
"that",
"need",
"special",
"security",
"treatment",
"."
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/executable_sequence.rb#L191-L204 | train |
rightscale/right_link | lib/instance/cook/executable_sequence.rb | RightScale.ExecutableSequence.configure_logging | def configure_logging
Chef::Log.logger = AuditLogger.new(sensitive_inputs)
Chef::Log.logger.level = Log.level_from_sym(Log.level)
end | ruby | def configure_logging
Chef::Log.logger = AuditLogger.new(sensitive_inputs)
Chef::Log.logger.level = Log.level_from_sym(Log.level)
end | [
"def",
"configure_logging",
"Chef",
"::",
"Log",
".",
"logger",
"=",
"AuditLogger",
".",
"new",
"(",
"sensitive_inputs",
")",
"Chef",
"::",
"Log",
".",
"logger",
".",
"level",
"=",
"Log",
".",
"level_from_sym",
"(",
"Log",
".",
"level",
")",
"end"
] | Initialize and configure the logger | [
"Initialize",
"and",
"configure",
"the",
"logger"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/executable_sequence.rb#L217-L220 | train |
rightscale/right_link | lib/instance/cook/executable_sequence.rb | RightScale.ExecutableSequence.configure_chef | def configure_chef
# setup logger for mixlib-shellout gem to consume instead of the chef
# v0.10.10 behavior of not logging ShellOut calls by default. also setup
# command failure exception and callback for legacy reasons.
::Mixlib::ShellOut.default_logger = ::Chef::Log
::Mixlib::ShellOut.command_failure_callback = lambda do |params|
failure_reason = ::RightScale::SubprocessFormatting.reason(params[:status])
expected_error_codes = Array(params[:args][:returns]).join(' or ')
::RightScale::Exceptions::Exec.new("\"#{params[:args][:command]}\" #{failure_reason}, expected #{expected_error_codes}.",
params[:args][:cwd])
end
# Chef run mode is always solo for cook
Chef::Config[:solo] = true
# determine default cookbooks path. If debugging cookbooks, place the debug pat(s) first, otherwise
# clear out the list as it will be filled out with cookbooks needed for this converge as they are downloaded.
if CookState.use_cookbooks_path?
Chef::Config[:cookbook_path] = [CookState.cookbooks_path].flatten
@audit.append_info("Using development cookbooks repositories path:\n\t- #{Chef::Config[:cookbook_path].join("\n\t- ")}")
else
# reset the cookbook path. Will be filled out with cookbooks needed for this execution
Chef::Config[:cookbook_path] = []
end
# add the rightscript cookbook if there are rightscripts in this converge
Chef::Config[:cookbook_path] << @right_scripts_cookbook.repo_dir unless @right_scripts_cookbook.empty?
# must set file cache path and ensure it exists otherwise evented run_command will fail
file_cache_path = File.join(AgentConfig.cache_dir, 'chef')
Chef::Config[:file_cache_path] = file_cache_path
FileUtils.mkdir_p(Chef::Config[:file_cache_path])
Chef::Config[:cache_options][:path] = File.join(file_cache_path, 'checksums')
FileUtils.mkdir_p(Chef::Config[:cache_options][:path])
# Where backups of chef-managed files should go. Set to nil to backup to the same directory the file being backed up is in.
Chef::Config[:file_backup_path] = nil
# Chef 11+ defaults client_fork to true which cause Chef::Client to fork
# This create problems with right_popen - right_popen expects to be used inside running EM reactor
# EM seems not to play well with forking
Chef::Config[:client_fork] = false
# Chef 11+ allow concurrent execution of the recipes in different theads,
# by setting different lockfile per thread.
Chef::Config[:lockfile] = File.join(Chef::Config[:file_cache_path], "chef-client-#{@thread_name}-running.pid")
true
end | ruby | def configure_chef
# setup logger for mixlib-shellout gem to consume instead of the chef
# v0.10.10 behavior of not logging ShellOut calls by default. also setup
# command failure exception and callback for legacy reasons.
::Mixlib::ShellOut.default_logger = ::Chef::Log
::Mixlib::ShellOut.command_failure_callback = lambda do |params|
failure_reason = ::RightScale::SubprocessFormatting.reason(params[:status])
expected_error_codes = Array(params[:args][:returns]).join(' or ')
::RightScale::Exceptions::Exec.new("\"#{params[:args][:command]}\" #{failure_reason}, expected #{expected_error_codes}.",
params[:args][:cwd])
end
# Chef run mode is always solo for cook
Chef::Config[:solo] = true
# determine default cookbooks path. If debugging cookbooks, place the debug pat(s) first, otherwise
# clear out the list as it will be filled out with cookbooks needed for this converge as they are downloaded.
if CookState.use_cookbooks_path?
Chef::Config[:cookbook_path] = [CookState.cookbooks_path].flatten
@audit.append_info("Using development cookbooks repositories path:\n\t- #{Chef::Config[:cookbook_path].join("\n\t- ")}")
else
# reset the cookbook path. Will be filled out with cookbooks needed for this execution
Chef::Config[:cookbook_path] = []
end
# add the rightscript cookbook if there are rightscripts in this converge
Chef::Config[:cookbook_path] << @right_scripts_cookbook.repo_dir unless @right_scripts_cookbook.empty?
# must set file cache path and ensure it exists otherwise evented run_command will fail
file_cache_path = File.join(AgentConfig.cache_dir, 'chef')
Chef::Config[:file_cache_path] = file_cache_path
FileUtils.mkdir_p(Chef::Config[:file_cache_path])
Chef::Config[:cache_options][:path] = File.join(file_cache_path, 'checksums')
FileUtils.mkdir_p(Chef::Config[:cache_options][:path])
# Where backups of chef-managed files should go. Set to nil to backup to the same directory the file being backed up is in.
Chef::Config[:file_backup_path] = nil
# Chef 11+ defaults client_fork to true which cause Chef::Client to fork
# This create problems with right_popen - right_popen expects to be used inside running EM reactor
# EM seems not to play well with forking
Chef::Config[:client_fork] = false
# Chef 11+ allow concurrent execution of the recipes in different theads,
# by setting different lockfile per thread.
Chef::Config[:lockfile] = File.join(Chef::Config[:file_cache_path], "chef-client-#{@thread_name}-running.pid")
true
end | [
"def",
"configure_chef",
"::",
"Mixlib",
"::",
"ShellOut",
".",
"default_logger",
"=",
"::",
"Chef",
"::",
"Log",
"::",
"Mixlib",
"::",
"ShellOut",
".",
"command_failure_callback",
"=",
"lambda",
"do",
"|",
"params",
"|",
"failure_reason",
"=",
"::",
"RightScale",
"::",
"SubprocessFormatting",
".",
"reason",
"(",
"params",
"[",
":status",
"]",
")",
"expected_error_codes",
"=",
"Array",
"(",
"params",
"[",
":args",
"]",
"[",
":returns",
"]",
")",
".",
"join",
"(",
"' or '",
")",
"::",
"RightScale",
"::",
"Exceptions",
"::",
"Exec",
".",
"new",
"(",
"\"\\\"#{params[:args][:command]}\\\" #{failure_reason}, expected #{expected_error_codes}.\"",
",",
"params",
"[",
":args",
"]",
"[",
":cwd",
"]",
")",
"end",
"Chef",
"::",
"Config",
"[",
":solo",
"]",
"=",
"true",
"if",
"CookState",
".",
"use_cookbooks_path?",
"Chef",
"::",
"Config",
"[",
":cookbook_path",
"]",
"=",
"[",
"CookState",
".",
"cookbooks_path",
"]",
".",
"flatten",
"@audit",
".",
"append_info",
"(",
"\"Using development cookbooks repositories path:\\n\\t- #{Chef::Config[:cookbook_path].join(\"\\n\\t- \")}\"",
")",
"else",
"Chef",
"::",
"Config",
"[",
":cookbook_path",
"]",
"=",
"[",
"]",
"end",
"Chef",
"::",
"Config",
"[",
":cookbook_path",
"]",
"<<",
"@right_scripts_cookbook",
".",
"repo_dir",
"unless",
"@right_scripts_cookbook",
".",
"empty?",
"file_cache_path",
"=",
"File",
".",
"join",
"(",
"AgentConfig",
".",
"cache_dir",
",",
"'chef'",
")",
"Chef",
"::",
"Config",
"[",
":file_cache_path",
"]",
"=",
"file_cache_path",
"FileUtils",
".",
"mkdir_p",
"(",
"Chef",
"::",
"Config",
"[",
":file_cache_path",
"]",
")",
"Chef",
"::",
"Config",
"[",
":cache_options",
"]",
"[",
":path",
"]",
"=",
"File",
".",
"join",
"(",
"file_cache_path",
",",
"'checksums'",
")",
"FileUtils",
".",
"mkdir_p",
"(",
"Chef",
"::",
"Config",
"[",
":cache_options",
"]",
"[",
":path",
"]",
")",
"Chef",
"::",
"Config",
"[",
":file_backup_path",
"]",
"=",
"nil",
"Chef",
"::",
"Config",
"[",
":client_fork",
"]",
"=",
"false",
"Chef",
"::",
"Config",
"[",
":lockfile",
"]",
"=",
"File",
".",
"join",
"(",
"Chef",
"::",
"Config",
"[",
":file_cache_path",
"]",
",",
"\"chef-client-#{@thread_name}-running.pid\"",
")",
"true",
"end"
] | Configure chef so it can find cookbooks and so its logs go to the audits
=== Return
true:: Always return true | [
"Configure",
"chef",
"so",
"it",
"can",
"find",
"cookbooks",
"and",
"so",
"its",
"logs",
"go",
"to",
"the",
"audits"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/executable_sequence.rb#L226-L274 | train |
rightscale/right_link | lib/instance/cook/executable_sequence.rb | RightScale.ExecutableSequence.update_cookbook_path | def update_cookbook_path
# both cookbook sequences and paths are listed in same order as
# presented in repo UI. previous to RL v5.7 we received cookbook sequences
# in an arbitrary order, but this has been fixed as of the release of v5.8
# (we will not change the order for v5.7-).
# for chef to execute repos and paths in the order listed, both of these
# ordered lists need to be inserted in reverse order because the chef code
# replaces cookbook paths as it reads the array from beginning to end.
@cookbooks.reverse.each do |cookbook_sequence|
local_basedir = File.join(@download_path, cookbook_sequence.hash)
cookbook_sequence.paths.reverse.each do |path|
dir = File.expand_path(File.join(local_basedir, path))
unless Chef::Config[:cookbook_path].include?(dir)
if File.directory?(dir)
Chef::Config[:cookbook_path] << dir
else
RightScale::Log.info("Excluding #{path} from chef cookbooks_path because it was not downloaded")
end
end
end
end
RightScale::Log.info("Updated cookbook_path to: #{Chef::Config[:cookbook_path].join(", ")}")
true
end | ruby | def update_cookbook_path
# both cookbook sequences and paths are listed in same order as
# presented in repo UI. previous to RL v5.7 we received cookbook sequences
# in an arbitrary order, but this has been fixed as of the release of v5.8
# (we will not change the order for v5.7-).
# for chef to execute repos and paths in the order listed, both of these
# ordered lists need to be inserted in reverse order because the chef code
# replaces cookbook paths as it reads the array from beginning to end.
@cookbooks.reverse.each do |cookbook_sequence|
local_basedir = File.join(@download_path, cookbook_sequence.hash)
cookbook_sequence.paths.reverse.each do |path|
dir = File.expand_path(File.join(local_basedir, path))
unless Chef::Config[:cookbook_path].include?(dir)
if File.directory?(dir)
Chef::Config[:cookbook_path] << dir
else
RightScale::Log.info("Excluding #{path} from chef cookbooks_path because it was not downloaded")
end
end
end
end
RightScale::Log.info("Updated cookbook_path to: #{Chef::Config[:cookbook_path].join(", ")}")
true
end | [
"def",
"update_cookbook_path",
"@cookbooks",
".",
"reverse",
".",
"each",
"do",
"|",
"cookbook_sequence",
"|",
"local_basedir",
"=",
"File",
".",
"join",
"(",
"@download_path",
",",
"cookbook_sequence",
".",
"hash",
")",
"cookbook_sequence",
".",
"paths",
".",
"reverse",
".",
"each",
"do",
"|",
"path",
"|",
"dir",
"=",
"File",
".",
"expand_path",
"(",
"File",
".",
"join",
"(",
"local_basedir",
",",
"path",
")",
")",
"unless",
"Chef",
"::",
"Config",
"[",
":cookbook_path",
"]",
".",
"include?",
"(",
"dir",
")",
"if",
"File",
".",
"directory?",
"(",
"dir",
")",
"Chef",
"::",
"Config",
"[",
":cookbook_path",
"]",
"<<",
"dir",
"else",
"RightScale",
"::",
"Log",
".",
"info",
"(",
"\"Excluding #{path} from chef cookbooks_path because it was not downloaded\"",
")",
"end",
"end",
"end",
"end",
"RightScale",
"::",
"Log",
".",
"info",
"(",
"\"Updated cookbook_path to: #{Chef::Config[:cookbook_path].join(\", \")}\"",
")",
"true",
"end"
] | Update the Chef cookbook_path based on the cookbooks in the bundle.
=== Return
true:: Always return true | [
"Update",
"the",
"Chef",
"cookbook_path",
"based",
"on",
"the",
"cookbooks",
"in",
"the",
"bundle",
"."
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/executable_sequence.rb#L351-L374 | train |
rightscale/right_link | lib/instance/cook/executable_sequence.rb | RightScale.ExecutableSequence.checkout_cookbook_repos | def checkout_cookbook_repos
return true unless @cookbook_repo_retriever.has_cookbooks?
@audit.create_new_section('Checking out cookbooks for development')
@audit.append_info("Cookbook repositories will be checked out to #{@cookbook_repo_retriever.checkout_root}")
audit_time do
# only create a scraper if there are dev cookbooks
@cookbook_repo_retriever.checkout_cookbook_repos do |state, operation, explanation, exception|
# audit progress
case state
when :begin
@audit.append_info("start #{operation} #{explanation}") if AUDIT_BEGIN_OPERATIONS.include?(operation)
when :commit
@audit.append_info("finish #{operation} #{explanation}") if AUDIT_COMMIT_OPERATIONS.include?(operation)
when :abort
@audit.append_error("Failed #{operation} #{explanation}")
Log.error(Log.format("Failed #{operation} #{explanation}", exception, :trace))
end
end
end
end | ruby | def checkout_cookbook_repos
return true unless @cookbook_repo_retriever.has_cookbooks?
@audit.create_new_section('Checking out cookbooks for development')
@audit.append_info("Cookbook repositories will be checked out to #{@cookbook_repo_retriever.checkout_root}")
audit_time do
# only create a scraper if there are dev cookbooks
@cookbook_repo_retriever.checkout_cookbook_repos do |state, operation, explanation, exception|
# audit progress
case state
when :begin
@audit.append_info("start #{operation} #{explanation}") if AUDIT_BEGIN_OPERATIONS.include?(operation)
when :commit
@audit.append_info("finish #{operation} #{explanation}") if AUDIT_COMMIT_OPERATIONS.include?(operation)
when :abort
@audit.append_error("Failed #{operation} #{explanation}")
Log.error(Log.format("Failed #{operation} #{explanation}", exception, :trace))
end
end
end
end | [
"def",
"checkout_cookbook_repos",
"return",
"true",
"unless",
"@cookbook_repo_retriever",
".",
"has_cookbooks?",
"@audit",
".",
"create_new_section",
"(",
"'Checking out cookbooks for development'",
")",
"@audit",
".",
"append_info",
"(",
"\"Cookbook repositories will be checked out to #{@cookbook_repo_retriever.checkout_root}\"",
")",
"audit_time",
"do",
"@cookbook_repo_retriever",
".",
"checkout_cookbook_repos",
"do",
"|",
"state",
",",
"operation",
",",
"explanation",
",",
"exception",
"|",
"case",
"state",
"when",
":begin",
"@audit",
".",
"append_info",
"(",
"\"start #{operation} #{explanation}\"",
")",
"if",
"AUDIT_BEGIN_OPERATIONS",
".",
"include?",
"(",
"operation",
")",
"when",
":commit",
"@audit",
".",
"append_info",
"(",
"\"finish #{operation} #{explanation}\"",
")",
"if",
"AUDIT_COMMIT_OPERATIONS",
".",
"include?",
"(",
"operation",
")",
"when",
":abort",
"@audit",
".",
"append_error",
"(",
"\"Failed #{operation} #{explanation}\"",
")",
"Log",
".",
"error",
"(",
"Log",
".",
"format",
"(",
"\"Failed #{operation} #{explanation}\"",
",",
"exception",
",",
":trace",
")",
")",
"end",
"end",
"end",
"end"
] | Checkout repositories for selected cookbooks. Audit progress and errors, do not fail on checkout error.
=== Return
true:: Always return true | [
"Checkout",
"repositories",
"for",
"selected",
"cookbooks",
".",
"Audit",
"progress",
"and",
"errors",
"do",
"not",
"fail",
"on",
"checkout",
"error",
"."
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/executable_sequence.rb#L387-L408 | train |
rightscale/right_link | lib/instance/cook/executable_sequence.rb | RightScale.ExecutableSequence.check_ohai | def check_ohai(&block)
ohai = create_ohai
if ohai[:hostname]
block.call(ohai)
else
Log.warning("Could not determine node name from Ohai, will retry in #{@ohai_retry_delay}s...")
# Need to execute on defer thread consistent with where ExecutableSequence is running
# otherwise EM main thread command client activity will block
EM.add_timer(@ohai_retry_delay) { EM.defer { check_ohai(&block) } }
@ohai_retry_delay = [2 * @ohai_retry_delay, OHAI_RETRY_MAX_DELAY].min
end
true
end | ruby | def check_ohai(&block)
ohai = create_ohai
if ohai[:hostname]
block.call(ohai)
else
Log.warning("Could not determine node name from Ohai, will retry in #{@ohai_retry_delay}s...")
# Need to execute on defer thread consistent with where ExecutableSequence is running
# otherwise EM main thread command client activity will block
EM.add_timer(@ohai_retry_delay) { EM.defer { check_ohai(&block) } }
@ohai_retry_delay = [2 * @ohai_retry_delay, OHAI_RETRY_MAX_DELAY].min
end
true
end | [
"def",
"check_ohai",
"(",
"&",
"block",
")",
"ohai",
"=",
"create_ohai",
"if",
"ohai",
"[",
":hostname",
"]",
"block",
".",
"call",
"(",
"ohai",
")",
"else",
"Log",
".",
"warning",
"(",
"\"Could not determine node name from Ohai, will retry in #{@ohai_retry_delay}s...\"",
")",
"EM",
".",
"add_timer",
"(",
"@ohai_retry_delay",
")",
"{",
"EM",
".",
"defer",
"{",
"check_ohai",
"(",
"&",
"block",
")",
"}",
"}",
"@ohai_retry_delay",
"=",
"[",
"2",
"*",
"@ohai_retry_delay",
",",
"OHAI_RETRY_MAX_DELAY",
"]",
".",
"min",
"end",
"true",
"end"
] | Checks whether Ohai is ready and calls given block with it
if that's the case otherwise schedules itself to try again
indefinitely
=== Block
Given block should take one argument which corresponds to
ohai instance
=== Return
true:: Always return true | [
"Checks",
"whether",
"Ohai",
"is",
"ready",
"and",
"calls",
"given",
"block",
"with",
"it",
"if",
"that",
"s",
"the",
"case",
"otherwise",
"schedules",
"itself",
"to",
"try",
"again",
"indefinitely"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/executable_sequence.rb#L543-L555 | train |
rightscale/right_link | lib/instance/cook/executable_sequence.rb | RightScale.ExecutableSequence.create_ohai | def create_ohai
ohai = Ohai::System.new
ohai.require_plugin('os')
ohai.require_plugin('hostname')
return ohai
end | ruby | def create_ohai
ohai = Ohai::System.new
ohai.require_plugin('os')
ohai.require_plugin('hostname')
return ohai
end | [
"def",
"create_ohai",
"ohai",
"=",
"Ohai",
"::",
"System",
".",
"new",
"ohai",
".",
"require_plugin",
"(",
"'os'",
")",
"ohai",
".",
"require_plugin",
"(",
"'hostname'",
")",
"return",
"ohai",
"end"
] | Creates a new ohai and configures it.
=== Return
ohai(Ohai::System):: configured ohai | [
"Creates",
"a",
"new",
"ohai",
"and",
"configures",
"it",
"."
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/executable_sequence.rb#L561-L566 | train |
rightscale/right_link | lib/instance/cook/executable_sequence.rb | RightScale.ExecutableSequence.report_success | def report_success(node)
ChefState.merge_attributes(node.normal_attrs) if node
remove_right_script_params_from_chef_state
patch = ::RightSupport::Data::HashTools.deep_create_patch(@inputs, ChefState.attributes)
# We don't want to send back new attributes (ohai etc.)
patch[:right_only] = { }
@inputs_patch = patch
EM.next_tick { succeed }
true
end | ruby | def report_success(node)
ChefState.merge_attributes(node.normal_attrs) if node
remove_right_script_params_from_chef_state
patch = ::RightSupport::Data::HashTools.deep_create_patch(@inputs, ChefState.attributes)
# We don't want to send back new attributes (ohai etc.)
patch[:right_only] = { }
@inputs_patch = patch
EM.next_tick { succeed }
true
end | [
"def",
"report_success",
"(",
"node",
")",
"ChefState",
".",
"merge_attributes",
"(",
"node",
".",
"normal_attrs",
")",
"if",
"node",
"remove_right_script_params_from_chef_state",
"patch",
"=",
"::",
"RightSupport",
"::",
"Data",
"::",
"HashTools",
".",
"deep_create_patch",
"(",
"@inputs",
",",
"ChefState",
".",
"attributes",
")",
"patch",
"[",
":right_only",
"]",
"=",
"{",
"}",
"@inputs_patch",
"=",
"patch",
"EM",
".",
"next_tick",
"{",
"succeed",
"}",
"true",
"end"
] | Initialize inputs patch and report success
=== Parameters
node(ChefNode):: Chef node used to converge, can be nil (patch is empty in this case)
=== Return
true:: Always return true | [
"Initialize",
"inputs",
"patch",
"and",
"report",
"success"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/executable_sequence.rb#L657-L666 | train |
rightscale/right_link | lib/instance/cook/executable_sequence.rb | RightScale.ExecutableSequence.report_failure | def report_failure(title, msg)
@ok = false
@failure_title = title
@failure_message = msg
# note that the errback handler is expected to audit the message based on
# the preserved title and message and so we don't audit it here.
EM.next_tick { fail }
true
end | ruby | def report_failure(title, msg)
@ok = false
@failure_title = title
@failure_message = msg
# note that the errback handler is expected to audit the message based on
# the preserved title and message and so we don't audit it here.
EM.next_tick { fail }
true
end | [
"def",
"report_failure",
"(",
"title",
",",
"msg",
")",
"@ok",
"=",
"false",
"@failure_title",
"=",
"title",
"@failure_message",
"=",
"msg",
"EM",
".",
"next_tick",
"{",
"fail",
"}",
"true",
"end"
] | Set status with failure message and audit it
=== Parameters
title(String):: Title used to update audit status
msg(String):: Failure message
=== Return
true:: Always return true | [
"Set",
"status",
"with",
"failure",
"message",
"and",
"audit",
"it"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/executable_sequence.rb#L676-L684 | train |
rightscale/right_link | lib/instance/cook/executable_sequence.rb | RightScale.ExecutableSequence.chef_error | def chef_error(e)
if e.is_a?(::RightScale::Exceptions::Exec)
msg = "External command error: "
if match = /RightScale::Exceptions::Exec: (.*)/.match(e.message)
cmd_output = match[1]
else
cmd_output = e.message
end
msg += cmd_output
msg += "\nThe command was run from \"#{e.path}\"" if e.path
elsif e.is_a?(::Chef::Exceptions::ValidationFailed) && (e.message =~ /Option action must be equal to one of:/)
msg = "[chef] recipe references an action that does not exist. #{e.message}"
elsif e.is_a?(::NoMethodError) && (missing_action_match = /undefined method .action_(\S*)' for #<\S*:\S*>/.match(e.message)) && missing_action_match[1]
msg = "[chef] recipe references the action <#{missing_action_match[1]}> which is missing an implementation"
else
msg = "Execution error:\n"
msg += e.message
file, line, meth = e.backtrace[0].scan(BACKTRACE_LINE_REGEXP).flatten
line_number = line.to_i
if file && line && (line_number.to_s == line)
dir = AgentConfig.cookbook_download_dir
if file[0..dir.size - 1] == dir
path = "[COOKBOOKS]/" + file[dir.size..file.size]
else
path = file
end
msg += "\n\nThe error occurred line #{line} of #{path}"
msg += " in method '#{meth}'" if meth
context = ""
if File.readable?(file)
File.open(file, 'r') do |f|
lines = f.readlines
lines_count = lines.size
if lines_count >= line_number
upper = [lines_count, line_number + 2].max
padding = upper.to_s.size
context += context_line(lines, line_number - 2, padding)
context += context_line(lines, line_number - 1, padding)
context += context_line(lines, line_number, padding, '*')
context += context_line(lines, line_number + 1, padding)
context += context_line(lines, line_number + 2, padding)
end
end
end
msg += " while executing:\n\n#{context}" unless context.empty?
end
end
msg
end | ruby | def chef_error(e)
if e.is_a?(::RightScale::Exceptions::Exec)
msg = "External command error: "
if match = /RightScale::Exceptions::Exec: (.*)/.match(e.message)
cmd_output = match[1]
else
cmd_output = e.message
end
msg += cmd_output
msg += "\nThe command was run from \"#{e.path}\"" if e.path
elsif e.is_a?(::Chef::Exceptions::ValidationFailed) && (e.message =~ /Option action must be equal to one of:/)
msg = "[chef] recipe references an action that does not exist. #{e.message}"
elsif e.is_a?(::NoMethodError) && (missing_action_match = /undefined method .action_(\S*)' for #<\S*:\S*>/.match(e.message)) && missing_action_match[1]
msg = "[chef] recipe references the action <#{missing_action_match[1]}> which is missing an implementation"
else
msg = "Execution error:\n"
msg += e.message
file, line, meth = e.backtrace[0].scan(BACKTRACE_LINE_REGEXP).flatten
line_number = line.to_i
if file && line && (line_number.to_s == line)
dir = AgentConfig.cookbook_download_dir
if file[0..dir.size - 1] == dir
path = "[COOKBOOKS]/" + file[dir.size..file.size]
else
path = file
end
msg += "\n\nThe error occurred line #{line} of #{path}"
msg += " in method '#{meth}'" if meth
context = ""
if File.readable?(file)
File.open(file, 'r') do |f|
lines = f.readlines
lines_count = lines.size
if lines_count >= line_number
upper = [lines_count, line_number + 2].max
padding = upper.to_s.size
context += context_line(lines, line_number - 2, padding)
context += context_line(lines, line_number - 1, padding)
context += context_line(lines, line_number, padding, '*')
context += context_line(lines, line_number + 1, padding)
context += context_line(lines, line_number + 2, padding)
end
end
end
msg += " while executing:\n\n#{context}" unless context.empty?
end
end
msg
end | [
"def",
"chef_error",
"(",
"e",
")",
"if",
"e",
".",
"is_a?",
"(",
"::",
"RightScale",
"::",
"Exceptions",
"::",
"Exec",
")",
"msg",
"=",
"\"External command error: \"",
"if",
"match",
"=",
"/",
"/",
".",
"match",
"(",
"e",
".",
"message",
")",
"cmd_output",
"=",
"match",
"[",
"1",
"]",
"else",
"cmd_output",
"=",
"e",
".",
"message",
"end",
"msg",
"+=",
"cmd_output",
"msg",
"+=",
"\"\\nThe command was run from \\\"#{e.path}\\\"\"",
"if",
"e",
".",
"path",
"elsif",
"e",
".",
"is_a?",
"(",
"::",
"Chef",
"::",
"Exceptions",
"::",
"ValidationFailed",
")",
"&&",
"(",
"e",
".",
"message",
"=~",
"/",
"/",
")",
"msg",
"=",
"\"[chef] recipe references an action that does not exist. #{e.message}\"",
"elsif",
"e",
".",
"is_a?",
"(",
"::",
"NoMethodError",
")",
"&&",
"(",
"missing_action_match",
"=",
"/",
"\\S",
"\\S",
"\\S",
"/",
".",
"match",
"(",
"e",
".",
"message",
")",
")",
"&&",
"missing_action_match",
"[",
"1",
"]",
"msg",
"=",
"\"[chef] recipe references the action <#{missing_action_match[1]}> which is missing an implementation\"",
"else",
"msg",
"=",
"\"Execution error:\\n\"",
"msg",
"+=",
"e",
".",
"message",
"file",
",",
"line",
",",
"meth",
"=",
"e",
".",
"backtrace",
"[",
"0",
"]",
".",
"scan",
"(",
"BACKTRACE_LINE_REGEXP",
")",
".",
"flatten",
"line_number",
"=",
"line",
".",
"to_i",
"if",
"file",
"&&",
"line",
"&&",
"(",
"line_number",
".",
"to_s",
"==",
"line",
")",
"dir",
"=",
"AgentConfig",
".",
"cookbook_download_dir",
"if",
"file",
"[",
"0",
"..",
"dir",
".",
"size",
"-",
"1",
"]",
"==",
"dir",
"path",
"=",
"\"[COOKBOOKS]/\"",
"+",
"file",
"[",
"dir",
".",
"size",
"..",
"file",
".",
"size",
"]",
"else",
"path",
"=",
"file",
"end",
"msg",
"+=",
"\"\\n\\nThe error occurred line #{line} of #{path}\"",
"msg",
"+=",
"\" in method '#{meth}'\"",
"if",
"meth",
"context",
"=",
"\"\"",
"if",
"File",
".",
"readable?",
"(",
"file",
")",
"File",
".",
"open",
"(",
"file",
",",
"'r'",
")",
"do",
"|",
"f",
"|",
"lines",
"=",
"f",
".",
"readlines",
"lines_count",
"=",
"lines",
".",
"size",
"if",
"lines_count",
">=",
"line_number",
"upper",
"=",
"[",
"lines_count",
",",
"line_number",
"+",
"2",
"]",
".",
"max",
"padding",
"=",
"upper",
".",
"to_s",
".",
"size",
"context",
"+=",
"context_line",
"(",
"lines",
",",
"line_number",
"-",
"2",
",",
"padding",
")",
"context",
"+=",
"context_line",
"(",
"lines",
",",
"line_number",
"-",
"1",
",",
"padding",
")",
"context",
"+=",
"context_line",
"(",
"lines",
",",
"line_number",
",",
"padding",
",",
"'*'",
")",
"context",
"+=",
"context_line",
"(",
"lines",
",",
"line_number",
"+",
"1",
",",
"padding",
")",
"context",
"+=",
"context_line",
"(",
"lines",
",",
"line_number",
"+",
"2",
",",
"padding",
")",
"end",
"end",
"end",
"msg",
"+=",
"\" while executing:\\n\\n#{context}\"",
"unless",
"context",
".",
"empty?",
"end",
"end",
"msg",
"end"
] | Wrap chef exception with explanatory information and show
context of failure
=== Parameters
e(Exception):: Exception raised while executing Chef recipe
=== Return
msg(String):: Human friendly error message | [
"Wrap",
"chef",
"exception",
"with",
"explanatory",
"information",
"and",
"show",
"context",
"of",
"failure"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/executable_sequence.rb#L694-L742 | train |
rightscale/right_link | lib/instance/cook/executable_sequence.rb | RightScale.ExecutableSequence.context_line | def context_line(lines, index, padding, prefix=nil)
return '' if index < 1 || index > lines.size
margin = prefix ? prefix * index.to_s.size : index.to_s
"#{margin}#{' ' * ([padding - margin.size, 0].max)} #{lines[index - 1]}"
end | ruby | def context_line(lines, index, padding, prefix=nil)
return '' if index < 1 || index > lines.size
margin = prefix ? prefix * index.to_s.size : index.to_s
"#{margin}#{' ' * ([padding - margin.size, 0].max)} #{lines[index - 1]}"
end | [
"def",
"context_line",
"(",
"lines",
",",
"index",
",",
"padding",
",",
"prefix",
"=",
"nil",
")",
"return",
"''",
"if",
"index",
"<",
"1",
"||",
"index",
">",
"lines",
".",
"size",
"margin",
"=",
"prefix",
"?",
"prefix",
"*",
"index",
".",
"to_s",
".",
"size",
":",
"index",
".",
"to_s",
"\"#{margin}#{' ' * ([padding - margin.size, 0].max)} #{lines[index - 1]}\"",
"end"
] | Format a single line for the error context, return empty string
if given index is negative or greater than the lines array size
=== Parameters
lines(Array):: Lines of text
index(Integer):: Index of line that should be formatted for context
padding(Integer):: Number of character to pad line with (includes prefix)
prefix(String):: Single character string used to prefix line
use line number if not specified | [
"Format",
"a",
"single",
"line",
"for",
"the",
"error",
"context",
"return",
"empty",
"string",
"if",
"given",
"index",
"is",
"negative",
"or",
"greater",
"than",
"the",
"lines",
"array",
"size"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/executable_sequence.rb#L753-L757 | train |
rightscale/right_link | lib/instance/cook/executable_sequence.rb | RightScale.ExecutableSequence.retry_execution | def retry_execution(retry_message, times = AgentConfig.max_packages_install_retries)
count = 0
success = false
begin
count += 1
success = yield
@audit.append_info("\n#{retry_message}\n") unless success || count > times
end while !success && count <= times
success
end | ruby | def retry_execution(retry_message, times = AgentConfig.max_packages_install_retries)
count = 0
success = false
begin
count += 1
success = yield
@audit.append_info("\n#{retry_message}\n") unless success || count > times
end while !success && count <= times
success
end | [
"def",
"retry_execution",
"(",
"retry_message",
",",
"times",
"=",
"AgentConfig",
".",
"max_packages_install_retries",
")",
"count",
"=",
"0",
"success",
"=",
"false",
"begin",
"count",
"+=",
"1",
"success",
"=",
"yield",
"@audit",
".",
"append_info",
"(",
"\"\\n#{retry_message}\\n\"",
")",
"unless",
"success",
"||",
"count",
">",
"times",
"end",
"while",
"!",
"success",
"&&",
"count",
"<=",
"times",
"success",
"end"
] | Retry executing given block given number of times
Block should return true when it succeeds
=== Parameters
retry_message(String):: Message to audit before retrying
times(Integer):: Number of times block should be retried before giving up
=== Block
Block to be executed
=== Return
success(Boolean):: true if execution was successful, false otherwise. | [
"Retry",
"executing",
"given",
"block",
"given",
"number",
"of",
"times",
"Block",
"should",
"return",
"true",
"when",
"it",
"succeeds"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/executable_sequence.rb#L771-L780 | train |
arineng/jcrvalidator | lib/jcr/parts.rb | JCR.JcrParts.get_start | def get_start( line )
retval = nil
m = /^\s*;\s*start_part\s*(.+)[^\s]*/.match( line )
if m && m[1]
retval = m[1]
end
return retval
end | ruby | def get_start( line )
retval = nil
m = /^\s*;\s*start_part\s*(.+)[^\s]*/.match( line )
if m && m[1]
retval = m[1]
end
return retval
end | [
"def",
"get_start",
"(",
"line",
")",
"retval",
"=",
"nil",
"m",
"=",
"/",
"\\s",
"\\s",
"\\s",
"\\s",
"/",
".",
"match",
"(",
"line",
")",
"if",
"m",
"&&",
"m",
"[",
"1",
"]",
"retval",
"=",
"m",
"[",
"1",
"]",
"end",
"return",
"retval",
"end"
] | Determines if the the line is a start_part comment.
Return the file name otherwise nil | [
"Determines",
"if",
"the",
"the",
"line",
"is",
"a",
"start_part",
"comment",
".",
"Return",
"the",
"file",
"name",
"otherwise",
"nil"
] | 69325242727e5e5b671db5ec287ad3b31fd91653 | https://github.com/arineng/jcrvalidator/blob/69325242727e5e5b671db5ec287ad3b31fd91653/lib/jcr/parts.rb#L38-L45 | train |
arineng/jcrvalidator | lib/jcr/parts.rb | JCR.JcrParts.get_all | def get_all( line )
retval = nil
m = /^\s*;\s*all_parts\s*(.+)[^\s]*/.match( line )
if m && m[1]
retval = m[1]
end
return retval
end | ruby | def get_all( line )
retval = nil
m = /^\s*;\s*all_parts\s*(.+)[^\s]*/.match( line )
if m && m[1]
retval = m[1]
end
return retval
end | [
"def",
"get_all",
"(",
"line",
")",
"retval",
"=",
"nil",
"m",
"=",
"/",
"\\s",
"\\s",
"\\s",
"\\s",
"/",
".",
"match",
"(",
"line",
")",
"if",
"m",
"&&",
"m",
"[",
"1",
"]",
"retval",
"=",
"m",
"[",
"1",
"]",
"end",
"return",
"retval",
"end"
] | Determines if the the line is an all_parts comment.
Return the file name otherwise nil | [
"Determines",
"if",
"the",
"the",
"line",
"is",
"an",
"all_parts",
"comment",
".",
"Return",
"the",
"file",
"name",
"otherwise",
"nil"
] | 69325242727e5e5b671db5ec287ad3b31fd91653 | https://github.com/arineng/jcrvalidator/blob/69325242727e5e5b671db5ec287ad3b31fd91653/lib/jcr/parts.rb#L49-L56 | train |
arineng/jcrvalidator | lib/jcr/parts.rb | JCR.JcrParts.get_end | def get_end( line )
retval = nil
m = /^\s*;\s*end_part/.match( line )
if m
retval = true
end
return retval
end | ruby | def get_end( line )
retval = nil
m = /^\s*;\s*end_part/.match( line )
if m
retval = true
end
return retval
end | [
"def",
"get_end",
"(",
"line",
")",
"retval",
"=",
"nil",
"m",
"=",
"/",
"\\s",
"\\s",
"/",
".",
"match",
"(",
"line",
")",
"if",
"m",
"retval",
"=",
"true",
"end",
"return",
"retval",
"end"
] | Determines if the the line is an end_parts comment.
Return true otherwise nil | [
"Determines",
"if",
"the",
"the",
"line",
"is",
"an",
"end_parts",
"comment",
".",
"Return",
"true",
"otherwise",
"nil"
] | 69325242727e5e5b671db5ec287ad3b31fd91653 | https://github.com/arineng/jcrvalidator/blob/69325242727e5e5b671db5ec287ad3b31fd91653/lib/jcr/parts.rb#L60-L67 | train |
arineng/jcrvalidator | lib/jcr/parts.rb | JCR.JcrParts.process_ruleset | def process_ruleset( ruleset, dirname = nil )
all_file_names = []
all_parts = []
all_parts_name = nil
current_part = nil
current_part_name = nil
ruleset.lines do |line|
if !all_parts_name && ( all_parts_name = get_all( line ) )
all_parts_name = File.join( dirname, all_parts_name ) if dirname
all_file_names << all_parts_name
elsif ( current_part_name = get_start( line ) )
current_part_name = File.join( dirname, current_part_name ) if dirname
if current_part
current_part.close
end
current_part = File.open( current_part_name, "w" )
all_file_names << current_part_name
elsif get_end( line ) && current_part
current_part.close
current_part = nil
elsif current_part
current_part.puts line
all_parts << line
else
all_parts << line
end
end
if current_part
current_part.close
end
if all_parts_name
f = File.open( all_parts_name, "w" )
all_parts.each do |line|
f.puts( line )
end
f.close
end
if all_file_names.length
xml_fn = File.basename( all_file_names[0],".*" ) + "_xml_entity_refs"
xml_fn = File.join( File.dirname( all_file_names[0] ), xml_fn )
xml = File.open( xml_fn, "w" )
all_file_names.each do |fn|
bn = File.basename( fn, ".*" )
xml.puts( "<!ENTITY #{bn} PUBLIC '' '#{fn}'>")
end
xml.close
end
end | ruby | def process_ruleset( ruleset, dirname = nil )
all_file_names = []
all_parts = []
all_parts_name = nil
current_part = nil
current_part_name = nil
ruleset.lines do |line|
if !all_parts_name && ( all_parts_name = get_all( line ) )
all_parts_name = File.join( dirname, all_parts_name ) if dirname
all_file_names << all_parts_name
elsif ( current_part_name = get_start( line ) )
current_part_name = File.join( dirname, current_part_name ) if dirname
if current_part
current_part.close
end
current_part = File.open( current_part_name, "w" )
all_file_names << current_part_name
elsif get_end( line ) && current_part
current_part.close
current_part = nil
elsif current_part
current_part.puts line
all_parts << line
else
all_parts << line
end
end
if current_part
current_part.close
end
if all_parts_name
f = File.open( all_parts_name, "w" )
all_parts.each do |line|
f.puts( line )
end
f.close
end
if all_file_names.length
xml_fn = File.basename( all_file_names[0],".*" ) + "_xml_entity_refs"
xml_fn = File.join( File.dirname( all_file_names[0] ), xml_fn )
xml = File.open( xml_fn, "w" )
all_file_names.each do |fn|
bn = File.basename( fn, ".*" )
xml.puts( "<!ENTITY #{bn} PUBLIC '' '#{fn}'>")
end
xml.close
end
end | [
"def",
"process_ruleset",
"(",
"ruleset",
",",
"dirname",
"=",
"nil",
")",
"all_file_names",
"=",
"[",
"]",
"all_parts",
"=",
"[",
"]",
"all_parts_name",
"=",
"nil",
"current_part",
"=",
"nil",
"current_part_name",
"=",
"nil",
"ruleset",
".",
"lines",
"do",
"|",
"line",
"|",
"if",
"!",
"all_parts_name",
"&&",
"(",
"all_parts_name",
"=",
"get_all",
"(",
"line",
")",
")",
"all_parts_name",
"=",
"File",
".",
"join",
"(",
"dirname",
",",
"all_parts_name",
")",
"if",
"dirname",
"all_file_names",
"<<",
"all_parts_name",
"elsif",
"(",
"current_part_name",
"=",
"get_start",
"(",
"line",
")",
")",
"current_part_name",
"=",
"File",
".",
"join",
"(",
"dirname",
",",
"current_part_name",
")",
"if",
"dirname",
"if",
"current_part",
"current_part",
".",
"close",
"end",
"current_part",
"=",
"File",
".",
"open",
"(",
"current_part_name",
",",
"\"w\"",
")",
"all_file_names",
"<<",
"current_part_name",
"elsif",
"get_end",
"(",
"line",
")",
"&&",
"current_part",
"current_part",
".",
"close",
"current_part",
"=",
"nil",
"elsif",
"current_part",
"current_part",
".",
"puts",
"line",
"all_parts",
"<<",
"line",
"else",
"all_parts",
"<<",
"line",
"end",
"end",
"if",
"current_part",
"current_part",
".",
"close",
"end",
"if",
"all_parts_name",
"f",
"=",
"File",
".",
"open",
"(",
"all_parts_name",
",",
"\"w\"",
")",
"all_parts",
".",
"each",
"do",
"|",
"line",
"|",
"f",
".",
"puts",
"(",
"line",
")",
"end",
"f",
".",
"close",
"end",
"if",
"all_file_names",
".",
"length",
"xml_fn",
"=",
"File",
".",
"basename",
"(",
"all_file_names",
"[",
"0",
"]",
",",
"\".*\"",
")",
"+",
"\"_xml_entity_refs\"",
"xml_fn",
"=",
"File",
".",
"join",
"(",
"File",
".",
"dirname",
"(",
"all_file_names",
"[",
"0",
"]",
")",
",",
"xml_fn",
")",
"xml",
"=",
"File",
".",
"open",
"(",
"xml_fn",
",",
"\"w\"",
")",
"all_file_names",
".",
"each",
"do",
"|",
"fn",
"|",
"bn",
"=",
"File",
".",
"basename",
"(",
"fn",
",",
"\".*\"",
")",
"xml",
".",
"puts",
"(",
"\"<!ENTITY #{bn} PUBLIC '' '#{fn}'>\"",
")",
"end",
"xml",
".",
"close",
"end",
"end"
] | processes the lines
ruleset is to be a string read in using File.read | [
"processes",
"the",
"lines",
"ruleset",
"is",
"to",
"be",
"a",
"string",
"read",
"in",
"using",
"File",
".",
"read"
] | 69325242727e5e5b671db5ec287ad3b31fd91653 | https://github.com/arineng/jcrvalidator/blob/69325242727e5e5b671db5ec287ad3b31fd91653/lib/jcr/parts.rb#L71-L118 | train |
mattThousand/sad_panda | lib/sad_panda/polarity.rb | SadPanda.Polarity.call | def call
words = stems_for(remove_stopwords_in(@words))
score_polarities_for(frequencies_for(words))
polarities.empty? ? 5.0 : (polarities.inject(0){ |sum, polarity| sum + polarity } / polarities.length)
end | ruby | def call
words = stems_for(remove_stopwords_in(@words))
score_polarities_for(frequencies_for(words))
polarities.empty? ? 5.0 : (polarities.inject(0){ |sum, polarity| sum + polarity } / polarities.length)
end | [
"def",
"call",
"words",
"=",
"stems_for",
"(",
"remove_stopwords_in",
"(",
"@words",
")",
")",
"score_polarities_for",
"(",
"frequencies_for",
"(",
"words",
")",
")",
"polarities",
".",
"empty?",
"?",
"5.0",
":",
"(",
"polarities",
".",
"inject",
"(",
"0",
")",
"{",
"|",
"sum",
",",
"polarity",
"|",
"sum",
"+",
"polarity",
"}",
"/",
"polarities",
".",
"length",
")",
"end"
] | Main method that initiates calculating polarity | [
"Main",
"method",
"that",
"initiates",
"calculating",
"polarity"
] | 2ccb1496529d5c5a453d3822fa44b746295f3962 | https://github.com/mattThousand/sad_panda/blob/2ccb1496529d5c5a453d3822fa44b746295f3962/lib/sad_panda/polarity.rb#L16-L22 | train |
mattThousand/sad_panda | lib/sad_panda/polarity.rb | SadPanda.Polarity.score_emoticon_polarity | def score_emoticon_polarity
happy = happy_emoticon?(words)
sad = sad_emoticon?(words)
polarities << 5.0 if happy && sad
polarities << 8.0 if happy
polarities << 2.0 if sad
end | ruby | def score_emoticon_polarity
happy = happy_emoticon?(words)
sad = sad_emoticon?(words)
polarities << 5.0 if happy && sad
polarities << 8.0 if happy
polarities << 2.0 if sad
end | [
"def",
"score_emoticon_polarity",
"happy",
"=",
"happy_emoticon?",
"(",
"words",
")",
"sad",
"=",
"sad_emoticon?",
"(",
"words",
")",
"polarities",
"<<",
"5.0",
"if",
"happy",
"&&",
"sad",
"polarities",
"<<",
"8.0",
"if",
"happy",
"polarities",
"<<",
"2.0",
"if",
"sad",
"end"
] | Checks if words has happy or sad emoji and adds polarity for it | [
"Checks",
"if",
"words",
"has",
"happy",
"or",
"sad",
"emoji",
"and",
"adds",
"polarity",
"for",
"it"
] | 2ccb1496529d5c5a453d3822fa44b746295f3962 | https://github.com/mattThousand/sad_panda/blob/2ccb1496529d5c5a453d3822fa44b746295f3962/lib/sad_panda/polarity.rb#L27-L34 | train |
mattThousand/sad_panda | lib/sad_panda/polarity.rb | SadPanda.Polarity.score_polarities_for | def score_polarities_for(word_frequencies)
word_frequencies.each do |word, frequency|
polarity = SadPanda::Bank::POLARITIES[word.to_sym]
polarities << (polarity * frequency.to_f) if polarity
end
score_emoticon_polarity
end | ruby | def score_polarities_for(word_frequencies)
word_frequencies.each do |word, frequency|
polarity = SadPanda::Bank::POLARITIES[word.to_sym]
polarities << (polarity * frequency.to_f) if polarity
end
score_emoticon_polarity
end | [
"def",
"score_polarities_for",
"(",
"word_frequencies",
")",
"word_frequencies",
".",
"each",
"do",
"|",
"word",
",",
"frequency",
"|",
"polarity",
"=",
"SadPanda",
"::",
"Bank",
"::",
"POLARITIES",
"[",
"word",
".",
"to_sym",
"]",
"polarities",
"<<",
"(",
"polarity",
"*",
"frequency",
".",
"to_f",
")",
"if",
"polarity",
"end",
"score_emoticon_polarity",
"end"
] | Appends polarities of words to array polarities | [
"Appends",
"polarities",
"of",
"words",
"to",
"array",
"polarities"
] | 2ccb1496529d5c5a453d3822fa44b746295f3962 | https://github.com/mattThousand/sad_panda/blob/2ccb1496529d5c5a453d3822fa44b746295f3962/lib/sad_panda/polarity.rb#L37-L44 | train |
rightscale/right_link | lib/instance/network_configurator/centos_network_configurator.rb | RightScale.CentosNetworkConfigurator.network_route_add | def network_route_add(network, nat_server_ip)
super
route_str = "#{network} via #{nat_server_ip}"
begin
if @boot
logger.info "Adding route to network #{route_str}"
device = route_device(network, nat_server_ip)
if device
update_route_file(network, nat_server_ip, device)
else
logger.warn "Unable to find associated device for #{route_str} in pre-networking section. As network devices aren't setup yet, will try again after network start."
end
else
if network_route_exists?(network, nat_server_ip)
logger.debug "Route already exists to #{route_str}"
else
logger.info "Adding route to network #{route_str}"
runshell("ip route add #{route_str}")
device = route_device(network, nat_server_ip)
if device
update_route_file(network, nat_server_ip, device)
else
logger.error "Unable to set route in system config: unable to find associated device for #{route_str} post-networking."
# No need to raise here -- ip route should have failed above if there is no device to attach to
end
end
end
rescue Exception => e
logger.error "Unable to set a route #{route_str}. Check network settings."
# XXX: for some reason network_route_exists? allowing mutple routes
# to be set. For now, don't fail if route already exists.
throw e unless e.message.include?("NETLINK answers: File exists")
end
true
end | ruby | def network_route_add(network, nat_server_ip)
super
route_str = "#{network} via #{nat_server_ip}"
begin
if @boot
logger.info "Adding route to network #{route_str}"
device = route_device(network, nat_server_ip)
if device
update_route_file(network, nat_server_ip, device)
else
logger.warn "Unable to find associated device for #{route_str} in pre-networking section. As network devices aren't setup yet, will try again after network start."
end
else
if network_route_exists?(network, nat_server_ip)
logger.debug "Route already exists to #{route_str}"
else
logger.info "Adding route to network #{route_str}"
runshell("ip route add #{route_str}")
device = route_device(network, nat_server_ip)
if device
update_route_file(network, nat_server_ip, device)
else
logger.error "Unable to set route in system config: unable to find associated device for #{route_str} post-networking."
# No need to raise here -- ip route should have failed above if there is no device to attach to
end
end
end
rescue Exception => e
logger.error "Unable to set a route #{route_str}. Check network settings."
# XXX: for some reason network_route_exists? allowing mutple routes
# to be set. For now, don't fail if route already exists.
throw e unless e.message.include?("NETLINK answers: File exists")
end
true
end | [
"def",
"network_route_add",
"(",
"network",
",",
"nat_server_ip",
")",
"super",
"route_str",
"=",
"\"#{network} via #{nat_server_ip}\"",
"begin",
"if",
"@boot",
"logger",
".",
"info",
"\"Adding route to network #{route_str}\"",
"device",
"=",
"route_device",
"(",
"network",
",",
"nat_server_ip",
")",
"if",
"device",
"update_route_file",
"(",
"network",
",",
"nat_server_ip",
",",
"device",
")",
"else",
"logger",
".",
"warn",
"\"Unable to find associated device for #{route_str} in pre-networking section. As network devices aren't setup yet, will try again after network start.\"",
"end",
"else",
"if",
"network_route_exists?",
"(",
"network",
",",
"nat_server_ip",
")",
"logger",
".",
"debug",
"\"Route already exists to #{route_str}\"",
"else",
"logger",
".",
"info",
"\"Adding route to network #{route_str}\"",
"runshell",
"(",
"\"ip route add #{route_str}\"",
")",
"device",
"=",
"route_device",
"(",
"network",
",",
"nat_server_ip",
")",
"if",
"device",
"update_route_file",
"(",
"network",
",",
"nat_server_ip",
",",
"device",
")",
"else",
"logger",
".",
"error",
"\"Unable to set route in system config: unable to find associated device for #{route_str} post-networking.\"",
"end",
"end",
"end",
"rescue",
"Exception",
"=>",
"e",
"logger",
".",
"error",
"\"Unable to set a route #{route_str}. Check network settings.\"",
"throw",
"e",
"unless",
"e",
".",
"message",
".",
"include?",
"(",
"\"NETLINK answers: File exists\"",
")",
"end",
"true",
"end"
] | This is now quite tricky. We do two routing passes, a pass before the
system networking is setup (@boot is true) in which we setup static system
config files and a pass after system networking (@boot is false) in which
we fix up the remaining routes cases involving DHCP. We have to set any routes
involving DHCP post networking as we can't know the DHCP gateway beforehand | [
"This",
"is",
"now",
"quite",
"tricky",
".",
"We",
"do",
"two",
"routing",
"passes",
"a",
"pass",
"before",
"the",
"system",
"networking",
"is",
"setup",
"("
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/network_configurator/centos_network_configurator.rb#L67-L102 | train |
rightscale/right_link | lib/instance/network_configurator/centos_network_configurator.rb | RightScale.CentosNetworkConfigurator.update_route_file | def update_route_file(network, nat_server_ip, device)
raise "ERROR: invalid nat_server_ip : '#{nat_server_ip}'" unless valid_ipv4?(nat_server_ip)
raise "ERROR: invalid CIDR network : '#{network}'" unless valid_ipv4_cidr?(network)
routes_file = routes_file(device)
ip_route_cmd = ip_route_cmd(network, nat_server_ip)
update_config_file(
routes_file,
ip_route_cmd,
"Route to #{ip_route_cmd} already exists in #{routes_file}",
"Appending #{ip_route_cmd} route to #{routes_file}"
)
true
end | ruby | def update_route_file(network, nat_server_ip, device)
raise "ERROR: invalid nat_server_ip : '#{nat_server_ip}'" unless valid_ipv4?(nat_server_ip)
raise "ERROR: invalid CIDR network : '#{network}'" unless valid_ipv4_cidr?(network)
routes_file = routes_file(device)
ip_route_cmd = ip_route_cmd(network, nat_server_ip)
update_config_file(
routes_file,
ip_route_cmd,
"Route to #{ip_route_cmd} already exists in #{routes_file}",
"Appending #{ip_route_cmd} route to #{routes_file}"
)
true
end | [
"def",
"update_route_file",
"(",
"network",
",",
"nat_server_ip",
",",
"device",
")",
"raise",
"\"ERROR: invalid nat_server_ip : '#{nat_server_ip}'\"",
"unless",
"valid_ipv4?",
"(",
"nat_server_ip",
")",
"raise",
"\"ERROR: invalid CIDR network : '#{network}'\"",
"unless",
"valid_ipv4_cidr?",
"(",
"network",
")",
"routes_file",
"=",
"routes_file",
"(",
"device",
")",
"ip_route_cmd",
"=",
"ip_route_cmd",
"(",
"network",
",",
"nat_server_ip",
")",
"update_config_file",
"(",
"routes_file",
",",
"ip_route_cmd",
",",
"\"Route to #{ip_route_cmd} already exists in #{routes_file}\"",
",",
"\"Appending #{ip_route_cmd} route to #{routes_file}\"",
")",
"true",
"end"
] | Persist network route to file
If the file does not exist, it will be created.
If the route already exists, it will not be added again.
=== Parameters
network(String):: target network in CIDR notation
nat_server_ip(String):: the IP address of the NAT "router"
=== Return
result(True):: Always returns true | [
"Persist",
"network",
"route",
"to",
"file"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/network_configurator/centos_network_configurator.rb#L149-L163 | train |
rightscale/right_link | lib/instance/network_configurator/centos_network_configurator.rb | RightScale.CentosNetworkConfigurator.write_adaptor_config | def write_adaptor_config(device, data)
config_file = config_file(device)
raise "FATAL: invalid device name of '#{device}' specified for static IP allocation" unless device.match(/eth[0-9+]/)
logger.info "Writing persistent network configuration to #{config_file}"
File.open(config_file, "w") { |f| f.write(data) }
end | ruby | def write_adaptor_config(device, data)
config_file = config_file(device)
raise "FATAL: invalid device name of '#{device}' specified for static IP allocation" unless device.match(/eth[0-9+]/)
logger.info "Writing persistent network configuration to #{config_file}"
File.open(config_file, "w") { |f| f.write(data) }
end | [
"def",
"write_adaptor_config",
"(",
"device",
",",
"data",
")",
"config_file",
"=",
"config_file",
"(",
"device",
")",
"raise",
"\"FATAL: invalid device name of '#{device}' specified for static IP allocation\"",
"unless",
"device",
".",
"match",
"(",
"/",
"/",
")",
"logger",
".",
"info",
"\"Writing persistent network configuration to #{config_file}\"",
"File",
".",
"open",
"(",
"config_file",
",",
"\"w\"",
")",
"{",
"|",
"f",
"|",
"f",
".",
"write",
"(",
"data",
")",
"}",
"end"
] | Persist device config to a file
If the file does not exist, it will be created.
=== Parameters
device(String):: target device name
data(String):: target device config | [
"Persist",
"device",
"config",
"to",
"a",
"file"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/network_configurator/centos_network_configurator.rb#L225-L230 | train |
rightscale/right_link | lib/instance/network_configurator/centos_network_configurator.rb | RightScale.CentosNetworkConfigurator.update_config_file | def update_config_file(filename, line, exists_str=nil, append_str=nil)
FileUtils.mkdir_p(File.dirname(filename)) # make sure the directory exists
if read_config_file(filename).include?(line)
exists_str ||= "Config already exists in #{filename}"
logger.info exists_str
else
append_str ||= "Appending config to #{filename}"
logger.info append_str
append_config_file(filename, line)
end
true
end | ruby | def update_config_file(filename, line, exists_str=nil, append_str=nil)
FileUtils.mkdir_p(File.dirname(filename)) # make sure the directory exists
if read_config_file(filename).include?(line)
exists_str ||= "Config already exists in #{filename}"
logger.info exists_str
else
append_str ||= "Appending config to #{filename}"
logger.info append_str
append_config_file(filename, line)
end
true
end | [
"def",
"update_config_file",
"(",
"filename",
",",
"line",
",",
"exists_str",
"=",
"nil",
",",
"append_str",
"=",
"nil",
")",
"FileUtils",
".",
"mkdir_p",
"(",
"File",
".",
"dirname",
"(",
"filename",
")",
")",
"if",
"read_config_file",
"(",
"filename",
")",
".",
"include?",
"(",
"line",
")",
"exists_str",
"||=",
"\"Config already exists in #{filename}\"",
"logger",
".",
"info",
"exists_str",
"else",
"append_str",
"||=",
"\"Appending config to #{filename}\"",
"logger",
".",
"info",
"append_str",
"append_config_file",
"(",
"filename",
",",
"line",
")",
"end",
"true",
"end"
] | Add line to config file
If the file does not exist, it will be created.
If the line already exists, it will not be added again.
=== Parameters
filename(String):: absolute path to config file
line(String):: line to add
=== Return
result(Hash):: Hash-like leaf value | [
"Add",
"line",
"to",
"config",
"file"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/network_configurator/centos_network_configurator.rb#L299-L312 | train |
rightscale/right_link | lib/instance/network_configurator/centos_network_configurator.rb | RightScale.CentosNetworkConfigurator.read_config_file | def read_config_file(filename)
contents = ""
File.open(filename, "r") { |f| contents = f.read() } if File.exists?(filename)
contents
end | ruby | def read_config_file(filename)
contents = ""
File.open(filename, "r") { |f| contents = f.read() } if File.exists?(filename)
contents
end | [
"def",
"read_config_file",
"(",
"filename",
")",
"contents",
"=",
"\"\"",
"File",
".",
"open",
"(",
"filename",
",",
"\"r\"",
")",
"{",
"|",
"f",
"|",
"contents",
"=",
"f",
".",
"read",
"(",
")",
"}",
"if",
"File",
".",
"exists?",
"(",
"filename",
")",
"contents",
"end"
] | Read contents of config file
If file doesn't exist, return empty string
=== Return
result(String):: All lines in file | [
"Read",
"contents",
"of",
"config",
"file"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/network_configurator/centos_network_configurator.rb#L320-L324 | train |
rightscale/right_link | lib/instance/network_configurator/centos_network_configurator.rb | RightScale.CentosNetworkConfigurator.append_config_file | def append_config_file(filename, line)
File.open(filename, "a") { |f| f.puts(line) }
end | ruby | def append_config_file(filename, line)
File.open(filename, "a") { |f| f.puts(line) }
end | [
"def",
"append_config_file",
"(",
"filename",
",",
"line",
")",
"File",
".",
"open",
"(",
"filename",
",",
"\"a\"",
")",
"{",
"|",
"f",
"|",
"f",
".",
"puts",
"(",
"line",
")",
"}",
"end"
] | Appends line to config file | [
"Appends",
"line",
"to",
"config",
"file"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/network_configurator/centos_network_configurator.rb#L328-L330 | train |
rightscale/right_link | lib/instance/cook/cook.rb | RightScale.Cook.run | def run
# 1. Load configuration settings
options = OptionsBag.load
agent_id = options[:identity]
AgentConfig.root_dir = options[:root_dir]
Log.program_name = 'RightLink'
Log.facility = 'user'
Log.log_to_file_only(options[:log_to_file_only])
Log.init(agent_id, options[:log_path])
Log.level = CookState.log_level
# add an additional logger if the agent is set to log to an alternate
# location (install, operate, decommission, ...)
Log.add_logger(::Logger.new(CookState.log_file)) if CookState.log_file
Log.info("[cook] Process starting up with dev tags: [#{CookState.startup_tags.select { |tag| tag.include?(CookState::DEV_TAG_NAMESPACE)}.join(', ')}]")
fail('Missing command server listen port') unless options[:listen_port]
fail('Missing command cookie') unless options[:cookie]
@client = CommandClient.new(options[:listen_port], options[:cookie])
ShutdownRequestProxy.init(@client)
# 2. Retrieve bundle
input = gets.chomp
begin
platform = RightScale::Platform
if platform.windows?
bundle = MessageEncoder::SecretSerializer.new(InstanceState.identity, ENV[ExecutableSequenceProxy::DECRYPTION_KEY_NAME]).load(input)
else
bundle = MessageEncoder::Serializer.new.load(input)
end
rescue Exception => e
fail('Invalid bundle', e.message)
end
fail('Missing bundle', 'No bundle to run') if bundle.nil?
@thread_name = bundle.runlist_policy.thread_name if bundle.respond_to?(:runlist_policy) && bundle.runlist_policy
@thread_name ||= RightScale::AgentConfig.default_thread_name
options[:thread_name] = @thread_name
# Chef state needs the server secret so it can encrypt state on disk.
# The secret is the same for all instances of the server (i.e. is still
# valid after stop and restart server).
server_secret = bundle.server_secret || AgentConfig.default_server_secret
ChefState.init(agent_id, server_secret, reset=false)
# 3. Run bundle
@@instance = self
success = nil
Log.debug("[cook] Thread name associated with bundle = #{@thread_name}")
gatherer = ExternalParameterGatherer.new(bundle, options)
sequence = ExecutableSequence.new(bundle)
EM.threadpool_size = 1
EM.error_handler do |e|
Log.error("Execution failed", e, :trace)
fail('Exception caught', "The following exception was caught during execution:\n #{e.message}")
end
EM.run do
begin
AuditStub.instance.init(options)
check_for_missing_inputs(bundle)
gatherer.callback { EM.defer { sequence.run } }
gatherer.errback { success = false; report_failure(gatherer) }
sequence.callback { success = true; send_inputs_patch(sequence) }
sequence.errback { success = false; report_failure(sequence) }
EM.defer { gatherer.run }
rescue Exception => e
fail('Execution failed', Log.format("Execution failed", e, :trace))
end
end
rescue Exception => e
fail('Execution failed', Log.format("Run failed", e, :trace))
ensure
Log.info("[cook] Process stopping")
exit(1) unless success
end | ruby | def run
# 1. Load configuration settings
options = OptionsBag.load
agent_id = options[:identity]
AgentConfig.root_dir = options[:root_dir]
Log.program_name = 'RightLink'
Log.facility = 'user'
Log.log_to_file_only(options[:log_to_file_only])
Log.init(agent_id, options[:log_path])
Log.level = CookState.log_level
# add an additional logger if the agent is set to log to an alternate
# location (install, operate, decommission, ...)
Log.add_logger(::Logger.new(CookState.log_file)) if CookState.log_file
Log.info("[cook] Process starting up with dev tags: [#{CookState.startup_tags.select { |tag| tag.include?(CookState::DEV_TAG_NAMESPACE)}.join(', ')}]")
fail('Missing command server listen port') unless options[:listen_port]
fail('Missing command cookie') unless options[:cookie]
@client = CommandClient.new(options[:listen_port], options[:cookie])
ShutdownRequestProxy.init(@client)
# 2. Retrieve bundle
input = gets.chomp
begin
platform = RightScale::Platform
if platform.windows?
bundle = MessageEncoder::SecretSerializer.new(InstanceState.identity, ENV[ExecutableSequenceProxy::DECRYPTION_KEY_NAME]).load(input)
else
bundle = MessageEncoder::Serializer.new.load(input)
end
rescue Exception => e
fail('Invalid bundle', e.message)
end
fail('Missing bundle', 'No bundle to run') if bundle.nil?
@thread_name = bundle.runlist_policy.thread_name if bundle.respond_to?(:runlist_policy) && bundle.runlist_policy
@thread_name ||= RightScale::AgentConfig.default_thread_name
options[:thread_name] = @thread_name
# Chef state needs the server secret so it can encrypt state on disk.
# The secret is the same for all instances of the server (i.e. is still
# valid after stop and restart server).
server_secret = bundle.server_secret || AgentConfig.default_server_secret
ChefState.init(agent_id, server_secret, reset=false)
# 3. Run bundle
@@instance = self
success = nil
Log.debug("[cook] Thread name associated with bundle = #{@thread_name}")
gatherer = ExternalParameterGatherer.new(bundle, options)
sequence = ExecutableSequence.new(bundle)
EM.threadpool_size = 1
EM.error_handler do |e|
Log.error("Execution failed", e, :trace)
fail('Exception caught', "The following exception was caught during execution:\n #{e.message}")
end
EM.run do
begin
AuditStub.instance.init(options)
check_for_missing_inputs(bundle)
gatherer.callback { EM.defer { sequence.run } }
gatherer.errback { success = false; report_failure(gatherer) }
sequence.callback { success = true; send_inputs_patch(sequence) }
sequence.errback { success = false; report_failure(sequence) }
EM.defer { gatherer.run }
rescue Exception => e
fail('Execution failed', Log.format("Execution failed", e, :trace))
end
end
rescue Exception => e
fail('Execution failed', Log.format("Run failed", e, :trace))
ensure
Log.info("[cook] Process stopping")
exit(1) unless success
end | [
"def",
"run",
"options",
"=",
"OptionsBag",
".",
"load",
"agent_id",
"=",
"options",
"[",
":identity",
"]",
"AgentConfig",
".",
"root_dir",
"=",
"options",
"[",
":root_dir",
"]",
"Log",
".",
"program_name",
"=",
"'RightLink'",
"Log",
".",
"facility",
"=",
"'user'",
"Log",
".",
"log_to_file_only",
"(",
"options",
"[",
":log_to_file_only",
"]",
")",
"Log",
".",
"init",
"(",
"agent_id",
",",
"options",
"[",
":log_path",
"]",
")",
"Log",
".",
"level",
"=",
"CookState",
".",
"log_level",
"Log",
".",
"add_logger",
"(",
"::",
"Logger",
".",
"new",
"(",
"CookState",
".",
"log_file",
")",
")",
"if",
"CookState",
".",
"log_file",
"Log",
".",
"info",
"(",
"\"[cook] Process starting up with dev tags: [#{CookState.startup_tags.select { |tag| tag.include?(CookState::DEV_TAG_NAMESPACE)}.join(', ')}]\"",
")",
"fail",
"(",
"'Missing command server listen port'",
")",
"unless",
"options",
"[",
":listen_port",
"]",
"fail",
"(",
"'Missing command cookie'",
")",
"unless",
"options",
"[",
":cookie",
"]",
"@client",
"=",
"CommandClient",
".",
"new",
"(",
"options",
"[",
":listen_port",
"]",
",",
"options",
"[",
":cookie",
"]",
")",
"ShutdownRequestProxy",
".",
"init",
"(",
"@client",
")",
"input",
"=",
"gets",
".",
"chomp",
"begin",
"platform",
"=",
"RightScale",
"::",
"Platform",
"if",
"platform",
".",
"windows?",
"bundle",
"=",
"MessageEncoder",
"::",
"SecretSerializer",
".",
"new",
"(",
"InstanceState",
".",
"identity",
",",
"ENV",
"[",
"ExecutableSequenceProxy",
"::",
"DECRYPTION_KEY_NAME",
"]",
")",
".",
"load",
"(",
"input",
")",
"else",
"bundle",
"=",
"MessageEncoder",
"::",
"Serializer",
".",
"new",
".",
"load",
"(",
"input",
")",
"end",
"rescue",
"Exception",
"=>",
"e",
"fail",
"(",
"'Invalid bundle'",
",",
"e",
".",
"message",
")",
"end",
"fail",
"(",
"'Missing bundle'",
",",
"'No bundle to run'",
")",
"if",
"bundle",
".",
"nil?",
"@thread_name",
"=",
"bundle",
".",
"runlist_policy",
".",
"thread_name",
"if",
"bundle",
".",
"respond_to?",
"(",
":runlist_policy",
")",
"&&",
"bundle",
".",
"runlist_policy",
"@thread_name",
"||=",
"RightScale",
"::",
"AgentConfig",
".",
"default_thread_name",
"options",
"[",
":thread_name",
"]",
"=",
"@thread_name",
"server_secret",
"=",
"bundle",
".",
"server_secret",
"||",
"AgentConfig",
".",
"default_server_secret",
"ChefState",
".",
"init",
"(",
"agent_id",
",",
"server_secret",
",",
"reset",
"=",
"false",
")",
"@@instance",
"=",
"self",
"success",
"=",
"nil",
"Log",
".",
"debug",
"(",
"\"[cook] Thread name associated with bundle = #{@thread_name}\"",
")",
"gatherer",
"=",
"ExternalParameterGatherer",
".",
"new",
"(",
"bundle",
",",
"options",
")",
"sequence",
"=",
"ExecutableSequence",
".",
"new",
"(",
"bundle",
")",
"EM",
".",
"threadpool_size",
"=",
"1",
"EM",
".",
"error_handler",
"do",
"|",
"e",
"|",
"Log",
".",
"error",
"(",
"\"Execution failed\"",
",",
"e",
",",
":trace",
")",
"fail",
"(",
"'Exception caught'",
",",
"\"The following exception was caught during execution:\\n #{e.message}\"",
")",
"end",
"EM",
".",
"run",
"do",
"begin",
"AuditStub",
".",
"instance",
".",
"init",
"(",
"options",
")",
"check_for_missing_inputs",
"(",
"bundle",
")",
"gatherer",
".",
"callback",
"{",
"EM",
".",
"defer",
"{",
"sequence",
".",
"run",
"}",
"}",
"gatherer",
".",
"errback",
"{",
"success",
"=",
"false",
";",
"report_failure",
"(",
"gatherer",
")",
"}",
"sequence",
".",
"callback",
"{",
"success",
"=",
"true",
";",
"send_inputs_patch",
"(",
"sequence",
")",
"}",
"sequence",
".",
"errback",
"{",
"success",
"=",
"false",
";",
"report_failure",
"(",
"sequence",
")",
"}",
"EM",
".",
"defer",
"{",
"gatherer",
".",
"run",
"}",
"rescue",
"Exception",
"=>",
"e",
"fail",
"(",
"'Execution failed'",
",",
"Log",
".",
"format",
"(",
"\"Execution failed\"",
",",
"e",
",",
":trace",
")",
")",
"end",
"end",
"rescue",
"Exception",
"=>",
"e",
"fail",
"(",
"'Execution failed'",
",",
"Log",
".",
"format",
"(",
"\"Run failed\"",
",",
"e",
",",
":trace",
")",
")",
"ensure",
"Log",
".",
"info",
"(",
"\"[cook] Process stopping\"",
")",
"exit",
"(",
"1",
")",
"unless",
"success",
"end"
] | Run bundle given in stdin | [
"Run",
"bundle",
"given",
"in",
"stdin"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/cook.rb#L42-L120 | train |
rightscale/right_link | lib/instance/cook/cook.rb | RightScale.Cook.send_push | def send_push(type, payload = nil, target = nil, opts = {})
cmd = {:name => :send_push, :type => type, :payload => payload, :target => target, :options => opts}
# Need to execute on EM main thread where command client is running
EM.next_tick { @client.send_command(cmd) }
end | ruby | def send_push(type, payload = nil, target = nil, opts = {})
cmd = {:name => :send_push, :type => type, :payload => payload, :target => target, :options => opts}
# Need to execute on EM main thread where command client is running
EM.next_tick { @client.send_command(cmd) }
end | [
"def",
"send_push",
"(",
"type",
",",
"payload",
"=",
"nil",
",",
"target",
"=",
"nil",
",",
"opts",
"=",
"{",
"}",
")",
"cmd",
"=",
"{",
":name",
"=>",
":send_push",
",",
":type",
"=>",
"type",
",",
":payload",
"=>",
"payload",
",",
":target",
"=>",
"target",
",",
":options",
"=>",
"opts",
"}",
"EM",
".",
"next_tick",
"{",
"@client",
".",
"send_command",
"(",
"cmd",
")",
"}",
"end"
] | Helper method to send a request to one or more targets with no response expected
See InstanceCommands for details | [
"Helper",
"method",
"to",
"send",
"a",
"request",
"to",
"one",
"or",
"more",
"targets",
"with",
"no",
"response",
"expected",
"See",
"InstanceCommands",
"for",
"details"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/cook.rb#L141-L145 | train |
rightscale/right_link | lib/instance/cook/cook.rb | RightScale.Cook.load_tags | def load_tags(timeout)
cmd = { :name => :get_tags }
res = blocking_request(cmd, timeout)
raise TagError.new("Retrieving current tags failed: #{res.inspect}") unless res.kind_of?(Array)
::Chef::Log.info("Successfully loaded current tags: '#{res.join("', '")}'")
res
end | ruby | def load_tags(timeout)
cmd = { :name => :get_tags }
res = blocking_request(cmd, timeout)
raise TagError.new("Retrieving current tags failed: #{res.inspect}") unless res.kind_of?(Array)
::Chef::Log.info("Successfully loaded current tags: '#{res.join("', '")}'")
res
end | [
"def",
"load_tags",
"(",
"timeout",
")",
"cmd",
"=",
"{",
":name",
"=>",
":get_tags",
"}",
"res",
"=",
"blocking_request",
"(",
"cmd",
",",
"timeout",
")",
"raise",
"TagError",
".",
"new",
"(",
"\"Retrieving current tags failed: #{res.inspect}\"",
")",
"unless",
"res",
".",
"kind_of?",
"(",
"Array",
")",
"::",
"Chef",
"::",
"Log",
".",
"info",
"(",
"\"Successfully loaded current tags: '#{res.join(\"', '\")}'\"",
")",
"res",
"end"
] | Retrieve current instance tags
=== Parameters
timeout(Fixnum):: Number of seconds to wait for agent response | [
"Retrieve",
"current",
"instance",
"tags"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/cook.rb#L211-L218 | train |
rightscale/right_link | lib/instance/cook/cook.rb | RightScale.Cook.send_inputs_patch | def send_inputs_patch(sequence)
if has_default_thread?
begin
cmd = { :name => :set_inputs_patch, :patch => sequence.inputs_patch }
@client.send_command(cmd)
rescue Exception => e
fail('Failed to update inputs', Log.format("Failed to apply inputs patch after execution", e, :trace))
end
end
true
ensure
stop
end | ruby | def send_inputs_patch(sequence)
if has_default_thread?
begin
cmd = { :name => :set_inputs_patch, :patch => sequence.inputs_patch }
@client.send_command(cmd)
rescue Exception => e
fail('Failed to update inputs', Log.format("Failed to apply inputs patch after execution", e, :trace))
end
end
true
ensure
stop
end | [
"def",
"send_inputs_patch",
"(",
"sequence",
")",
"if",
"has_default_thread?",
"begin",
"cmd",
"=",
"{",
":name",
"=>",
":set_inputs_patch",
",",
":patch",
"=>",
"sequence",
".",
"inputs_patch",
"}",
"@client",
".",
"send_command",
"(",
"cmd",
")",
"rescue",
"Exception",
"=>",
"e",
"fail",
"(",
"'Failed to update inputs'",
",",
"Log",
".",
"format",
"(",
"\"Failed to apply inputs patch after execution\"",
",",
"e",
",",
":trace",
")",
")",
"end",
"end",
"true",
"ensure",
"stop",
"end"
] | Initialize instance variables
Report inputs patch to core | [
"Initialize",
"instance",
"variables",
"Report",
"inputs",
"patch",
"to",
"core"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/cook.rb#L234-L246 | train |
rightscale/right_link | lib/instance/cook/cook.rb | RightScale.Cook.report_failure | def report_failure(subject)
begin
AuditStub.instance.append_error(subject.failure_title, :category => RightScale::EventCategories::CATEGORY_ERROR) if subject.failure_title
AuditStub.instance.append_error(subject.failure_message) if subject.failure_message
rescue Exception => e
fail('Failed to report failure', Log.format("Failed to report failure after execution", e, :trace))
ensure
stop
end
end | ruby | def report_failure(subject)
begin
AuditStub.instance.append_error(subject.failure_title, :category => RightScale::EventCategories::CATEGORY_ERROR) if subject.failure_title
AuditStub.instance.append_error(subject.failure_message) if subject.failure_message
rescue Exception => e
fail('Failed to report failure', Log.format("Failed to report failure after execution", e, :trace))
ensure
stop
end
end | [
"def",
"report_failure",
"(",
"subject",
")",
"begin",
"AuditStub",
".",
"instance",
".",
"append_error",
"(",
"subject",
".",
"failure_title",
",",
":category",
"=>",
"RightScale",
"::",
"EventCategories",
"::",
"CATEGORY_ERROR",
")",
"if",
"subject",
".",
"failure_title",
"AuditStub",
".",
"instance",
".",
"append_error",
"(",
"subject",
".",
"failure_message",
")",
"if",
"subject",
".",
"failure_message",
"rescue",
"Exception",
"=>",
"e",
"fail",
"(",
"'Failed to report failure'",
",",
"Log",
".",
"format",
"(",
"\"Failed to report failure after execution\"",
",",
"e",
",",
":trace",
")",
")",
"ensure",
"stop",
"end",
"end"
] | Report failure to core | [
"Report",
"failure",
"to",
"core"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/cook.rb#L249-L258 | train |
rightscale/right_link | lib/instance/cook/cook.rb | RightScale.Cook.fail | def fail(title, message=nil)
$stderr.puts title
$stderr.puts message || title
if @client
@client.stop { AuditStub.instance.stop { exit(1) } }
else
exit(1)
end
end | ruby | def fail(title, message=nil)
$stderr.puts title
$stderr.puts message || title
if @client
@client.stop { AuditStub.instance.stop { exit(1) } }
else
exit(1)
end
end | [
"def",
"fail",
"(",
"title",
",",
"message",
"=",
"nil",
")",
"$stderr",
".",
"puts",
"title",
"$stderr",
".",
"puts",
"message",
"||",
"title",
"if",
"@client",
"@client",
".",
"stop",
"{",
"AuditStub",
".",
"instance",
".",
"stop",
"{",
"exit",
"(",
"1",
")",
"}",
"}",
"else",
"exit",
"(",
"1",
")",
"end",
"end"
] | Print failure message and exit abnormally | [
"Print",
"failure",
"message",
"and",
"exit",
"abnormally"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/cook.rb#L261-L269 | train |
rightscale/right_link | lib/instance/cook/cook.rb | RightScale.Cook.stop | def stop
AuditStub.instance.stop do
@client.stop do |timeout|
Log.info('[cook] Failed to stop command client cleanly, forcing shutdown...') if timeout
EM.stop
end
end
end | ruby | def stop
AuditStub.instance.stop do
@client.stop do |timeout|
Log.info('[cook] Failed to stop command client cleanly, forcing shutdown...') if timeout
EM.stop
end
end
end | [
"def",
"stop",
"AuditStub",
".",
"instance",
".",
"stop",
"do",
"@client",
".",
"stop",
"do",
"|",
"timeout",
"|",
"Log",
".",
"info",
"(",
"'[cook] Failed to stop command client cleanly, forcing shutdown...'",
")",
"if",
"timeout",
"EM",
".",
"stop",
"end",
"end",
"end"
] | Stop command client then stop auditor stub then EM | [
"Stop",
"command",
"client",
"then",
"stop",
"auditor",
"stub",
"then",
"EM"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/cook.rb#L272-L279 | train |
rightscale/right_link | lib/instance/cook/cook.rb | RightScale.Cook.blocking_request | def blocking_request(cmd, timeout)
raise BlockingError, "Blocking request not allowed on EM main thread for command #{cmd.inspect}" if EM.reactor_thread?
# Use a queue to block and wait for response
response_queue = Queue.new
# Need to execute on EM main thread where command client is running
EM.next_tick { @client.send_command(cmd, false, timeout) { |response| response_queue << response } }
return response_queue.shift
end | ruby | def blocking_request(cmd, timeout)
raise BlockingError, "Blocking request not allowed on EM main thread for command #{cmd.inspect}" if EM.reactor_thread?
# Use a queue to block and wait for response
response_queue = Queue.new
# Need to execute on EM main thread where command client is running
EM.next_tick { @client.send_command(cmd, false, timeout) { |response| response_queue << response } }
return response_queue.shift
end | [
"def",
"blocking_request",
"(",
"cmd",
",",
"timeout",
")",
"raise",
"BlockingError",
",",
"\"Blocking request not allowed on EM main thread for command #{cmd.inspect}\"",
"if",
"EM",
".",
"reactor_thread?",
"response_queue",
"=",
"Queue",
".",
"new",
"EM",
".",
"next_tick",
"{",
"@client",
".",
"send_command",
"(",
"cmd",
",",
"false",
",",
"timeout",
")",
"{",
"|",
"response",
"|",
"response_queue",
"<<",
"response",
"}",
"}",
"return",
"response_queue",
".",
"shift",
"end"
] | Provides a blocking request for the given command
Can only be called when on EM defer thread
=== Parameters
cmd(Hash):: request to send
=== Return
response(String):: raw response
=== Raise
BlockingError:: If request called when on EM main thread | [
"Provides",
"a",
"blocking",
"request",
"for",
"the",
"given",
"command",
"Can",
"only",
"be",
"called",
"when",
"on",
"EM",
"defer",
"thread"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/cook.rb#L292-L299 | train |
rightscale/right_link | lib/instance/cook/cook.rb | RightScale.Cook.load | def load(data, error_message, format = nil)
serializer = Serializer.new(format)
content = nil
begin
content = serializer.load(data)
rescue Exception => e
fail(error_message, "Failed to load #{serializer.format.to_s} data (#{e}):\n#{data.inspect}")
end
content
end | ruby | def load(data, error_message, format = nil)
serializer = Serializer.new(format)
content = nil
begin
content = serializer.load(data)
rescue Exception => e
fail(error_message, "Failed to load #{serializer.format.to_s} data (#{e}):\n#{data.inspect}")
end
content
end | [
"def",
"load",
"(",
"data",
",",
"error_message",
",",
"format",
"=",
"nil",
")",
"serializer",
"=",
"Serializer",
".",
"new",
"(",
"format",
")",
"content",
"=",
"nil",
"begin",
"content",
"=",
"serializer",
".",
"load",
"(",
"data",
")",
"rescue",
"Exception",
"=>",
"e",
"fail",
"(",
"error_message",
",",
"\"Failed to load #{serializer.format.to_s} data (#{e}):\\n#{data.inspect}\"",
")",
"end",
"content",
"end"
] | Load serialized content
fail if serialized data is invalid
=== Parameters
data(String):: Serialized content
error_message(String):: Error to be logged/audited in case of failure
format(Symbol):: Serialization format
=== Return
content(String):: Unserialized content | [
"Load",
"serialized",
"content",
"fail",
"if",
"serialized",
"data",
"is",
"invalid"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/cook.rb#L311-L320 | train |
piotrmurach/verse | lib/verse/wrapping.rb | Verse.Wrapping.wrap | def wrap(wrap_at = DEFAULT_WIDTH)
if text.length < wrap_at.to_i || wrap_at.to_i.zero?
return text
end
ansi_stack = []
text.split(NEWLINE, -1).map do |paragraph|
format_paragraph(paragraph, wrap_at, ansi_stack)
end * NEWLINE
end | ruby | def wrap(wrap_at = DEFAULT_WIDTH)
if text.length < wrap_at.to_i || wrap_at.to_i.zero?
return text
end
ansi_stack = []
text.split(NEWLINE, -1).map do |paragraph|
format_paragraph(paragraph, wrap_at, ansi_stack)
end * NEWLINE
end | [
"def",
"wrap",
"(",
"wrap_at",
"=",
"DEFAULT_WIDTH",
")",
"if",
"text",
".",
"length",
"<",
"wrap_at",
".",
"to_i",
"||",
"wrap_at",
".",
"to_i",
".",
"zero?",
"return",
"text",
"end",
"ansi_stack",
"=",
"[",
"]",
"text",
".",
"split",
"(",
"NEWLINE",
",",
"-",
"1",
")",
".",
"map",
"do",
"|",
"paragraph",
"|",
"format_paragraph",
"(",
"paragraph",
",",
"wrap_at",
",",
"ansi_stack",
")",
"end",
"*",
"NEWLINE",
"end"
] | Wrap a text into lines no longer than wrap_at length.
Preserves existing lines and existing word boundaries.
@example
wrapping = Verse::Wrapping.new "Some longish text"
wrapping.wrap(8)
# => >Some
>longish
>text
@api public | [
"Wrap",
"a",
"text",
"into",
"lines",
"no",
"longer",
"than",
"wrap_at",
"length",
".",
"Preserves",
"existing",
"lines",
"and",
"existing",
"word",
"boundaries",
"."
] | 4e3b9e4b3741600ee58e24478d463bfc553786f2 | https://github.com/piotrmurach/verse/blob/4e3b9e4b3741600ee58e24478d463bfc553786f2/lib/verse/wrapping.rb#L41-L49 | train |
davetron5000/moocow | lib/moocow/endpoint.rb | RTM.Endpoint.url_for | def url_for(method,params={},endpoint='rest')
params['api_key'] = @api_key
params['method'] = method if method
signature = sign(params)
url = BASE_URL + endpoint + '/' + params_to_url(params.merge({'api_sig' => signature}))
url
end | ruby | def url_for(method,params={},endpoint='rest')
params['api_key'] = @api_key
params['method'] = method if method
signature = sign(params)
url = BASE_URL + endpoint + '/' + params_to_url(params.merge({'api_sig' => signature}))
url
end | [
"def",
"url_for",
"(",
"method",
",",
"params",
"=",
"{",
"}",
",",
"endpoint",
"=",
"'rest'",
")",
"params",
"[",
"'api_key'",
"]",
"=",
"@api_key",
"params",
"[",
"'method'",
"]",
"=",
"method",
"if",
"method",
"signature",
"=",
"sign",
"(",
"params",
")",
"url",
"=",
"BASE_URL",
"+",
"endpoint",
"+",
"'/'",
"+",
"params_to_url",
"(",
"params",
".",
"merge",
"(",
"{",
"'api_sig'",
"=>",
"signature",
"}",
")",
")",
"url",
"end"
] | Get the url for a particular call, doing the signing and all that other stuff.
[method] the RTM method to call
[params] hash of parameters. The +method+, +api_key+, and +api_sig+ parameters should _not_ be included.
[endpoint] the endpoint relate to BASE_URL at which this request should be made. | [
"Get",
"the",
"url",
"for",
"a",
"particular",
"call",
"doing",
"the",
"signing",
"and",
"all",
"that",
"other",
"stuff",
"."
] | 92377d31d76728097fe505a5d0bf5dd7f034c9d5 | https://github.com/davetron5000/moocow/blob/92377d31d76728097fe505a5d0bf5dd7f034c9d5/lib/moocow/endpoint.rb#L85-L91 | train |
davetron5000/moocow | lib/moocow/endpoint.rb | RTM.Endpoint.params_to_url | def params_to_url(params)
string = '?'
params.each do |k,v|
string += CGI::escape(k)
string += '='
string += CGI::escape(v)
string += '&'
end
string
end | ruby | def params_to_url(params)
string = '?'
params.each do |k,v|
string += CGI::escape(k)
string += '='
string += CGI::escape(v)
string += '&'
end
string
end | [
"def",
"params_to_url",
"(",
"params",
")",
"string",
"=",
"'?'",
"params",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"string",
"+=",
"CGI",
"::",
"escape",
"(",
"k",
")",
"string",
"+=",
"'='",
"string",
"+=",
"CGI",
"::",
"escape",
"(",
"v",
")",
"string",
"+=",
"'&'",
"end",
"string",
"end"
] | Turns params into a URL | [
"Turns",
"params",
"into",
"a",
"URL"
] | 92377d31d76728097fe505a5d0bf5dd7f034c9d5 | https://github.com/davetron5000/moocow/blob/92377d31d76728097fe505a5d0bf5dd7f034c9d5/lib/moocow/endpoint.rb#L119-L128 | train |
davetron5000/moocow | lib/moocow/endpoint.rb | RTM.Endpoint.sign | def sign(params)
raise "Something's wrong; @secret is nil" if @secret.nil?
sign_me = @secret
params.keys.sort.each do |key|
sign_me += key
raise "Omit params with nil values; key #{key} was nil" if params[key].nil?
sign_me += params[key]
end
return Digest::MD5.hexdigest(sign_me)
end | ruby | def sign(params)
raise "Something's wrong; @secret is nil" if @secret.nil?
sign_me = @secret
params.keys.sort.each do |key|
sign_me += key
raise "Omit params with nil values; key #{key} was nil" if params[key].nil?
sign_me += params[key]
end
return Digest::MD5.hexdigest(sign_me)
end | [
"def",
"sign",
"(",
"params",
")",
"raise",
"\"Something's wrong; @secret is nil\"",
"if",
"@secret",
".",
"nil?",
"sign_me",
"=",
"@secret",
"params",
".",
"keys",
".",
"sort",
".",
"each",
"do",
"|",
"key",
"|",
"sign_me",
"+=",
"key",
"raise",
"\"Omit params with nil values; key #{key} was nil\"",
"if",
"params",
"[",
"key",
"]",
".",
"nil?",
"sign_me",
"+=",
"params",
"[",
"key",
"]",
"end",
"return",
"Digest",
"::",
"MD5",
".",
"hexdigest",
"(",
"sign_me",
")",
"end"
] | Signs the request given the params and secret key
[params] hash of parameters | [
"Signs",
"the",
"request",
"given",
"the",
"params",
"and",
"secret",
"key"
] | 92377d31d76728097fe505a5d0bf5dd7f034c9d5 | https://github.com/davetron5000/moocow/blob/92377d31d76728097fe505a5d0bf5dd7f034c9d5/lib/moocow/endpoint.rb#L134-L143 | train |
flippa/ralexa | lib/ralexa/top_sites.rb | Ralexa.TopSites.country | def country(code, limit, params = {})
paginating_collection(
limit,
PER_PAGE,
{"ResponseGroup" => "Country", "CountryCode" => code.to_s.upcase},
params,
&top_sites_parser
)
end | ruby | def country(code, limit, params = {})
paginating_collection(
limit,
PER_PAGE,
{"ResponseGroup" => "Country", "CountryCode" => code.to_s.upcase},
params,
&top_sites_parser
)
end | [
"def",
"country",
"(",
"code",
",",
"limit",
",",
"params",
"=",
"{",
"}",
")",
"paginating_collection",
"(",
"limit",
",",
"PER_PAGE",
",",
"{",
"\"ResponseGroup\"",
"=>",
"\"Country\"",
",",
"\"CountryCode\"",
"=>",
"code",
".",
"to_s",
".",
"upcase",
"}",
",",
"params",
",",
"&",
"top_sites_parser",
")",
"end"
] | Top sites for the specified two letter country code. | [
"Top",
"sites",
"for",
"the",
"specified",
"two",
"letter",
"country",
"code",
"."
] | fd5bdff102fe52f5c2898b1f917a12a1f17f25de | https://github.com/flippa/ralexa/blob/fd5bdff102fe52f5c2898b1f917a12a1f17f25de/lib/ralexa/top_sites.rb#L18-L26 | train |
flippa/ralexa | lib/ralexa/top_sites.rb | Ralexa.TopSites.list_countries | def list_countries(params = {})
collection({"ResponseGroup" => "ListCountries"}, params) do |document|
path = "//TopSitesResult/Alexa/TopSites/Countries"
document.at(path).elements.map do |node|
Country.new(
node.at("Name").text,
node.at("Code").text,
node.at("TotalSites").text.to_i,
node.at("PageViews").text.to_f * 1_000_000,
node.at("Users").text.to_f * 1_000_000,
)
end
end
end | ruby | def list_countries(params = {})
collection({"ResponseGroup" => "ListCountries"}, params) do |document|
path = "//TopSitesResult/Alexa/TopSites/Countries"
document.at(path).elements.map do |node|
Country.new(
node.at("Name").text,
node.at("Code").text,
node.at("TotalSites").text.to_i,
node.at("PageViews").text.to_f * 1_000_000,
node.at("Users").text.to_f * 1_000_000,
)
end
end
end | [
"def",
"list_countries",
"(",
"params",
"=",
"{",
"}",
")",
"collection",
"(",
"{",
"\"ResponseGroup\"",
"=>",
"\"ListCountries\"",
"}",
",",
"params",
")",
"do",
"|",
"document",
"|",
"path",
"=",
"\"//TopSitesResult/Alexa/TopSites/Countries\"",
"document",
".",
"at",
"(",
"path",
")",
".",
"elements",
".",
"map",
"do",
"|",
"node",
"|",
"Country",
".",
"new",
"(",
"node",
".",
"at",
"(",
"\"Name\"",
")",
".",
"text",
",",
"node",
".",
"at",
"(",
"\"Code\"",
")",
".",
"text",
",",
"node",
".",
"at",
"(",
"\"TotalSites\"",
")",
".",
"text",
".",
"to_i",
",",
"node",
".",
"at",
"(",
"\"PageViews\"",
")",
".",
"text",
".",
"to_f",
"*",
"1_000_000",
",",
"node",
".",
"at",
"(",
"\"Users\"",
")",
".",
"text",
".",
"to_f",
"*",
"1_000_000",
",",
")",
"end",
"end",
"end"
] | All countries that have Alexa top sites. | [
"All",
"countries",
"that",
"have",
"Alexa",
"top",
"sites",
"."
] | fd5bdff102fe52f5c2898b1f917a12a1f17f25de | https://github.com/flippa/ralexa/blob/fd5bdff102fe52f5c2898b1f917a12a1f17f25de/lib/ralexa/top_sites.rb#L29-L42 | train |
jrichardlai/taskrabbit | lib/taskrabbit/smash.rb | Taskrabbit.Smash.reload | def reload(method, path, options = {})
self.loaded = true
response = request(method, path, self.class, Smash::filtered_options(options))
self.merge!(response)
clear_errors
!redirect?
rescue Smash::Error => e
self.merge!(e.response) if e.response.is_a?(Hash)
false
end | ruby | def reload(method, path, options = {})
self.loaded = true
response = request(method, path, self.class, Smash::filtered_options(options))
self.merge!(response)
clear_errors
!redirect?
rescue Smash::Error => e
self.merge!(e.response) if e.response.is_a?(Hash)
false
end | [
"def",
"reload",
"(",
"method",
",",
"path",
",",
"options",
"=",
"{",
"}",
")",
"self",
".",
"loaded",
"=",
"true",
"response",
"=",
"request",
"(",
"method",
",",
"path",
",",
"self",
".",
"class",
",",
"Smash",
"::",
"filtered_options",
"(",
"options",
")",
")",
"self",
".",
"merge!",
"(",
"response",
")",
"clear_errors",
"!",
"redirect?",
"rescue",
"Smash",
"::",
"Error",
"=>",
"e",
"self",
".",
"merge!",
"(",
"e",
".",
"response",
")",
"if",
"e",
".",
"response",
".",
"is_a?",
"(",
"Hash",
")",
"false",
"end"
] | reload the object after doing a query to the api | [
"reload",
"the",
"object",
"after",
"doing",
"a",
"query",
"to",
"the",
"api"
] | 26f8526b60091a46b444e7b736137133868fb3c2 | https://github.com/jrichardlai/taskrabbit/blob/26f8526b60091a46b444e7b736137133868fb3c2/lib/taskrabbit/smash.rb#L63-L72 | train |
jrichardlai/taskrabbit | lib/taskrabbit/smash.rb | Taskrabbit.Smash.[] | def [](property)
value = nil
return value unless (value = super(property)).nil?
if api and !loaded
# load the object if trying to access a property
self.loaded = true
fetch
end
super(property)
end | ruby | def [](property)
value = nil
return value unless (value = super(property)).nil?
if api and !loaded
# load the object if trying to access a property
self.loaded = true
fetch
end
super(property)
end | [
"def",
"[]",
"(",
"property",
")",
"value",
"=",
"nil",
"return",
"value",
"unless",
"(",
"value",
"=",
"super",
"(",
"property",
")",
")",
".",
"nil?",
"if",
"api",
"and",
"!",
"loaded",
"self",
".",
"loaded",
"=",
"true",
"fetch",
"end",
"super",
"(",
"property",
")",
"end"
] | get the property from the hash
if the value is not set and the object has not been loaded, try to load it | [
"get",
"the",
"property",
"from",
"the",
"hash",
"if",
"the",
"value",
"is",
"not",
"set",
"and",
"the",
"object",
"has",
"not",
"been",
"loaded",
"try",
"to",
"load",
"it"
] | 26f8526b60091a46b444e7b736137133868fb3c2 | https://github.com/jrichardlai/taskrabbit/blob/26f8526b60091a46b444e7b736137133868fb3c2/lib/taskrabbit/smash.rb#L79-L88 | train |
christinedraper/knife-topo | lib/chef/knife/topo/bootstrap_helper.rb | KnifeTopo.BootstrapHelper.run_bootstrap | def run_bootstrap(data, bootstrap_args, overwrite = false)
node_name = data['name']
args = setup_bootstrap_args(bootstrap_args, data)
delete_client_node(node_name) if overwrite
ui.info "Bootstrapping node #{node_name}"
run_cmd(Chef::Knife::Bootstrap, args)
rescue StandardError => e
raise if Chef::Config[:verbosity] == 2
ui.warn "bootstrap of node #{node_name} exited with error"
humanize_exception(e)
false
end | ruby | def run_bootstrap(data, bootstrap_args, overwrite = false)
node_name = data['name']
args = setup_bootstrap_args(bootstrap_args, data)
delete_client_node(node_name) if overwrite
ui.info "Bootstrapping node #{node_name}"
run_cmd(Chef::Knife::Bootstrap, args)
rescue StandardError => e
raise if Chef::Config[:verbosity] == 2
ui.warn "bootstrap of node #{node_name} exited with error"
humanize_exception(e)
false
end | [
"def",
"run_bootstrap",
"(",
"data",
",",
"bootstrap_args",
",",
"overwrite",
"=",
"false",
")",
"node_name",
"=",
"data",
"[",
"'name'",
"]",
"args",
"=",
"setup_bootstrap_args",
"(",
"bootstrap_args",
",",
"data",
")",
"delete_client_node",
"(",
"node_name",
")",
"if",
"overwrite",
"ui",
".",
"info",
"\"Bootstrapping node #{node_name}\"",
"run_cmd",
"(",
"Chef",
"::",
"Knife",
"::",
"Bootstrap",
",",
"args",
")",
"rescue",
"StandardError",
"=>",
"e",
"raise",
"if",
"Chef",
"::",
"Config",
"[",
":verbosity",
"]",
"==",
"2",
"ui",
".",
"warn",
"\"bootstrap of node #{node_name} exited with error\"",
"humanize_exception",
"(",
"e",
")",
"false",
"end"
] | Setup the bootstrap args and run the bootstrap command | [
"Setup",
"the",
"bootstrap",
"args",
"and",
"run",
"the",
"bootstrap",
"command"
] | 323f5767a6ed98212629888323c4e694fec820ca | https://github.com/christinedraper/knife-topo/blob/323f5767a6ed98212629888323c4e694fec820ca/lib/chef/knife/topo/bootstrap_helper.rb#L28-L40 | train |
marks/truevault.rb | lib/truevault/authorization.rb | TrueVault.Authorization.login | def login(options = {})
body = {
body: {
username: options[:username],
password: options[:password],
account_id: options[:account_id]
}
}
self.class.post("/#{@api_ver}/auth/login", body)
end | ruby | def login(options = {})
body = {
body: {
username: options[:username],
password: options[:password],
account_id: options[:account_id]
}
}
self.class.post("/#{@api_ver}/auth/login", body)
end | [
"def",
"login",
"(",
"options",
"=",
"{",
"}",
")",
"body",
"=",
"{",
"body",
":",
"{",
"username",
":",
"options",
"[",
":username",
"]",
",",
"password",
":",
"options",
"[",
":password",
"]",
",",
"account_id",
":",
"options",
"[",
":account_id",
"]",
"}",
"}",
"self",
".",
"class",
".",
"post",
"(",
"\"/#{@api_ver}/auth/login\"",
",",
"body",
")",
"end"
] | AUTHORIZATION API Methods
logs in a user
the account_id is different from user id response
TVAuth.login(
username: "bar",
password: "foo",
account_id: "00000000-0000-0000-0000-000000000000"
) | [
"AUTHORIZATION",
"API",
"Methods"
] | d0d22fc0945de324e45e7d300a37542949ee67b9 | https://github.com/marks/truevault.rb/blob/d0d22fc0945de324e45e7d300a37542949ee67b9/lib/truevault/authorization.rb#L17-L26 | train |
rhenium/plum | lib/plum/frame.rb | Plum.Frame.flags | def flags
fs = FRAME_FLAGS[type]
[0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80]
.select { |v| @flags_value & v > 0 }
.map { |val| fs && fs.key(val) || ("unknown_%02x" % val).to_sym }
end | ruby | def flags
fs = FRAME_FLAGS[type]
[0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80]
.select { |v| @flags_value & v > 0 }
.map { |val| fs && fs.key(val) || ("unknown_%02x" % val).to_sym }
end | [
"def",
"flags",
"fs",
"=",
"FRAME_FLAGS",
"[",
"type",
"]",
"[",
"0x01",
",",
"0x02",
",",
"0x04",
",",
"0x08",
",",
"0x10",
",",
"0x20",
",",
"0x40",
",",
"0x80",
"]",
".",
"select",
"{",
"|",
"v",
"|",
"@flags_value",
"&",
"v",
">",
"0",
"}",
".",
"map",
"{",
"|",
"val",
"|",
"fs",
"&&",
"fs",
".",
"key",
"(",
"val",
")",
"||",
"(",
"\"unknown_%02x\"",
"%",
"val",
")",
".",
"to_sym",
"}",
"end"
] | Returns the set flags on the frame.
@return [Array<Symbol>] The flags. | [
"Returns",
"the",
"set",
"flags",
"on",
"the",
"frame",
"."
] | 9190801a092d46c7079ccee201b212b2d7985952 | https://github.com/rhenium/plum/blob/9190801a092d46c7079ccee201b212b2d7985952/lib/plum/frame.rb#L119-L124 | train |
rhenium/plum | lib/plum/frame.rb | Plum.Frame.flags= | def flags=(values)
val = 0
FRAME_FLAGS_MAP.values_at(*values).each { |c|
val |= c if c
}
@flags_value = val
end | ruby | def flags=(values)
val = 0
FRAME_FLAGS_MAP.values_at(*values).each { |c|
val |= c if c
}
@flags_value = val
end | [
"def",
"flags",
"=",
"(",
"values",
")",
"val",
"=",
"0",
"FRAME_FLAGS_MAP",
".",
"values_at",
"(",
"*",
"values",
")",
".",
"each",
"{",
"|",
"c",
"|",
"val",
"|=",
"c",
"if",
"c",
"}",
"@flags_value",
"=",
"val",
"end"
] | Sets the frame flags.
@param values [Array<Symbol>] The flags. | [
"Sets",
"the",
"frame",
"flags",
"."
] | 9190801a092d46c7079ccee201b212b2d7985952 | https://github.com/rhenium/plum/blob/9190801a092d46c7079ccee201b212b2d7985952/lib/plum/frame.rb#L128-L134 | train |
rhenium/plum | lib/plum/connection.rb | Plum.Connection.receive | def receive(new_data)
return if @state == :closed
return if new_data.empty?
@buffer << new_data
consume_buffer
rescue RemoteConnectionError => e
callback(:connection_error, e)
goaway(e.http2_error_type)
close
end | ruby | def receive(new_data)
return if @state == :closed
return if new_data.empty?
@buffer << new_data
consume_buffer
rescue RemoteConnectionError => e
callback(:connection_error, e)
goaway(e.http2_error_type)
close
end | [
"def",
"receive",
"(",
"new_data",
")",
"return",
"if",
"@state",
"==",
":closed",
"return",
"if",
"new_data",
".",
"empty?",
"@buffer",
"<<",
"new_data",
"consume_buffer",
"rescue",
"RemoteConnectionError",
"=>",
"e",
"callback",
"(",
":connection_error",
",",
"e",
")",
"goaway",
"(",
"e",
".",
"http2_error_type",
")",
"close",
"end"
] | Receives the specified data and process.
@param new_data [String] The data received from the peer. | [
"Receives",
"the",
"specified",
"data",
"and",
"process",
"."
] | 9190801a092d46c7079ccee201b212b2d7985952 | https://github.com/rhenium/plum/blob/9190801a092d46c7079ccee201b212b2d7985952/lib/plum/connection.rb#L49-L58 | train |
rhenium/plum | lib/plum/connection.rb | Plum.Connection.stream | def stream(stream_id, update_max_id = true)
raise ArgumentError, "stream_id can't be 0" if stream_id == 0
stream = @streams[stream_id]
if stream
if stream.state == :idle && stream_id < @max_stream_ids[stream_id % 2]
stream.set_state(:closed_implicitly)
end
elsif stream_id > @max_stream_ids[stream_id % 2]
@max_stream_ids[stream_id % 2] = stream_id if update_max_id
stream = Stream.new(self, stream_id, state: :idle)
callback(:stream, stream)
@streams[stream_id] = stream
else
stream = Stream.new(self, stream_id, state: :closed_implicitly)
callback(:stream, stream)
end
stream
end | ruby | def stream(stream_id, update_max_id = true)
raise ArgumentError, "stream_id can't be 0" if stream_id == 0
stream = @streams[stream_id]
if stream
if stream.state == :idle && stream_id < @max_stream_ids[stream_id % 2]
stream.set_state(:closed_implicitly)
end
elsif stream_id > @max_stream_ids[stream_id % 2]
@max_stream_ids[stream_id % 2] = stream_id if update_max_id
stream = Stream.new(self, stream_id, state: :idle)
callback(:stream, stream)
@streams[stream_id] = stream
else
stream = Stream.new(self, stream_id, state: :closed_implicitly)
callback(:stream, stream)
end
stream
end | [
"def",
"stream",
"(",
"stream_id",
",",
"update_max_id",
"=",
"true",
")",
"raise",
"ArgumentError",
",",
"\"stream_id can't be 0\"",
"if",
"stream_id",
"==",
"0",
"stream",
"=",
"@streams",
"[",
"stream_id",
"]",
"if",
"stream",
"if",
"stream",
".",
"state",
"==",
":idle",
"&&",
"stream_id",
"<",
"@max_stream_ids",
"[",
"stream_id",
"%",
"2",
"]",
"stream",
".",
"set_state",
"(",
":closed_implicitly",
")",
"end",
"elsif",
"stream_id",
">",
"@max_stream_ids",
"[",
"stream_id",
"%",
"2",
"]",
"@max_stream_ids",
"[",
"stream_id",
"%",
"2",
"]",
"=",
"stream_id",
"if",
"update_max_id",
"stream",
"=",
"Stream",
".",
"new",
"(",
"self",
",",
"stream_id",
",",
"state",
":",
":idle",
")",
"callback",
"(",
":stream",
",",
"stream",
")",
"@streams",
"[",
"stream_id",
"]",
"=",
"stream",
"else",
"stream",
"=",
"Stream",
".",
"new",
"(",
"self",
",",
"stream_id",
",",
"state",
":",
":closed_implicitly",
")",
"callback",
"(",
":stream",
",",
"stream",
")",
"end",
"stream",
"end"
] | Returns a Stream object with the specified ID.
@param stream_id [Integer] the stream id
@return [Stream] the stream | [
"Returns",
"a",
"Stream",
"object",
"with",
"the",
"specified",
"ID",
"."
] | 9190801a092d46c7079ccee201b212b2d7985952 | https://github.com/rhenium/plum/blob/9190801a092d46c7079ccee201b212b2d7985952/lib/plum/connection.rb#L64-L83 | train |
rhenium/plum | lib/plum/connection.rb | Plum.Connection.settings | def settings(**new_settings)
send_immediately Frame::Settings.new(**new_settings)
old_settings = @local_settings.dup
@local_settings.merge!(new_settings)
@hpack_decoder.limit = @local_settings[:header_table_size]
update_recv_initial_window_size(@local_settings[:initial_window_size] - old_settings[:initial_window_size])
end | ruby | def settings(**new_settings)
send_immediately Frame::Settings.new(**new_settings)
old_settings = @local_settings.dup
@local_settings.merge!(new_settings)
@hpack_decoder.limit = @local_settings[:header_table_size]
update_recv_initial_window_size(@local_settings[:initial_window_size] - old_settings[:initial_window_size])
end | [
"def",
"settings",
"(",
"**",
"new_settings",
")",
"send_immediately",
"Frame",
"::",
"Settings",
".",
"new",
"(",
"**",
"new_settings",
")",
"old_settings",
"=",
"@local_settings",
".",
"dup",
"@local_settings",
".",
"merge!",
"(",
"new_settings",
")",
"@hpack_decoder",
".",
"limit",
"=",
"@local_settings",
"[",
":header_table_size",
"]",
"update_recv_initial_window_size",
"(",
"@local_settings",
"[",
":initial_window_size",
"]",
"-",
"old_settings",
"[",
":initial_window_size",
"]",
")",
"end"
] | Sends local settings to the peer.
@param new_settings [Hash<Symbol, Integer>] | [
"Sends",
"local",
"settings",
"to",
"the",
"peer",
"."
] | 9190801a092d46c7079ccee201b212b2d7985952 | https://github.com/rhenium/plum/blob/9190801a092d46c7079ccee201b212b2d7985952/lib/plum/connection.rb#L87-L95 | train |
rhenium/plum | lib/plum/connection.rb | Plum.Connection.goaway | def goaway(error_type = :no_error, message = "")
last_id = @max_stream_ids.max
send_immediately Frame::Goaway.new(last_id, error_type, message)
end | ruby | def goaway(error_type = :no_error, message = "")
last_id = @max_stream_ids.max
send_immediately Frame::Goaway.new(last_id, error_type, message)
end | [
"def",
"goaway",
"(",
"error_type",
"=",
":no_error",
",",
"message",
"=",
"\"\"",
")",
"last_id",
"=",
"@max_stream_ids",
".",
"max",
"send_immediately",
"Frame",
"::",
"Goaway",
".",
"new",
"(",
"last_id",
",",
"error_type",
",",
"message",
")",
"end"
] | Sends GOAWAY frame to the peer and closes the connection.
@param error_type [Symbol] The error type to be contained in the GOAWAY frame. | [
"Sends",
"GOAWAY",
"frame",
"to",
"the",
"peer",
"and",
"closes",
"the",
"connection",
"."
] | 9190801a092d46c7079ccee201b212b2d7985952 | https://github.com/rhenium/plum/blob/9190801a092d46c7079ccee201b212b2d7985952/lib/plum/connection.rb#L106-L109 | train |
zinosama/transitionable | lib/transitionable.rb | Transitionable.ClassMethods.transition | def transition(name, states = self::STATES, transitions = self::TRANSITIONS)
self.state_machines ||= {}
self.state_machines[name] = { states: states.values, transitions: transitions }
self.state_machines[name][:states].each do |this_state|
method_name = "#{this_state}?".to_sym
raise 'Method already defined' if self.instance_methods(false).include?(method_name)
define_method method_name do
current_state_based_on(this_state) == this_state
end
end
end | ruby | def transition(name, states = self::STATES, transitions = self::TRANSITIONS)
self.state_machines ||= {}
self.state_machines[name] = { states: states.values, transitions: transitions }
self.state_machines[name][:states].each do |this_state|
method_name = "#{this_state}?".to_sym
raise 'Method already defined' if self.instance_methods(false).include?(method_name)
define_method method_name do
current_state_based_on(this_state) == this_state
end
end
end | [
"def",
"transition",
"(",
"name",
",",
"states",
"=",
"self",
"::",
"STATES",
",",
"transitions",
"=",
"self",
"::",
"TRANSITIONS",
")",
"self",
".",
"state_machines",
"||=",
"{",
"}",
"self",
".",
"state_machines",
"[",
"name",
"]",
"=",
"{",
"states",
":",
"states",
".",
"values",
",",
"transitions",
":",
"transitions",
"}",
"self",
".",
"state_machines",
"[",
"name",
"]",
"[",
":states",
"]",
".",
"each",
"do",
"|",
"this_state",
"|",
"method_name",
"=",
"\"#{this_state}?\"",
".",
"to_sym",
"raise",
"'Method already defined'",
"if",
"self",
".",
"instance_methods",
"(",
"false",
")",
".",
"include?",
"(",
"method_name",
")",
"define_method",
"method_name",
"do",
"current_state_based_on",
"(",
"this_state",
")",
"==",
"this_state",
"end",
"end",
"end"
] | This assumes states is a hash | [
"This",
"assumes",
"states",
"is",
"a",
"hash"
] | c2208bffbc377e68106d1349f18201941058e34e | https://github.com/zinosama/transitionable/blob/c2208bffbc377e68106d1349f18201941058e34e/lib/transitionable.rb#L22-L32 | train |
kandebonfim/itcsscli | lib/itcsscli.rb | Itcsscli.Core.inuit_find_modules | def inuit_find_modules(current_module)
current_config = YAML.load_file(@ITCSS_CONFIG_FILE)
current_inuit_modules = current_config["inuit_modules"].select{ |p| p.include? current_module }
current_inuit_modules.map{ |p| inuit_imports_path p }
end | ruby | def inuit_find_modules(current_module)
current_config = YAML.load_file(@ITCSS_CONFIG_FILE)
current_inuit_modules = current_config["inuit_modules"].select{ |p| p.include? current_module }
current_inuit_modules.map{ |p| inuit_imports_path p }
end | [
"def",
"inuit_find_modules",
"(",
"current_module",
")",
"current_config",
"=",
"YAML",
".",
"load_file",
"(",
"@ITCSS_CONFIG_FILE",
")",
"current_inuit_modules",
"=",
"current_config",
"[",
"\"inuit_modules\"",
"]",
".",
"select",
"{",
"|",
"p",
"|",
"p",
".",
"include?",
"current_module",
"}",
"current_inuit_modules",
".",
"map",
"{",
"|",
"p",
"|",
"inuit_imports_path",
"p",
"}",
"end"
] | Inuit Helper Methods | [
"Inuit",
"Helper",
"Methods"
] | 11ac53187a8c6af389e3aefabe0b54f0dd591526 | https://github.com/kandebonfim/itcsscli/blob/11ac53187a8c6af389e3aefabe0b54f0dd591526/lib/itcsscli.rb#L370-L374 | train |
artemk/syntaxer | lib/syntaxer/writer.rb | Syntaxer.Writer.block | def block name, param = nil, &b
sp = ' '*2 if name == :lang || name == :languages
body = yield self if block_given?
param = ":#{param.to_s}" unless param.nil?
"#{sp}#{name.to_s} #{param} do\n#{body}\n#{sp}end\n"
end | ruby | def block name, param = nil, &b
sp = ' '*2 if name == :lang || name == :languages
body = yield self if block_given?
param = ":#{param.to_s}" unless param.nil?
"#{sp}#{name.to_s} #{param} do\n#{body}\n#{sp}end\n"
end | [
"def",
"block",
"name",
",",
"param",
"=",
"nil",
",",
"&",
"b",
"sp",
"=",
"' '",
"*",
"2",
"if",
"name",
"==",
":lang",
"||",
"name",
"==",
":languages",
"body",
"=",
"yield",
"self",
"if",
"block_given?",
"param",
"=",
"\":#{param.to_s}\"",
"unless",
"param",
".",
"nil?",
"\"#{sp}#{name.to_s} #{param} do\\n#{body}\\n#{sp}end\\n\"",
"end"
] | Create DSL block
@param [Symbol, String] block name
@param [String] parameter that is passed in to block
@return [String] DSL block string | [
"Create",
"DSL",
"block"
] | 7557318e9ab1554b38cb8df9d00f2ff4acc701cb | https://github.com/artemk/syntaxer/blob/7557318e9ab1554b38cb8df9d00f2ff4acc701cb/lib/syntaxer/writer.rb#L63-L68 | train |
artemk/syntaxer | lib/syntaxer/writer.rb | Syntaxer.Writer.property | def property name, prop
return '' if EXCLUDE_PROPERTIES.include?(name.to_s) || prop.nil? || (prop.kind_of?(Array) && prop.empty?)
prop = prop.flatten.map{|p| "'#{p}'"}.join(', ') if prop.respond_to?(:flatten) && name.to_sym != :folders
prop = @paths.map{|f| "'#{f}'"}.join(',') if name.to_sym == :folders
prop = "'#{prop.exec_rule}'" if prop.instance_of?(Syntaxer::Runner::ExecRule) && !prop.exec_rule.nil?
prop = "Syntaxer::Runner.#{prop.language}" if prop.instance_of?(Syntaxer::Runner::ExecRule) && prop.exec_rule.nil?
' '*4 + "#{name.to_s} #{prop}\n"
end | ruby | def property name, prop
return '' if EXCLUDE_PROPERTIES.include?(name.to_s) || prop.nil? || (prop.kind_of?(Array) && prop.empty?)
prop = prop.flatten.map{|p| "'#{p}'"}.join(', ') if prop.respond_to?(:flatten) && name.to_sym != :folders
prop = @paths.map{|f| "'#{f}'"}.join(',') if name.to_sym == :folders
prop = "'#{prop.exec_rule}'" if prop.instance_of?(Syntaxer::Runner::ExecRule) && !prop.exec_rule.nil?
prop = "Syntaxer::Runner.#{prop.language}" if prop.instance_of?(Syntaxer::Runner::ExecRule) && prop.exec_rule.nil?
' '*4 + "#{name.to_s} #{prop}\n"
end | [
"def",
"property",
"name",
",",
"prop",
"return",
"''",
"if",
"EXCLUDE_PROPERTIES",
".",
"include?",
"(",
"name",
".",
"to_s",
")",
"||",
"prop",
".",
"nil?",
"||",
"(",
"prop",
".",
"kind_of?",
"(",
"Array",
")",
"&&",
"prop",
".",
"empty?",
")",
"prop",
"=",
"prop",
".",
"flatten",
".",
"map",
"{",
"|",
"p",
"|",
"\"'#{p}'\"",
"}",
".",
"join",
"(",
"', '",
")",
"if",
"prop",
".",
"respond_to?",
"(",
":flatten",
")",
"&&",
"name",
".",
"to_sym",
"!=",
":folders",
"prop",
"=",
"@paths",
".",
"map",
"{",
"|",
"f",
"|",
"\"'#{f}'\"",
"}",
".",
"join",
"(",
"','",
")",
"if",
"name",
".",
"to_sym",
"==",
":folders",
"prop",
"=",
"\"'#{prop.exec_rule}'\"",
"if",
"prop",
".",
"instance_of?",
"(",
"Syntaxer",
"::",
"Runner",
"::",
"ExecRule",
")",
"&&",
"!",
"prop",
".",
"exec_rule",
".",
"nil?",
"prop",
"=",
"\"Syntaxer::Runner.#{prop.language}\"",
"if",
"prop",
".",
"instance_of?",
"(",
"Syntaxer",
"::",
"Runner",
"::",
"ExecRule",
")",
"&&",
"prop",
".",
"exec_rule",
".",
"nil?",
"' '",
"*",
"4",
"+",
"\"#{name.to_s} #{prop}\\n\"",
"end"
] | Create DSL property of block
@param [String] name of the property
@param [Syntaxer::Runner, Array] properties
@return [String] DSL property string | [
"Create",
"DSL",
"property",
"of",
"block"
] | 7557318e9ab1554b38cb8df9d00f2ff4acc701cb | https://github.com/artemk/syntaxer/blob/7557318e9ab1554b38cb8df9d00f2ff4acc701cb/lib/syntaxer/writer.rb#L75-L85 | train |
rightscale/scheduled_job | lib/scheduled_job.rb | ScheduledJob.ScheduledJobClassMethods.schedule_job | def schedule_job(job = nil)
if can_schedule_job?(job)
callback = ScheduledJob.config.fast_mode
in_fast_mode = callback ? callback.call(self) : false
run_at = in_fast_mode ? Time.now.utc + 1 : time_to_recur(Time.now.utc)
Delayed::Job.enqueue(new, :run_at => run_at, :queue => queue_name)
end
end | ruby | def schedule_job(job = nil)
if can_schedule_job?(job)
callback = ScheduledJob.config.fast_mode
in_fast_mode = callback ? callback.call(self) : false
run_at = in_fast_mode ? Time.now.utc + 1 : time_to_recur(Time.now.utc)
Delayed::Job.enqueue(new, :run_at => run_at, :queue => queue_name)
end
end | [
"def",
"schedule_job",
"(",
"job",
"=",
"nil",
")",
"if",
"can_schedule_job?",
"(",
"job",
")",
"callback",
"=",
"ScheduledJob",
".",
"config",
".",
"fast_mode",
"in_fast_mode",
"=",
"callback",
"?",
"callback",
".",
"call",
"(",
"self",
")",
":",
"false",
"run_at",
"=",
"in_fast_mode",
"?",
"Time",
".",
"now",
".",
"utc",
"+",
"1",
":",
"time_to_recur",
"(",
"Time",
".",
"now",
".",
"utc",
")",
"Delayed",
"::",
"Job",
".",
"enqueue",
"(",
"new",
",",
":run_at",
"=>",
"run_at",
",",
":queue",
"=>",
"queue_name",
")",
"end",
"end"
] | This method should be called when scheduling a recurring job as it checks to ensure no
other instances of the job are already running. | [
"This",
"method",
"should",
"be",
"called",
"when",
"scheduling",
"a",
"recurring",
"job",
"as",
"it",
"checks",
"to",
"ensure",
"no",
"other",
"instances",
"of",
"the",
"job",
"are",
"already",
"running",
"."
] | 9e41d330eb636c03a8239d76e19e336492db7e87 | https://github.com/rightscale/scheduled_job/blob/9e41d330eb636c03a8239d76e19e336492db7e87/lib/scheduled_job.rb#L83-L92 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.