id
int32 0
24.9k
| repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
sequence | docstring
stringlengths 8
16k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 94
266
|
---|---|---|---|---|---|---|---|---|---|---|---|
600 | pengwynn/topsy | lib/topsy/client.rb | Topsy.Client.related | def related(url, options={})
response = handle_response(get("/related.json", :query => {:url => url}.merge(options)))
Topsy::Page.new(response,Topsy::LinkSearchResult)
end | ruby | def related(url, options={})
response = handle_response(get("/related.json", :query => {:url => url}.merge(options)))
Topsy::Page.new(response,Topsy::LinkSearchResult)
end | [
"def",
"related",
"(",
"url",
",",
"options",
"=",
"{",
"}",
")",
"response",
"=",
"handle_response",
"(",
"get",
"(",
"\"/related.json\"",
",",
":query",
"=>",
"{",
":url",
"=>",
"url",
"}",
".",
"merge",
"(",
"options",
")",
")",
")",
"Topsy",
"::",
"Page",
".",
"new",
"(",
"response",
",",
"Topsy",
"::",
"LinkSearchResult",
")",
"end"
] | Returns list of URLs related to a given URL
@param [String] url URL string for the author.
@param [Hash] options method options
@option options [Integer] :page page number of the result set. (default: 1, max: 10)
@option options [Integer] :perpage limit number of results per page. (default: 10, max: 50)
@return [Topsy::Page] | [
"Returns",
"list",
"of",
"URLs",
"related",
"to",
"a",
"given",
"URL"
] | 20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170 | https://github.com/pengwynn/topsy/blob/20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170/lib/topsy/client.rb#L89-L92 |
601 | pengwynn/topsy | lib/topsy/client.rb | Topsy.Client.search | def search(q, options={})
if q.is_a?(Hash)
options = q
q = "site:#{options.delete(:site)}" if options[:site]
else
q += " site:#{options.delete(:site)}" if options[:site]
end
options = set_window_or_default(options)
results = handle_response(get("/search.json", :query => {:q => q}.merge(options)))
Topsy::Page.new(results,Topsy::LinkSearchResult)
end | ruby | def search(q, options={})
if q.is_a?(Hash)
options = q
q = "site:#{options.delete(:site)}" if options[:site]
else
q += " site:#{options.delete(:site)}" if options[:site]
end
options = set_window_or_default(options)
results = handle_response(get("/search.json", :query => {:q => q}.merge(options)))
Topsy::Page.new(results,Topsy::LinkSearchResult)
end | [
"def",
"search",
"(",
"q",
",",
"options",
"=",
"{",
"}",
")",
"if",
"q",
".",
"is_a?",
"(",
"Hash",
")",
"options",
"=",
"q",
"q",
"=",
"\"site:#{options.delete(:site)}\"",
"if",
"options",
"[",
":site",
"]",
"else",
"q",
"+=",
"\" site:#{options.delete(:site)}\"",
"if",
"options",
"[",
":site",
"]",
"end",
"options",
"=",
"set_window_or_default",
"(",
"options",
")",
"results",
"=",
"handle_response",
"(",
"get",
"(",
"\"/search.json\"",
",",
":query",
"=>",
"{",
":q",
"=>",
"q",
"}",
".",
"merge",
"(",
"options",
")",
")",
")",
"Topsy",
"::",
"Page",
".",
"new",
"(",
"results",
",",
"Topsy",
"::",
"LinkSearchResult",
")",
"end"
] | Returns list of results for a query.
@param [String] q the search query string
@param [Hash] options method options
@option options [Symbol] :window Time window for results. (default: :all) Options: :dynamic most relevant, :hour last hour, :day last day, :week last week, :month last month, :all all time. You can also use the h6 (6 hours) d3 (3 days) syntax.
@option options [Integer] :page page number of the result set. (default: 1, max: 10)
@option options [Integer] :perpage limit number of results per page. (default: 10, max: 50)
@option options [String] :site narrow results to a domain
@return [Topsy::Page] | [
"Returns",
"list",
"of",
"results",
"for",
"a",
"query",
"."
] | 20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170 | https://github.com/pengwynn/topsy/blob/20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170/lib/topsy/client.rb#L103-L113 |
602 | pengwynn/topsy | lib/topsy/client.rb | Topsy.Client.search_count | def search_count(q)
counts = handle_response(get("/searchcount.json", :query => {:q => q}))
Topsy::SearchCounts.new(counts)
end | ruby | def search_count(q)
counts = handle_response(get("/searchcount.json", :query => {:q => q}))
Topsy::SearchCounts.new(counts)
end | [
"def",
"search_count",
"(",
"q",
")",
"counts",
"=",
"handle_response",
"(",
"get",
"(",
"\"/searchcount.json\"",
",",
":query",
"=>",
"{",
":q",
"=>",
"q",
"}",
")",
")",
"Topsy",
"::",
"SearchCounts",
".",
"new",
"(",
"counts",
")",
"end"
] | Returns count of results for a search query.
@param [String] q the search query string
@return [Topsy::SearchCounts] | [
"Returns",
"count",
"of",
"results",
"for",
"a",
"search",
"query",
"."
] | 20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170 | https://github.com/pengwynn/topsy/blob/20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170/lib/topsy/client.rb#L119-L122 |
603 | pengwynn/topsy | lib/topsy/client.rb | Topsy.Client.search_histogram | def search_histogram( q , count_method = 'target' , slice = 86400 , period = 30 )
response = handle_response(get("/searchhistogram.json" , :query => { :q => q , :slice => slice , :period => period , :count_method => count_method } ))
Topsy::SearchHistogram.new(response)
end | ruby | def search_histogram( q , count_method = 'target' , slice = 86400 , period = 30 )
response = handle_response(get("/searchhistogram.json" , :query => { :q => q , :slice => slice , :period => period , :count_method => count_method } ))
Topsy::SearchHistogram.new(response)
end | [
"def",
"search_histogram",
"(",
"q",
",",
"count_method",
"=",
"'target'",
",",
"slice",
"=",
"86400",
",",
"period",
"=",
"30",
")",
"response",
"=",
"handle_response",
"(",
"get",
"(",
"\"/searchhistogram.json\"",
",",
":query",
"=>",
"{",
":q",
"=>",
"q",
",",
":slice",
"=>",
"slice",
",",
":period",
"=>",
"period",
",",
":count_method",
"=>",
"count_method",
"}",
")",
")",
"Topsy",
"::",
"SearchHistogram",
".",
"new",
"(",
"response",
")",
"end"
] | Returns mention count data for the given query
@param [String] q - The query. Use site:domain.com to get domain counts and @username to get mention counts.
@param [String] count_method - what is being counted - "target" (default) - the number of unique links , or "citation" - cthe number of unique tweets about links
@param [Integer] slice -
@param [Integer] period - | [
"Returns",
"mention",
"count",
"data",
"for",
"the",
"given",
"query"
] | 20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170 | https://github.com/pengwynn/topsy/blob/20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170/lib/topsy/client.rb#L131-L134 |
604 | pengwynn/topsy | lib/topsy/client.rb | Topsy.Client.stats | def stats(url, options={})
query = {:url => url}
query.merge!(options)
response = handle_response(get("/stats.json", :query => query))
Topsy::Stats.new(response)
end | ruby | def stats(url, options={})
query = {:url => url}
query.merge!(options)
response = handle_response(get("/stats.json", :query => query))
Topsy::Stats.new(response)
end | [
"def",
"stats",
"(",
"url",
",",
"options",
"=",
"{",
"}",
")",
"query",
"=",
"{",
":url",
"=>",
"url",
"}",
"query",
".",
"merge!",
"(",
"options",
")",
"response",
"=",
"handle_response",
"(",
"get",
"(",
"\"/stats.json\"",
",",
":query",
"=>",
"query",
")",
")",
"Topsy",
"::",
"Stats",
".",
"new",
"(",
"response",
")",
"end"
] | Returns counts of tweets for a URL
@param [String] url the url to look up
@param [Hash] options method options
@option options [String] :contains Query string to filter results
@return [Topsy::Stats] | [
"Returns",
"counts",
"of",
"tweets",
"for",
"a",
"URL"
] | 20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170 | https://github.com/pengwynn/topsy/blob/20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170/lib/topsy/client.rb#L142-L147 |
605 | pengwynn/topsy | lib/topsy/client.rb | Topsy.Client.tags | def tags(url, options={})
response = handle_response(get("/tags.json", :query => {:url => url}.merge(options)))
Topsy::Page.new(response,Topsy::Tag)
end | ruby | def tags(url, options={})
response = handle_response(get("/tags.json", :query => {:url => url}.merge(options)))
Topsy::Page.new(response,Topsy::Tag)
end | [
"def",
"tags",
"(",
"url",
",",
"options",
"=",
"{",
"}",
")",
"response",
"=",
"handle_response",
"(",
"get",
"(",
"\"/tags.json\"",
",",
":query",
"=>",
"{",
":url",
"=>",
"url",
"}",
".",
"merge",
"(",
"options",
")",
")",
")",
"Topsy",
"::",
"Page",
".",
"new",
"(",
"response",
",",
"Topsy",
"::",
"Tag",
")",
"end"
] | Returns list of tags for a URL.
@param [String] url the search query string
@param [Hash] options method options
@option options [Integer] :page page number of the result set. (default: 1, max: 10)
@option options [Integer] :perpage limit number of results per page. (default: 10, max: 50)
@return [Topsy::Page] | [
"Returns",
"list",
"of",
"tags",
"for",
"a",
"URL",
"."
] | 20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170 | https://github.com/pengwynn/topsy/blob/20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170/lib/topsy/client.rb#L156-L159 |
606 | pengwynn/topsy | lib/topsy/client.rb | Topsy.Client.trending | def trending(options={})
response = handle_response(get("/trending.json", :query => options))
Topsy::Page.new(response,Topsy::Trend)
end | ruby | def trending(options={})
response = handle_response(get("/trending.json", :query => options))
Topsy::Page.new(response,Topsy::Trend)
end | [
"def",
"trending",
"(",
"options",
"=",
"{",
"}",
")",
"response",
"=",
"handle_response",
"(",
"get",
"(",
"\"/trending.json\"",
",",
":query",
"=>",
"options",
")",
")",
"Topsy",
"::",
"Page",
".",
"new",
"(",
"response",
",",
"Topsy",
"::",
"Trend",
")",
"end"
] | Returns list of trending terms
@param [Hash] options method options
@option options [Integer] :page page number of the result set. (default: 1, max: 10)
@option options [Integer] :perpage limit number of results per page. (default: 10, max: 50)
@return [Topsy::Page] | [
"Returns",
"list",
"of",
"trending",
"terms"
] | 20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170 | https://github.com/pengwynn/topsy/blob/20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170/lib/topsy/client.rb#L184-L187 |
607 | pengwynn/topsy | lib/topsy/client.rb | Topsy.Client.url_info | def url_info(url)
response = handle_response(get("/urlinfo.json", :query => {:url => url}))
Topsy::UrlInfo.new(response)
end | ruby | def url_info(url)
response = handle_response(get("/urlinfo.json", :query => {:url => url}))
Topsy::UrlInfo.new(response)
end | [
"def",
"url_info",
"(",
"url",
")",
"response",
"=",
"handle_response",
"(",
"get",
"(",
"\"/urlinfo.json\"",
",",
":query",
"=>",
"{",
":url",
"=>",
"url",
"}",
")",
")",
"Topsy",
"::",
"UrlInfo",
".",
"new",
"(",
"response",
")",
"end"
] | Returns info about a URL
@param [String] url the url to look up
@return [Topsy::UrlInfo] | [
"Returns",
"info",
"about",
"a",
"URL"
] | 20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170 | https://github.com/pengwynn/topsy/blob/20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170/lib/topsy/client.rb#L193-L196 |
608 | pengwynn/topsy | lib/topsy/client.rb | Topsy.Client.extract_header_value | def extract_header_value(response, key)
response.headers[key].class == Array ? response.headers[key].first.to_i : response.headers[key].to_i
end | ruby | def extract_header_value(response, key)
response.headers[key].class == Array ? response.headers[key].first.to_i : response.headers[key].to_i
end | [
"def",
"extract_header_value",
"(",
"response",
",",
"key",
")",
"response",
".",
"headers",
"[",
"key",
"]",
".",
"class",
"==",
"Array",
"?",
"response",
".",
"headers",
"[",
"key",
"]",
".",
"first",
".",
"to_i",
":",
"response",
".",
"headers",
"[",
"key",
"]",
".",
"to_i",
"end"
] | extracts the header key | [
"extracts",
"the",
"header",
"key"
] | 20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170 | https://github.com/pengwynn/topsy/blob/20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170/lib/topsy/client.rb#L232-L234 |
609 | rightscale/right_agent | lib/right_agent/clients/non_blocking_client.rb | RightScale.NonBlockingClient.poll_again | def poll_again(fiber, connection, request_options, stop_at)
http = connection.send(:get, request_options)
http.errback { fiber.resume(*handle_error("POLL", http.error)) }
http.callback do
code, body, headers = http.response_header.status, http.response, http.response_header
if code == 200 && (body.nil? || body == "null") && Time.now < stop_at
poll_again(fiber, connection, request_options, stop_at)
else
fiber.resume(code, body, headers)
end
end
true
end | ruby | def poll_again(fiber, connection, request_options, stop_at)
http = connection.send(:get, request_options)
http.errback { fiber.resume(*handle_error("POLL", http.error)) }
http.callback do
code, body, headers = http.response_header.status, http.response, http.response_header
if code == 200 && (body.nil? || body == "null") && Time.now < stop_at
poll_again(fiber, connection, request_options, stop_at)
else
fiber.resume(code, body, headers)
end
end
true
end | [
"def",
"poll_again",
"(",
"fiber",
",",
"connection",
",",
"request_options",
",",
"stop_at",
")",
"http",
"=",
"connection",
".",
"send",
"(",
":get",
",",
"request_options",
")",
"http",
".",
"errback",
"{",
"fiber",
".",
"resume",
"(",
"handle_error",
"(",
"\"POLL\"",
",",
"http",
".",
"error",
")",
")",
"}",
"http",
".",
"callback",
"do",
"code",
",",
"body",
",",
"headers",
"=",
"http",
".",
"response_header",
".",
"status",
",",
"http",
".",
"response",
",",
"http",
".",
"response_header",
"if",
"code",
"==",
"200",
"&&",
"(",
"body",
".",
"nil?",
"||",
"body",
"==",
"\"null\"",
")",
"&&",
"Time",
".",
"now",
"<",
"stop_at",
"poll_again",
"(",
"fiber",
",",
"connection",
",",
"request_options",
",",
"stop_at",
")",
"else",
"fiber",
".",
"resume",
"(",
"code",
",",
"body",
",",
"headers",
")",
"end",
"end",
"true",
"end"
] | Repeatedly make long-polling request until receive data, hit error, or timeout
Treat "terminating" and "reconnecting" errors as an empty poll result
@param [Symbol] verb for HTTP REST request
@param [EM:HttpRequest] connection to server from previous request
@param [Hash] request_options for HTTP request
@param [Time] stop_at time for polling
@return [TrueClass] always true
@raise [HttpException] HTTP failure with associated status code | [
"Repeatedly",
"make",
"long",
"-",
"polling",
"request",
"until",
"receive",
"data",
"hit",
"error",
"or",
"timeout",
"Treat",
"terminating",
"and",
"reconnecting",
"errors",
"as",
"an",
"empty",
"poll",
"result"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/non_blocking_client.rb#L184-L196 |
610 | rightscale/right_agent | lib/right_agent/clients/non_blocking_client.rb | RightScale.NonBlockingClient.beautify_headers | def beautify_headers(headers)
headers.inject({}) { |out, (key, value)| out[key.gsub(/-/, '_').downcase.to_sym] = value; out }
end | ruby | def beautify_headers(headers)
headers.inject({}) { |out, (key, value)| out[key.gsub(/-/, '_').downcase.to_sym] = value; out }
end | [
"def",
"beautify_headers",
"(",
"headers",
")",
"headers",
".",
"inject",
"(",
"{",
"}",
")",
"{",
"|",
"out",
",",
"(",
"key",
",",
"value",
")",
"|",
"out",
"[",
"key",
".",
"gsub",
"(",
"/",
"/",
",",
"'_'",
")",
".",
"downcase",
".",
"to_sym",
"]",
"=",
"value",
";",
"out",
"}",
"end"
] | Beautify response header keys so that in same form as RestClient
@param [Hash] headers from response
@return [Hash] response headers with keys as lower case symbols | [
"Beautify",
"response",
"header",
"keys",
"so",
"that",
"in",
"same",
"form",
"as",
"RestClient"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/non_blocking_client.rb#L218-L220 |
611 | rightscale/right_agent | lib/right_agent/agent_tag_manager.rb | RightScale.AgentTagManager.tags | def tags(options = {})
# TODO remove use of agent identity when fully drop AMQP
do_query(nil, @agent.mode == :http ? @agent.self_href : @agent.identity, options) do |result|
if result.kind_of?(Hash)
yield(result.size == 1 ? result.values.first['tags'] : [])
else
yield result
end
end
end | ruby | def tags(options = {})
# TODO remove use of agent identity when fully drop AMQP
do_query(nil, @agent.mode == :http ? @agent.self_href : @agent.identity, options) do |result|
if result.kind_of?(Hash)
yield(result.size == 1 ? result.values.first['tags'] : [])
else
yield result
end
end
end | [
"def",
"tags",
"(",
"options",
"=",
"{",
"}",
")",
"# TODO remove use of agent identity when fully drop AMQP",
"do_query",
"(",
"nil",
",",
"@agent",
".",
"mode",
"==",
":http",
"?",
"@agent",
".",
"self_href",
":",
"@agent",
".",
"identity",
",",
"options",
")",
"do",
"|",
"result",
"|",
"if",
"result",
".",
"kind_of?",
"(",
"Hash",
")",
"yield",
"(",
"result",
".",
"size",
"==",
"1",
"?",
"result",
".",
"values",
".",
"first",
"[",
"'tags'",
"]",
":",
"[",
"]",
")",
"else",
"yield",
"result",
"end",
"end",
"end"
] | Retrieve current agent tags and give result to block
=== Parameters
options(Hash):: Request options
:raw(Boolean):: true to yield raw tag response instead of deserialized tags
:timeout(Integer):: timeout in seconds before giving up and yielding an error message
=== Block
Given block should take one argument which will be set with an array
initialized with the tags of this instance
=== Return
true:: Always return true | [
"Retrieve",
"current",
"agent",
"tags",
"and",
"give",
"result",
"to",
"block"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/agent_tag_manager.rb#L46-L55 |
612 | rightscale/right_agent | lib/right_agent/agent_tag_manager.rb | RightScale.AgentTagManager.query_tags | def query_tags(tags, options = {})
tags = ensure_flat_array_value(tags) unless tags.nil? || tags.empty?
do_query(tags, nil, options) { |result| yield result }
end | ruby | def query_tags(tags, options = {})
tags = ensure_flat_array_value(tags) unless tags.nil? || tags.empty?
do_query(tags, nil, options) { |result| yield result }
end | [
"def",
"query_tags",
"(",
"tags",
",",
"options",
"=",
"{",
"}",
")",
"tags",
"=",
"ensure_flat_array_value",
"(",
"tags",
")",
"unless",
"tags",
".",
"nil?",
"||",
"tags",
".",
"empty?",
"do_query",
"(",
"tags",
",",
"nil",
",",
"options",
")",
"{",
"|",
"result",
"|",
"yield",
"result",
"}",
"end"
] | Queries a list of servers in the current deployment which have one or more
of the given tags.
=== Parameters
tags(String, Array):: Tag or tags to query or empty
options(Hash):: Request options
:raw(Boolean):: true to yield raw tag response instead of deserialized tags
:timeout(Integer):: timeout in seconds before giving up and yielding an error message
=== Block
Given block should take one argument which will be set with an array
initialized with the tags of this instance
=== Return
true:: Always return true | [
"Queries",
"a",
"list",
"of",
"servers",
"in",
"the",
"current",
"deployment",
"which",
"have",
"one",
"or",
"more",
"of",
"the",
"given",
"tags",
"."
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/agent_tag_manager.rb#L72-L75 |
613 | rightscale/right_agent | lib/right_agent/agent_tag_manager.rb | RightScale.AgentTagManager.add_tags | def add_tags(new_tags, options = {})
new_tags = ensure_flat_array_value(new_tags) unless new_tags.nil? || new_tags.empty?
do_update(new_tags, [], options) { |raw_response| yield raw_response if block_given? }
end | ruby | def add_tags(new_tags, options = {})
new_tags = ensure_flat_array_value(new_tags) unless new_tags.nil? || new_tags.empty?
do_update(new_tags, [], options) { |raw_response| yield raw_response if block_given? }
end | [
"def",
"add_tags",
"(",
"new_tags",
",",
"options",
"=",
"{",
"}",
")",
"new_tags",
"=",
"ensure_flat_array_value",
"(",
"new_tags",
")",
"unless",
"new_tags",
".",
"nil?",
"||",
"new_tags",
".",
"empty?",
"do_update",
"(",
"new_tags",
",",
"[",
"]",
",",
"options",
")",
"{",
"|",
"raw_response",
"|",
"yield",
"raw_response",
"if",
"block_given?",
"}",
"end"
] | Add given tags to agent
=== Parameters
new_tags(String, Array):: Tag or tags to be added
options(Hash):: Request options
:timeout(Integer):: timeout in seconds before giving up and yielding an error message
=== Block
A block is optional. If provided, should take one argument which will be set with the
raw response
=== Return
true always return true | [
"Add",
"given",
"tags",
"to",
"agent"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/agent_tag_manager.rb#L110-L113 |
614 | rightscale/right_agent | lib/right_agent/agent_tag_manager.rb | RightScale.AgentTagManager.remove_tags | def remove_tags(old_tags, options = {})
old_tags = ensure_flat_array_value(old_tags) unless old_tags.nil? || old_tags.empty?
do_update([], old_tags, options) { |raw_response| yield raw_response if block_given? }
end | ruby | def remove_tags(old_tags, options = {})
old_tags = ensure_flat_array_value(old_tags) unless old_tags.nil? || old_tags.empty?
do_update([], old_tags, options) { |raw_response| yield raw_response if block_given? }
end | [
"def",
"remove_tags",
"(",
"old_tags",
",",
"options",
"=",
"{",
"}",
")",
"old_tags",
"=",
"ensure_flat_array_value",
"(",
"old_tags",
")",
"unless",
"old_tags",
".",
"nil?",
"||",
"old_tags",
".",
"empty?",
"do_update",
"(",
"[",
"]",
",",
"old_tags",
",",
"options",
")",
"{",
"|",
"raw_response",
"|",
"yield",
"raw_response",
"if",
"block_given?",
"}",
"end"
] | Remove given tags from agent
=== Parameters
old_tags(String, Array):: Tag or tags to be removed
options(Hash):: Request options
:timeout(Integer):: timeout in seconds before giving up and yielding an error message
=== Block
A block is optional. If provided, should take one argument which will be set with the
raw response
=== Return
true always return true | [
"Remove",
"given",
"tags",
"from",
"agent"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/agent_tag_manager.rb#L128-L131 |
615 | rightscale/right_agent | lib/right_agent/agent_tag_manager.rb | RightScale.AgentTagManager.do_query | def do_query(tags = nil, hrefs = nil, options = {})
raw = options[:raw]
timeout = options[:timeout]
request_options = {}
request_options[:timeout] = timeout if timeout
agent_check
payload = {:agent_identity => @agent.identity}
payload[:tags] = ensure_flat_array_value(tags) unless tags.nil? || tags.empty?
# TODO remove use of agent identity when fully drop AMQP
if @agent.mode == :http
payload[:hrefs] = ensure_flat_array_value(hrefs) unless hrefs.nil? || hrefs.empty?
else
payload[:agent_ids] = ensure_flat_array_value(hrefs) unless hrefs.nil? || hrefs.empty?
end
request = RightScale::RetryableRequest.new("/router/query_tags", payload, request_options)
request.callback { |result| yield raw ? request.raw_response : result }
request.errback do |message|
ErrorTracker.log(self, "Failed to query tags (#{message})")
yield((raw ? request.raw_response : nil) || message)
end
request.run
true
end | ruby | def do_query(tags = nil, hrefs = nil, options = {})
raw = options[:raw]
timeout = options[:timeout]
request_options = {}
request_options[:timeout] = timeout if timeout
agent_check
payload = {:agent_identity => @agent.identity}
payload[:tags] = ensure_flat_array_value(tags) unless tags.nil? || tags.empty?
# TODO remove use of agent identity when fully drop AMQP
if @agent.mode == :http
payload[:hrefs] = ensure_flat_array_value(hrefs) unless hrefs.nil? || hrefs.empty?
else
payload[:agent_ids] = ensure_flat_array_value(hrefs) unless hrefs.nil? || hrefs.empty?
end
request = RightScale::RetryableRequest.new("/router/query_tags", payload, request_options)
request.callback { |result| yield raw ? request.raw_response : result }
request.errback do |message|
ErrorTracker.log(self, "Failed to query tags (#{message})")
yield((raw ? request.raw_response : nil) || message)
end
request.run
true
end | [
"def",
"do_query",
"(",
"tags",
"=",
"nil",
",",
"hrefs",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
")",
"raw",
"=",
"options",
"[",
":raw",
"]",
"timeout",
"=",
"options",
"[",
":timeout",
"]",
"request_options",
"=",
"{",
"}",
"request_options",
"[",
":timeout",
"]",
"=",
"timeout",
"if",
"timeout",
"agent_check",
"payload",
"=",
"{",
":agent_identity",
"=>",
"@agent",
".",
"identity",
"}",
"payload",
"[",
":tags",
"]",
"=",
"ensure_flat_array_value",
"(",
"tags",
")",
"unless",
"tags",
".",
"nil?",
"||",
"tags",
".",
"empty?",
"# TODO remove use of agent identity when fully drop AMQP",
"if",
"@agent",
".",
"mode",
"==",
":http",
"payload",
"[",
":hrefs",
"]",
"=",
"ensure_flat_array_value",
"(",
"hrefs",
")",
"unless",
"hrefs",
".",
"nil?",
"||",
"hrefs",
".",
"empty?",
"else",
"payload",
"[",
":agent_ids",
"]",
"=",
"ensure_flat_array_value",
"(",
"hrefs",
")",
"unless",
"hrefs",
".",
"nil?",
"||",
"hrefs",
".",
"empty?",
"end",
"request",
"=",
"RightScale",
"::",
"RetryableRequest",
".",
"new",
"(",
"\"/router/query_tags\"",
",",
"payload",
",",
"request_options",
")",
"request",
".",
"callback",
"{",
"|",
"result",
"|",
"yield",
"raw",
"?",
"request",
".",
"raw_response",
":",
"result",
"}",
"request",
".",
"errback",
"do",
"|",
"message",
"|",
"ErrorTracker",
".",
"log",
"(",
"self",
",",
"\"Failed to query tags (#{message})\"",
")",
"yield",
"(",
"(",
"raw",
"?",
"request",
".",
"raw_response",
":",
"nil",
")",
"||",
"message",
")",
"end",
"request",
".",
"run",
"true",
"end"
] | Runs a tag query with an optional list of tags.
=== Parameters
tags(Array):: Tags to query or empty or nil
hrefs(Array):: hrefs of resources to query with empty or nil meaning all instances in deployment
options(Hash):: Request options
:raw(Boolean):: true to yield raw tag response instead of unserialized tags
:timeout(Integer):: timeout in seconds before giving up and yielding an error message
=== Block
Given block should take one argument which will be set with an array
initialized with the tags of this instance
=== Return
true:: Always return true | [
"Runs",
"a",
"tag",
"query",
"with",
"an",
"optional",
"list",
"of",
"tags",
"."
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/agent_tag_manager.rb#L169-L193 |
616 | rightscale/right_agent | lib/right_agent/agent_tag_manager.rb | RightScale.AgentTagManager.do_update | def do_update(new_tags, old_tags, options = {}, &block)
agent_check
raise ArgumentError.new("Cannot add and remove tags in same update") if new_tags.any? && old_tags.any?
tags = @agent.tags
tags += new_tags
tags -= old_tags
tags.uniq!
if new_tags.any?
request = RightScale::RetryableRequest.new("/router/add_tags", {:tags => new_tags}, options)
elsif old_tags.any?
request = RightScale::RetryableRequest.new("/router/delete_tags", {:tags => old_tags}, options)
else
return
end
if block
# Always yield raw response
request.callback do |_|
# Refresh agent's copy of tags on successful update
@agent.tags = tags
block.call(request.raw_response)
end
request.errback { |message| block.call(request.raw_response || message) }
end
request.run
true
end | ruby | def do_update(new_tags, old_tags, options = {}, &block)
agent_check
raise ArgumentError.new("Cannot add and remove tags in same update") if new_tags.any? && old_tags.any?
tags = @agent.tags
tags += new_tags
tags -= old_tags
tags.uniq!
if new_tags.any?
request = RightScale::RetryableRequest.new("/router/add_tags", {:tags => new_tags}, options)
elsif old_tags.any?
request = RightScale::RetryableRequest.new("/router/delete_tags", {:tags => old_tags}, options)
else
return
end
if block
# Always yield raw response
request.callback do |_|
# Refresh agent's copy of tags on successful update
@agent.tags = tags
block.call(request.raw_response)
end
request.errback { |message| block.call(request.raw_response || message) }
end
request.run
true
end | [
"def",
"do_update",
"(",
"new_tags",
",",
"old_tags",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"agent_check",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"Cannot add and remove tags in same update\"",
")",
"if",
"new_tags",
".",
"any?",
"&&",
"old_tags",
".",
"any?",
"tags",
"=",
"@agent",
".",
"tags",
"tags",
"+=",
"new_tags",
"tags",
"-=",
"old_tags",
"tags",
".",
"uniq!",
"if",
"new_tags",
".",
"any?",
"request",
"=",
"RightScale",
"::",
"RetryableRequest",
".",
"new",
"(",
"\"/router/add_tags\"",
",",
"{",
":tags",
"=>",
"new_tags",
"}",
",",
"options",
")",
"elsif",
"old_tags",
".",
"any?",
"request",
"=",
"RightScale",
"::",
"RetryableRequest",
".",
"new",
"(",
"\"/router/delete_tags\"",
",",
"{",
":tags",
"=>",
"old_tags",
"}",
",",
"options",
")",
"else",
"return",
"end",
"if",
"block",
"# Always yield raw response",
"request",
".",
"callback",
"do",
"|",
"_",
"|",
"# Refresh agent's copy of tags on successful update",
"@agent",
".",
"tags",
"=",
"tags",
"block",
".",
"call",
"(",
"request",
".",
"raw_response",
")",
"end",
"request",
".",
"errback",
"{",
"|",
"message",
"|",
"block",
".",
"call",
"(",
"request",
".",
"raw_response",
"||",
"message",
")",
"}",
"end",
"request",
".",
"run",
"true",
"end"
] | Runs a tag update with a list of new or old tags
=== Parameters
new_tags(Array):: new tags to add or empty
old_tags(Array):: old tags to remove or empty
block(Block):: optional callback for update response
=== Block
A block is optional. If provided, should take one argument which will be set with the
raw response
=== Return
true:: Always return true | [
"Runs",
"a",
"tag",
"update",
"with",
"a",
"list",
"of",
"new",
"or",
"old",
"tags"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/agent_tag_manager.rb#L208-L235 |
617 | rightscale/right_agent | lib/right_agent/error_tracker.rb | RightScale.ErrorTracker.init | def init(agent, agent_name, options = {})
@agent = agent
@trace_level = options[:trace_level] || {}
notify_init(agent_name, options)
reset_stats
true
end | ruby | def init(agent, agent_name, options = {})
@agent = agent
@trace_level = options[:trace_level] || {}
notify_init(agent_name, options)
reset_stats
true
end | [
"def",
"init",
"(",
"agent",
",",
"agent_name",
",",
"options",
"=",
"{",
"}",
")",
"@agent",
"=",
"agent",
"@trace_level",
"=",
"options",
"[",
":trace_level",
"]",
"||",
"{",
"}",
"notify_init",
"(",
"agent_name",
",",
"options",
")",
"reset_stats",
"true",
"end"
] | Initialize error tracker
@param [Object] agent object using this tracker
@param [String] agent_name uniquely identifying agent process on given server
@option options [Integer, NilClass] :shard_id identifying shard of database in use
@option options [Hash] :trace_level for restricting backtracing and Errbit reporting
with exception class as key and :no_trace, :caller, or :trace as value; exceptions
with :no_trace are not backtraced when logging nor are they recorded in stats
or reported to Errbit
@option options [Array<Symbol, String>] :filter_params names whose values are to be
filtered when notifying
@option options [String] :airbrake_endpoint URL for Airbrake for reporting exceptions
to Errbit
@option options [String] :airbrake_api_key for using the Airbrake API to access Errbit
@return [TrueClass] always true | [
"Initialize",
"error",
"tracker"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/error_tracker.rb#L45-L51 |
618 | rightscale/right_agent | lib/right_agent/error_tracker.rb | RightScale.ErrorTracker.log | def log(component, description, exception = nil, packet = nil, trace = nil)
if exception.nil?
Log.error(description)
elsif exception.is_a?(String)
Log.error(description, exception)
else
trace = (@trace_level && @trace_level[exception.class]) || trace || :trace
Log.error(description, exception, trace)
track(component, exception, packet) if trace != :no_trace
end
true
rescue StandardError => e
Log.error("Failed to log error", e, :trace) rescue nil
false
end | ruby | def log(component, description, exception = nil, packet = nil, trace = nil)
if exception.nil?
Log.error(description)
elsif exception.is_a?(String)
Log.error(description, exception)
else
trace = (@trace_level && @trace_level[exception.class]) || trace || :trace
Log.error(description, exception, trace)
track(component, exception, packet) if trace != :no_trace
end
true
rescue StandardError => e
Log.error("Failed to log error", e, :trace) rescue nil
false
end | [
"def",
"log",
"(",
"component",
",",
"description",
",",
"exception",
"=",
"nil",
",",
"packet",
"=",
"nil",
",",
"trace",
"=",
"nil",
")",
"if",
"exception",
".",
"nil?",
"Log",
".",
"error",
"(",
"description",
")",
"elsif",
"exception",
".",
"is_a?",
"(",
"String",
")",
"Log",
".",
"error",
"(",
"description",
",",
"exception",
")",
"else",
"trace",
"=",
"(",
"@trace_level",
"&&",
"@trace_level",
"[",
"exception",
".",
"class",
"]",
")",
"||",
"trace",
"||",
":trace",
"Log",
".",
"error",
"(",
"description",
",",
"exception",
",",
"trace",
")",
"track",
"(",
"component",
",",
"exception",
",",
"packet",
")",
"if",
"trace",
"!=",
":no_trace",
"end",
"true",
"rescue",
"StandardError",
"=>",
"e",
"Log",
".",
"error",
"(",
"\"Failed to log error\"",
",",
"e",
",",
":trace",
")",
"rescue",
"nil",
"false",
"end"
] | Log error and optionally track in stats
Errbit notification is left to the callback configured in the stats tracker
Logging works even if init was never called
@param [String, Object] component reporting error; non-string is snake-cased
@param [String] description of failure for use in logging
@param [Exception, String] exception to be logged and tracked in stats;
string errors are logged but not tracked in stats
@param [Packet, Hash, NilClass] packet associated with exception
@param [Symbol, NilClass] trace level override unless excluded by configured
trace levels
@return [Boolean] true if successfully logged, otherwise false | [
"Log",
"error",
"and",
"optionally",
"track",
"in",
"stats",
"Errbit",
"notification",
"is",
"left",
"to",
"the",
"callback",
"configured",
"in",
"the",
"stats",
"tracker",
"Logging",
"works",
"even",
"if",
"init",
"was",
"never",
"called"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/error_tracker.rb#L66-L80 |
619 | rightscale/right_agent | lib/right_agent/error_tracker.rb | RightScale.ErrorTracker.track | def track(component, exception, packet = nil)
if @exception_stats
component = component.class.name.split("::").last.snake_case unless component.is_a?(String)
@exception_stats.track(component, exception, packet)
end
true
end | ruby | def track(component, exception, packet = nil)
if @exception_stats
component = component.class.name.split("::").last.snake_case unless component.is_a?(String)
@exception_stats.track(component, exception, packet)
end
true
end | [
"def",
"track",
"(",
"component",
",",
"exception",
",",
"packet",
"=",
"nil",
")",
"if",
"@exception_stats",
"component",
"=",
"component",
".",
"class",
".",
"name",
".",
"split",
"(",
"\"::\"",
")",
".",
"last",
".",
"snake_case",
"unless",
"component",
".",
"is_a?",
"(",
"String",
")",
"@exception_stats",
".",
"track",
"(",
"component",
",",
"exception",
",",
"packet",
")",
"end",
"true",
"end"
] | Track error in stats
@param [String] component reporting error
@param [Exception] exception to be tracked
@param [Packet, Hash, NilClass] packet associated with exception
@return [TrueClass] always true | [
"Track",
"error",
"in",
"stats"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/error_tracker.rb#L89-L95 |
620 | rightscale/right_agent | lib/right_agent/error_tracker.rb | RightScale.ErrorTracker.notify | def notify(exception, packet = nil, agent = nil, component = nil)
if @notify_enabled
if packet && packet.is_a?(Packet)
action = packet.type.split("/").last if packet.respond_to?(:type)
params = packet.respond_to?(:payload) && packet.payload
uuid = packet.respond_to?(:token) && packet.token
elsif packet.is_a?(Hash)
action_path = packet[:path] || packet["path"]
action = action_path.split("/").last if action_path
params = packet[:data] || packet["data"]
uuid = packet[:uuid] || packet["uuid"]
else
params = uuid = nil
end
component = component.class.name unless component.is_a?(String)
n = Airbrake.build_notice(
exception,
{ component: component, action: action },
:right_agent )
n[:params] = params.is_a?(Hash) ? filter(params) : {:param => params} if params
n[:session] = { :uuid => uuid } if uuid
if agent
n[:environment] = (@cgi_data || {}).merge(:agent_class => agent.class.name)
elsif @cgi_data
n[:environment] = @cgi_data || {}
end
Airbrake.notify(n, {}, :right_agent)
end
true
rescue Exception => e
raise if e.class.name =~ /^RSpec/ # keep us from going insane while running tests
Log.error("Failed to notify Errbit", e, :trace)
end | ruby | def notify(exception, packet = nil, agent = nil, component = nil)
if @notify_enabled
if packet && packet.is_a?(Packet)
action = packet.type.split("/").last if packet.respond_to?(:type)
params = packet.respond_to?(:payload) && packet.payload
uuid = packet.respond_to?(:token) && packet.token
elsif packet.is_a?(Hash)
action_path = packet[:path] || packet["path"]
action = action_path.split("/").last if action_path
params = packet[:data] || packet["data"]
uuid = packet[:uuid] || packet["uuid"]
else
params = uuid = nil
end
component = component.class.name unless component.is_a?(String)
n = Airbrake.build_notice(
exception,
{ component: component, action: action },
:right_agent )
n[:params] = params.is_a?(Hash) ? filter(params) : {:param => params} if params
n[:session] = { :uuid => uuid } if uuid
if agent
n[:environment] = (@cgi_data || {}).merge(:agent_class => agent.class.name)
elsif @cgi_data
n[:environment] = @cgi_data || {}
end
Airbrake.notify(n, {}, :right_agent)
end
true
rescue Exception => e
raise if e.class.name =~ /^RSpec/ # keep us from going insane while running tests
Log.error("Failed to notify Errbit", e, :trace)
end | [
"def",
"notify",
"(",
"exception",
",",
"packet",
"=",
"nil",
",",
"agent",
"=",
"nil",
",",
"component",
"=",
"nil",
")",
"if",
"@notify_enabled",
"if",
"packet",
"&&",
"packet",
".",
"is_a?",
"(",
"Packet",
")",
"action",
"=",
"packet",
".",
"type",
".",
"split",
"(",
"\"/\"",
")",
".",
"last",
"if",
"packet",
".",
"respond_to?",
"(",
":type",
")",
"params",
"=",
"packet",
".",
"respond_to?",
"(",
":payload",
")",
"&&",
"packet",
".",
"payload",
"uuid",
"=",
"packet",
".",
"respond_to?",
"(",
":token",
")",
"&&",
"packet",
".",
"token",
"elsif",
"packet",
".",
"is_a?",
"(",
"Hash",
")",
"action_path",
"=",
"packet",
"[",
":path",
"]",
"||",
"packet",
"[",
"\"path\"",
"]",
"action",
"=",
"action_path",
".",
"split",
"(",
"\"/\"",
")",
".",
"last",
"if",
"action_path",
"params",
"=",
"packet",
"[",
":data",
"]",
"||",
"packet",
"[",
"\"data\"",
"]",
"uuid",
"=",
"packet",
"[",
":uuid",
"]",
"||",
"packet",
"[",
"\"uuid\"",
"]",
"else",
"params",
"=",
"uuid",
"=",
"nil",
"end",
"component",
"=",
"component",
".",
"class",
".",
"name",
"unless",
"component",
".",
"is_a?",
"(",
"String",
")",
"n",
"=",
"Airbrake",
".",
"build_notice",
"(",
"exception",
",",
"{",
"component",
":",
"component",
",",
"action",
":",
"action",
"}",
",",
":right_agent",
")",
"n",
"[",
":params",
"]",
"=",
"params",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"filter",
"(",
"params",
")",
":",
"{",
":param",
"=>",
"params",
"}",
"if",
"params",
"n",
"[",
":session",
"]",
"=",
"{",
":uuid",
"=>",
"uuid",
"}",
"if",
"uuid",
"if",
"agent",
"n",
"[",
":environment",
"]",
"=",
"(",
"@cgi_data",
"||",
"{",
"}",
")",
".",
"merge",
"(",
":agent_class",
"=>",
"agent",
".",
"class",
".",
"name",
")",
"elsif",
"@cgi_data",
"n",
"[",
":environment",
"]",
"=",
"@cgi_data",
"||",
"{",
"}",
"end",
"Airbrake",
".",
"notify",
"(",
"n",
",",
"{",
"}",
",",
":right_agent",
")",
"end",
"true",
"rescue",
"Exception",
"=>",
"e",
"raise",
"if",
"e",
".",
"class",
".",
"name",
"=~",
"/",
"/",
"# keep us from going insane while running tests",
"Log",
".",
"error",
"(",
"\"Failed to notify Errbit\"",
",",
"e",
",",
":trace",
")",
"end"
] | Notify Errbit of error if notification enabled
@param [Exception, String] exception raised
@param [Packet, Hash] packet associated with exception
@param [Object] agent object reporting error
@param [String,Object] component or service area where error occurred
@return [TrueClass] always true | [
"Notify",
"Errbit",
"of",
"error",
"if",
"notification",
"enabled"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/error_tracker.rb#L105-L142 |
621 | rightscale/right_agent | lib/right_agent/error_tracker.rb | RightScale.ErrorTracker.notify_callback | def notify_callback
Proc.new do |exception, packet, agent, component|
notify(exception, packet, agent, component)
end
end | ruby | def notify_callback
Proc.new do |exception, packet, agent, component|
notify(exception, packet, agent, component)
end
end | [
"def",
"notify_callback",
"Proc",
".",
"new",
"do",
"|",
"exception",
",",
"packet",
",",
"agent",
",",
"component",
"|",
"notify",
"(",
"exception",
",",
"packet",
",",
"agent",
",",
"component",
")",
"end",
"end"
] | Create proc for making callback to notifier
@return [Proc] notifier callback | [
"Create",
"proc",
"for",
"making",
"callback",
"to",
"notifier"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/error_tracker.rb#L147-L151 |
622 | rightscale/right_agent | lib/right_agent/error_tracker.rb | RightScale.ErrorTracker.notify_init | def notify_init(agent_name, options)
if options[:airbrake_endpoint] && options[:airbrake_api_key]
unless require_succeeds?("airbrake-ruby")
raise RuntimeError, "airbrake-ruby gem missing - required if airbrake options used in ErrorTracker"
end
@cgi_data = {
:process => $0,
:pid => Process.pid,
:agent_name => agent_name
}
@cgi_data[:shard_id] = options[:shard_id] if options[:shard_id]
@filter_params = (options[:filter_params] || []).map { |p| p.to_s }
@notify_enabled = true
return true if Airbrake.send(:configured?, :right_agent)
Airbrake.configure(:right_agent) do |config|
config.host = options[:airbrake_endpoint]
config.project_id = options[:airbrake_api_key]
config.project_key = options[:airbrake_api_key]
config.root_directory = AgentConfig.root_dir
config.environment = ENV['RAILS_ENV']
config.app_version = CURRENT_SOURCE_SHA if defined?(CURRENT_SOURCE_SHA)
end
else
@notify_enabled = false
end
true
end | ruby | def notify_init(agent_name, options)
if options[:airbrake_endpoint] && options[:airbrake_api_key]
unless require_succeeds?("airbrake-ruby")
raise RuntimeError, "airbrake-ruby gem missing - required if airbrake options used in ErrorTracker"
end
@cgi_data = {
:process => $0,
:pid => Process.pid,
:agent_name => agent_name
}
@cgi_data[:shard_id] = options[:shard_id] if options[:shard_id]
@filter_params = (options[:filter_params] || []).map { |p| p.to_s }
@notify_enabled = true
return true if Airbrake.send(:configured?, :right_agent)
Airbrake.configure(:right_agent) do |config|
config.host = options[:airbrake_endpoint]
config.project_id = options[:airbrake_api_key]
config.project_key = options[:airbrake_api_key]
config.root_directory = AgentConfig.root_dir
config.environment = ENV['RAILS_ENV']
config.app_version = CURRENT_SOURCE_SHA if defined?(CURRENT_SOURCE_SHA)
end
else
@notify_enabled = false
end
true
end | [
"def",
"notify_init",
"(",
"agent_name",
",",
"options",
")",
"if",
"options",
"[",
":airbrake_endpoint",
"]",
"&&",
"options",
"[",
":airbrake_api_key",
"]",
"unless",
"require_succeeds?",
"(",
"\"airbrake-ruby\"",
")",
"raise",
"RuntimeError",
",",
"\"airbrake-ruby gem missing - required if airbrake options used in ErrorTracker\"",
"end",
"@cgi_data",
"=",
"{",
":process",
"=>",
"$0",
",",
":pid",
"=>",
"Process",
".",
"pid",
",",
":agent_name",
"=>",
"agent_name",
"}",
"@cgi_data",
"[",
":shard_id",
"]",
"=",
"options",
"[",
":shard_id",
"]",
"if",
"options",
"[",
":shard_id",
"]",
"@filter_params",
"=",
"(",
"options",
"[",
":filter_params",
"]",
"||",
"[",
"]",
")",
".",
"map",
"{",
"|",
"p",
"|",
"p",
".",
"to_s",
"}",
"@notify_enabled",
"=",
"true",
"return",
"true",
"if",
"Airbrake",
".",
"send",
"(",
":configured?",
",",
":right_agent",
")",
"Airbrake",
".",
"configure",
"(",
":right_agent",
")",
"do",
"|",
"config",
"|",
"config",
".",
"host",
"=",
"options",
"[",
":airbrake_endpoint",
"]",
"config",
".",
"project_id",
"=",
"options",
"[",
":airbrake_api_key",
"]",
"config",
".",
"project_key",
"=",
"options",
"[",
":airbrake_api_key",
"]",
"config",
".",
"root_directory",
"=",
"AgentConfig",
".",
"root_dir",
"config",
".",
"environment",
"=",
"ENV",
"[",
"'RAILS_ENV'",
"]",
"config",
".",
"app_version",
"=",
"CURRENT_SOURCE_SHA",
"if",
"defined?",
"(",
"CURRENT_SOURCE_SHA",
")",
"end",
"else",
"@notify_enabled",
"=",
"false",
"end",
"true",
"end"
] | Configure Airbrake for exception notification
@param [String] agent_name uniquely identifying agent process on given server
@option options [Integer, NilClass] :shard_id identifying shard of database in use
@option options [Array<Symbol, String>] :filter_params names whose values are to be
filtered when notifying
@option options [String] :airbrake_endpoint URL for Airbrake for reporting exceptions
to Errbit
@option options [String] :airbrake_api_key for using the Airbrake API to access Errbit
@return [TrueClass] always true
@raise [RuntimeError] airbrake gem missing | [
"Configure",
"Airbrake",
"for",
"exception",
"notification"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/error_tracker.rb#L189-L219 |
623 | rightscale/right_agent | lib/right_agent/error_tracker.rb | RightScale.ErrorTracker.filter | def filter(params)
if @filter_params
filtered_params = {}
params.each { |k, p| filtered_params[k] = @filter_params.include?(k.to_s) ? FILTERED_PARAM_VALUE : p }
filtered_params
end
end | ruby | def filter(params)
if @filter_params
filtered_params = {}
params.each { |k, p| filtered_params[k] = @filter_params.include?(k.to_s) ? FILTERED_PARAM_VALUE : p }
filtered_params
end
end | [
"def",
"filter",
"(",
"params",
")",
"if",
"@filter_params",
"filtered_params",
"=",
"{",
"}",
"params",
".",
"each",
"{",
"|",
"k",
",",
"p",
"|",
"filtered_params",
"[",
"k",
"]",
"=",
"@filter_params",
".",
"include?",
"(",
"k",
".",
"to_s",
")",
"?",
"FILTERED_PARAM_VALUE",
":",
"p",
"}",
"filtered_params",
"end",
"end"
] | Apply parameter filter
@param [Hash] params to be filtered
@return [Hash] filtered parameters | [
"Apply",
"parameter",
"filter"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/error_tracker.rb#L226-L232 |
624 | rightscale/right_agent | lib/right_agent/connectivity_checker.rb | RightScale.ConnectivityChecker.message_received | def message_received(&callback)
if block_given?
@message_received_callbacks << callback
else
@message_received_callbacks.each { |c| c.call }
if @check_interval > 0
now = Time.now
if (now - @last_received) > MIN_RESTART_INACTIVITY_TIMER_INTERVAL
@last_received = now
restart_inactivity_timer
end
end
end
true
end | ruby | def message_received(&callback)
if block_given?
@message_received_callbacks << callback
else
@message_received_callbacks.each { |c| c.call }
if @check_interval > 0
now = Time.now
if (now - @last_received) > MIN_RESTART_INACTIVITY_TIMER_INTERVAL
@last_received = now
restart_inactivity_timer
end
end
end
true
end | [
"def",
"message_received",
"(",
"&",
"callback",
")",
"if",
"block_given?",
"@message_received_callbacks",
"<<",
"callback",
"else",
"@message_received_callbacks",
".",
"each",
"{",
"|",
"c",
"|",
"c",
".",
"call",
"}",
"if",
"@check_interval",
">",
"0",
"now",
"=",
"Time",
".",
"now",
"if",
"(",
"now",
"-",
"@last_received",
")",
">",
"MIN_RESTART_INACTIVITY_TIMER_INTERVAL",
"@last_received",
"=",
"now",
"restart_inactivity_timer",
"end",
"end",
"end",
"true",
"end"
] | Update the time this agent last received a request or response message
and restart the inactivity timer thus deferring the next connectivity check
Also forward this message receipt notification to any callbacks that have registered
=== Block
Optional block without parameters that is activated when a message is received
=== Return
true:: Always return true | [
"Update",
"the",
"time",
"this",
"agent",
"last",
"received",
"a",
"request",
"or",
"response",
"message",
"and",
"restart",
"the",
"inactivity",
"timer",
"thus",
"deferring",
"the",
"next",
"connectivity",
"check",
"Also",
"forward",
"this",
"message",
"receipt",
"notification",
"to",
"any",
"callbacks",
"that",
"have",
"registered"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/connectivity_checker.rb#L61-L75 |
625 | rightscale/right_agent | lib/right_agent/connectivity_checker.rb | RightScale.ConnectivityChecker.check | def check(id = nil, max_ping_timeouts = MAX_PING_TIMEOUTS)
unless @terminating || @ping_timer || (id && [email protected]?(id))
@ping_id = id
@ping_timer = EM::Timer.new(PING_TIMEOUT) do
if @ping_id
begin
@ping_stats.update("timeout")
@ping_timer = nil
@ping_timeouts[@ping_id] = (@ping_timeouts[@ping_id] || 0) + 1
if @ping_timeouts[@ping_id] >= max_ping_timeouts
ErrorTracker.log(self, "Mapper ping via broker #{@ping_id} timed out after #{PING_TIMEOUT} seconds and now " +
"reached maximum of #{max_ping_timeouts} timeout#{max_ping_timeouts > 1 ? 's' : ''}, " +
"attempting to reconnect")
host, port, index, priority = @sender.client.identity_parts(@ping_id)
@sender.agent.connect(host, port, index, priority, force = true)
else
Log.warning("Mapper ping via broker #{@ping_id} timed out after #{PING_TIMEOUT} seconds")
end
rescue Exception => e
ErrorTracker.log(self, "Failed to reconnect to broker #{@ping_id}", e)
end
else
@ping_timer = nil
end
end
handler = lambda do |_|
begin
if @ping_timer
@ping_stats.update("success")
@ping_timer.cancel
@ping_timer = nil
@ping_timeouts[@ping_id] = 0
@ping_id = nil
end
rescue Exception => e
ErrorTracker.log(self, "Failed to cancel router ping", e)
end
end
request = Request.new("/router/ping", nil, {:from => @sender.identity, :token => AgentIdentity.generate})
@sender.pending_requests[request.token] = PendingRequest.new(Request, Time.now, handler)
ids = [@ping_id] if @ping_id
@ping_id = @sender.send(:publish, request, ids).first
end
true
end | ruby | def check(id = nil, max_ping_timeouts = MAX_PING_TIMEOUTS)
unless @terminating || @ping_timer || (id && [email protected]?(id))
@ping_id = id
@ping_timer = EM::Timer.new(PING_TIMEOUT) do
if @ping_id
begin
@ping_stats.update("timeout")
@ping_timer = nil
@ping_timeouts[@ping_id] = (@ping_timeouts[@ping_id] || 0) + 1
if @ping_timeouts[@ping_id] >= max_ping_timeouts
ErrorTracker.log(self, "Mapper ping via broker #{@ping_id} timed out after #{PING_TIMEOUT} seconds and now " +
"reached maximum of #{max_ping_timeouts} timeout#{max_ping_timeouts > 1 ? 's' : ''}, " +
"attempting to reconnect")
host, port, index, priority = @sender.client.identity_parts(@ping_id)
@sender.agent.connect(host, port, index, priority, force = true)
else
Log.warning("Mapper ping via broker #{@ping_id} timed out after #{PING_TIMEOUT} seconds")
end
rescue Exception => e
ErrorTracker.log(self, "Failed to reconnect to broker #{@ping_id}", e)
end
else
@ping_timer = nil
end
end
handler = lambda do |_|
begin
if @ping_timer
@ping_stats.update("success")
@ping_timer.cancel
@ping_timer = nil
@ping_timeouts[@ping_id] = 0
@ping_id = nil
end
rescue Exception => e
ErrorTracker.log(self, "Failed to cancel router ping", e)
end
end
request = Request.new("/router/ping", nil, {:from => @sender.identity, :token => AgentIdentity.generate})
@sender.pending_requests[request.token] = PendingRequest.new(Request, Time.now, handler)
ids = [@ping_id] if @ping_id
@ping_id = @sender.send(:publish, request, ids).first
end
true
end | [
"def",
"check",
"(",
"id",
"=",
"nil",
",",
"max_ping_timeouts",
"=",
"MAX_PING_TIMEOUTS",
")",
"unless",
"@terminating",
"||",
"@ping_timer",
"||",
"(",
"id",
"&&",
"!",
"@sender",
".",
"agent",
".",
"client",
".",
"connected?",
"(",
"id",
")",
")",
"@ping_id",
"=",
"id",
"@ping_timer",
"=",
"EM",
"::",
"Timer",
".",
"new",
"(",
"PING_TIMEOUT",
")",
"do",
"if",
"@ping_id",
"begin",
"@ping_stats",
".",
"update",
"(",
"\"timeout\"",
")",
"@ping_timer",
"=",
"nil",
"@ping_timeouts",
"[",
"@ping_id",
"]",
"=",
"(",
"@ping_timeouts",
"[",
"@ping_id",
"]",
"||",
"0",
")",
"+",
"1",
"if",
"@ping_timeouts",
"[",
"@ping_id",
"]",
">=",
"max_ping_timeouts",
"ErrorTracker",
".",
"log",
"(",
"self",
",",
"\"Mapper ping via broker #{@ping_id} timed out after #{PING_TIMEOUT} seconds and now \"",
"+",
"\"reached maximum of #{max_ping_timeouts} timeout#{max_ping_timeouts > 1 ? 's' : ''}, \"",
"+",
"\"attempting to reconnect\"",
")",
"host",
",",
"port",
",",
"index",
",",
"priority",
"=",
"@sender",
".",
"client",
".",
"identity_parts",
"(",
"@ping_id",
")",
"@sender",
".",
"agent",
".",
"connect",
"(",
"host",
",",
"port",
",",
"index",
",",
"priority",
",",
"force",
"=",
"true",
")",
"else",
"Log",
".",
"warning",
"(",
"\"Mapper ping via broker #{@ping_id} timed out after #{PING_TIMEOUT} seconds\"",
")",
"end",
"rescue",
"Exception",
"=>",
"e",
"ErrorTracker",
".",
"log",
"(",
"self",
",",
"\"Failed to reconnect to broker #{@ping_id}\"",
",",
"e",
")",
"end",
"else",
"@ping_timer",
"=",
"nil",
"end",
"end",
"handler",
"=",
"lambda",
"do",
"|",
"_",
"|",
"begin",
"if",
"@ping_timer",
"@ping_stats",
".",
"update",
"(",
"\"success\"",
")",
"@ping_timer",
".",
"cancel",
"@ping_timer",
"=",
"nil",
"@ping_timeouts",
"[",
"@ping_id",
"]",
"=",
"0",
"@ping_id",
"=",
"nil",
"end",
"rescue",
"Exception",
"=>",
"e",
"ErrorTracker",
".",
"log",
"(",
"self",
",",
"\"Failed to cancel router ping\"",
",",
"e",
")",
"end",
"end",
"request",
"=",
"Request",
".",
"new",
"(",
"\"/router/ping\"",
",",
"nil",
",",
"{",
":from",
"=>",
"@sender",
".",
"identity",
",",
":token",
"=>",
"AgentIdentity",
".",
"generate",
"}",
")",
"@sender",
".",
"pending_requests",
"[",
"request",
".",
"token",
"]",
"=",
"PendingRequest",
".",
"new",
"(",
"Request",
",",
"Time",
".",
"now",
",",
"handler",
")",
"ids",
"=",
"[",
"@ping_id",
"]",
"if",
"@ping_id",
"@ping_id",
"=",
"@sender",
".",
"send",
"(",
":publish",
",",
"request",
",",
"ids",
")",
".",
"first",
"end",
"true",
"end"
] | Check whether broker connection is usable by pinging a router via that broker
Attempt to reconnect if ping does not respond in PING_TIMEOUT seconds and
if have reached timeout limit
Ignore request if already checking a connection
=== Parameters
id(String):: Identity of specific broker to use to send ping, defaults to any
currently connected broker
max_ping_timeouts(Integer):: Maximum number of ping timeouts before attempt
to reconnect, defaults to MAX_PING_TIMEOUTS
=== Return
true:: Always return true | [
"Check",
"whether",
"broker",
"connection",
"is",
"usable",
"by",
"pinging",
"a",
"router",
"via",
"that",
"broker",
"Attempt",
"to",
"reconnect",
"if",
"ping",
"does",
"not",
"respond",
"in",
"PING_TIMEOUT",
"seconds",
"and",
"if",
"have",
"reached",
"timeout",
"limit",
"Ignore",
"request",
"if",
"already",
"checking",
"a",
"connection"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/connectivity_checker.rb#L90-L135 |
626 | rightscale/right_agent | lib/right_agent/connectivity_checker.rb | RightScale.ConnectivityChecker.restart_inactivity_timer | def restart_inactivity_timer
@inactivity_timer.cancel if @inactivity_timer
@inactivity_timer = EM::Timer.new(@check_interval) do
begin
check(id = nil, max_ping_timeouts = 1)
rescue Exception => e
ErrorTracker.log(self, "Failed connectivity check", e)
end
end
true
end | ruby | def restart_inactivity_timer
@inactivity_timer.cancel if @inactivity_timer
@inactivity_timer = EM::Timer.new(@check_interval) do
begin
check(id = nil, max_ping_timeouts = 1)
rescue Exception => e
ErrorTracker.log(self, "Failed connectivity check", e)
end
end
true
end | [
"def",
"restart_inactivity_timer",
"@inactivity_timer",
".",
"cancel",
"if",
"@inactivity_timer",
"@inactivity_timer",
"=",
"EM",
"::",
"Timer",
".",
"new",
"(",
"@check_interval",
")",
"do",
"begin",
"check",
"(",
"id",
"=",
"nil",
",",
"max_ping_timeouts",
"=",
"1",
")",
"rescue",
"Exception",
"=>",
"e",
"ErrorTracker",
".",
"log",
"(",
"self",
",",
"\"Failed connectivity check\"",
",",
"e",
")",
"end",
"end",
"true",
"end"
] | Start timer that waits for inactive messaging period to end before checking connectivity
=== Return
true:: Always return true | [
"Start",
"timer",
"that",
"waits",
"for",
"inactive",
"messaging",
"period",
"to",
"end",
"before",
"checking",
"connectivity"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/connectivity_checker.rb#L161-L171 |
627 | rightscale/right_agent | lib/right_agent/dispatched_cache.rb | RightScale.DispatchedCache.serviced_by | def serviced_by(token)
if @cache[token]
@cache[token] = Time.now.to_i
@lru.push(@lru.delete(token))
@identity
end
end | ruby | def serviced_by(token)
if @cache[token]
@cache[token] = Time.now.to_i
@lru.push(@lru.delete(token))
@identity
end
end | [
"def",
"serviced_by",
"(",
"token",
")",
"if",
"@cache",
"[",
"token",
"]",
"@cache",
"[",
"token",
"]",
"=",
"Time",
".",
"now",
".",
"to_i",
"@lru",
".",
"push",
"(",
"@lru",
".",
"delete",
"(",
"token",
")",
")",
"@identity",
"end",
"end"
] | Determine whether request has already been serviced
=== Parameters
token(String):: Generated message identifier
=== Return
(String|nil):: Identity of agent that already serviced request, or nil if none | [
"Determine",
"whether",
"request",
"has",
"already",
"been",
"serviced"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/dispatched_cache.rb#L75-L81 |
628 | rightscale/right_agent | lib/right_agent/dispatched_cache.rb | RightScale.DispatchedCache.stats | def stats
if (s = size) > 0
now = Time.now.to_i
{
"local total" => s,
"local max age" => RightSupport::Stats.elapsed(now - @cache[@lru.first])
}
end
end | ruby | def stats
if (s = size) > 0
now = Time.now.to_i
{
"local total" => s,
"local max age" => RightSupport::Stats.elapsed(now - @cache[@lru.first])
}
end
end | [
"def",
"stats",
"if",
"(",
"s",
"=",
"size",
")",
">",
"0",
"now",
"=",
"Time",
".",
"now",
".",
"to_i",
"{",
"\"local total\"",
"=>",
"s",
",",
"\"local max age\"",
"=>",
"RightSupport",
"::",
"Stats",
".",
"elapsed",
"(",
"now",
"-",
"@cache",
"[",
"@lru",
".",
"first",
"]",
")",
"}",
"end",
"end"
] | Get local cache statistics
=== Return
stats(Hash|nil):: Current statistics, or nil if cache empty
"local total"(Integer):: Total number in local cache, or nil if none
"local max age"(String):: Time since oldest local cache entry created or updated | [
"Get",
"local",
"cache",
"statistics"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/dispatched_cache.rb#L89-L97 |
629 | rightscale/right_agent | lib/right_agent/scripts/agent_controller.rb | RightScale.AgentController.control | def control(options)
# Initialize directory settings
AgentConfig.cfg_dir = options[:cfg_dir]
AgentConfig.pid_dir = options[:pid_dir]
# List agents if requested
list_configured_agents if options[:list]
# Validate arguments
action = options.delete(:action)
fail("No action specified on the command line.", print_usage = true) unless action
if action == 'kill' && (options[:pid_file].nil? || !File.file?(options[:pid_file]))
fail("Missing or invalid pid file #{options[:pid_file]}", print_usage = true)
end
if options[:agent_name]
if action == 'start'
cfg = configure_agent(action, options)
else
cfg = AgentConfig.load_cfg(options[:agent_name])
fail("Deployment is missing configuration file #{AgentConfig.cfg_file(options[:agent_name]).inspect}.") unless cfg
end
options.delete(:identity)
options = cfg.merge(options)
AgentConfig.root_dir = options[:root_dir]
AgentConfig.pid_dir = options[:pid_dir]
Log.program_name = syslog_program_name(options)
Log.facility = syslog_facility(options)
Log.log_to_file_only(options[:log_to_file_only])
configure_proxy(options[:http_proxy], options[:http_no_proxy]) if options[:http_proxy]
elsif options[:identity]
options[:agent_name] = AgentConfig.agent_name(options[:identity])
end
@options = DEFAULT_OPTIONS.clone.merge(options.merge(FORCED_OPTIONS))
FileUtils.mkdir_p(@options[:pid_dir]) unless @options[:pid_dir].nil? || File.directory?(@options[:pid_dir])
# Execute request
success = case action
when /show|killall/
action = 'stop' if action == 'killall'
s = true
AgentConfig.cfg_agents.each { |agent_name| s &&= dispatch(action, agent_name) }
s
when 'kill'
kill_process
else
dispatch(action, @options[:agent_name])
end
exit(1) unless success
end | ruby | def control(options)
# Initialize directory settings
AgentConfig.cfg_dir = options[:cfg_dir]
AgentConfig.pid_dir = options[:pid_dir]
# List agents if requested
list_configured_agents if options[:list]
# Validate arguments
action = options.delete(:action)
fail("No action specified on the command line.", print_usage = true) unless action
if action == 'kill' && (options[:pid_file].nil? || !File.file?(options[:pid_file]))
fail("Missing or invalid pid file #{options[:pid_file]}", print_usage = true)
end
if options[:agent_name]
if action == 'start'
cfg = configure_agent(action, options)
else
cfg = AgentConfig.load_cfg(options[:agent_name])
fail("Deployment is missing configuration file #{AgentConfig.cfg_file(options[:agent_name]).inspect}.") unless cfg
end
options.delete(:identity)
options = cfg.merge(options)
AgentConfig.root_dir = options[:root_dir]
AgentConfig.pid_dir = options[:pid_dir]
Log.program_name = syslog_program_name(options)
Log.facility = syslog_facility(options)
Log.log_to_file_only(options[:log_to_file_only])
configure_proxy(options[:http_proxy], options[:http_no_proxy]) if options[:http_proxy]
elsif options[:identity]
options[:agent_name] = AgentConfig.agent_name(options[:identity])
end
@options = DEFAULT_OPTIONS.clone.merge(options.merge(FORCED_OPTIONS))
FileUtils.mkdir_p(@options[:pid_dir]) unless @options[:pid_dir].nil? || File.directory?(@options[:pid_dir])
# Execute request
success = case action
when /show|killall/
action = 'stop' if action == 'killall'
s = true
AgentConfig.cfg_agents.each { |agent_name| s &&= dispatch(action, agent_name) }
s
when 'kill'
kill_process
else
dispatch(action, @options[:agent_name])
end
exit(1) unless success
end | [
"def",
"control",
"(",
"options",
")",
"# Initialize directory settings",
"AgentConfig",
".",
"cfg_dir",
"=",
"options",
"[",
":cfg_dir",
"]",
"AgentConfig",
".",
"pid_dir",
"=",
"options",
"[",
":pid_dir",
"]",
"# List agents if requested",
"list_configured_agents",
"if",
"options",
"[",
":list",
"]",
"# Validate arguments",
"action",
"=",
"options",
".",
"delete",
"(",
":action",
")",
"fail",
"(",
"\"No action specified on the command line.\"",
",",
"print_usage",
"=",
"true",
")",
"unless",
"action",
"if",
"action",
"==",
"'kill'",
"&&",
"(",
"options",
"[",
":pid_file",
"]",
".",
"nil?",
"||",
"!",
"File",
".",
"file?",
"(",
"options",
"[",
":pid_file",
"]",
")",
")",
"fail",
"(",
"\"Missing or invalid pid file #{options[:pid_file]}\"",
",",
"print_usage",
"=",
"true",
")",
"end",
"if",
"options",
"[",
":agent_name",
"]",
"if",
"action",
"==",
"'start'",
"cfg",
"=",
"configure_agent",
"(",
"action",
",",
"options",
")",
"else",
"cfg",
"=",
"AgentConfig",
".",
"load_cfg",
"(",
"options",
"[",
":agent_name",
"]",
")",
"fail",
"(",
"\"Deployment is missing configuration file #{AgentConfig.cfg_file(options[:agent_name]).inspect}.\"",
")",
"unless",
"cfg",
"end",
"options",
".",
"delete",
"(",
":identity",
")",
"options",
"=",
"cfg",
".",
"merge",
"(",
"options",
")",
"AgentConfig",
".",
"root_dir",
"=",
"options",
"[",
":root_dir",
"]",
"AgentConfig",
".",
"pid_dir",
"=",
"options",
"[",
":pid_dir",
"]",
"Log",
".",
"program_name",
"=",
"syslog_program_name",
"(",
"options",
")",
"Log",
".",
"facility",
"=",
"syslog_facility",
"(",
"options",
")",
"Log",
".",
"log_to_file_only",
"(",
"options",
"[",
":log_to_file_only",
"]",
")",
"configure_proxy",
"(",
"options",
"[",
":http_proxy",
"]",
",",
"options",
"[",
":http_no_proxy",
"]",
")",
"if",
"options",
"[",
":http_proxy",
"]",
"elsif",
"options",
"[",
":identity",
"]",
"options",
"[",
":agent_name",
"]",
"=",
"AgentConfig",
".",
"agent_name",
"(",
"options",
"[",
":identity",
"]",
")",
"end",
"@options",
"=",
"DEFAULT_OPTIONS",
".",
"clone",
".",
"merge",
"(",
"options",
".",
"merge",
"(",
"FORCED_OPTIONS",
")",
")",
"FileUtils",
".",
"mkdir_p",
"(",
"@options",
"[",
":pid_dir",
"]",
")",
"unless",
"@options",
"[",
":pid_dir",
"]",
".",
"nil?",
"||",
"File",
".",
"directory?",
"(",
"@options",
"[",
":pid_dir",
"]",
")",
"# Execute request",
"success",
"=",
"case",
"action",
"when",
"/",
"/",
"action",
"=",
"'stop'",
"if",
"action",
"==",
"'killall'",
"s",
"=",
"true",
"AgentConfig",
".",
"cfg_agents",
".",
"each",
"{",
"|",
"agent_name",
"|",
"s",
"&&=",
"dispatch",
"(",
"action",
",",
"agent_name",
")",
"}",
"s",
"when",
"'kill'",
"kill_process",
"else",
"dispatch",
"(",
"action",
",",
"@options",
"[",
":agent_name",
"]",
")",
"end",
"exit",
"(",
"1",
")",
"unless",
"success",
"end"
] | Parse arguments and execute request
=== Parameters
options(Hash):: Command line options
=== Return
true:: Always return true | [
"Parse",
"arguments",
"and",
"execute",
"request"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/scripts/agent_controller.rb#L116-L166 |
630 | rightscale/right_agent | lib/right_agent/scripts/agent_controller.rb | RightScale.AgentController.kill_process | def kill_process(sig = 'TERM')
content = IO.read(@options[:pid_file])
pid = content.to_i
fail("Invalid pid file content #{content.inspect}") if pid == 0
begin
Process.kill(sig, pid)
rescue Errno::ESRCH => e
fail("Could not find process with pid #{pid}")
rescue Errno::EPERM => e
fail("You don't have permissions to stop process #{pid}")
rescue Exception => e
fail(e.message)
end
true
end | ruby | def kill_process(sig = 'TERM')
content = IO.read(@options[:pid_file])
pid = content.to_i
fail("Invalid pid file content #{content.inspect}") if pid == 0
begin
Process.kill(sig, pid)
rescue Errno::ESRCH => e
fail("Could not find process with pid #{pid}")
rescue Errno::EPERM => e
fail("You don't have permissions to stop process #{pid}")
rescue Exception => e
fail(e.message)
end
true
end | [
"def",
"kill_process",
"(",
"sig",
"=",
"'TERM'",
")",
"content",
"=",
"IO",
".",
"read",
"(",
"@options",
"[",
":pid_file",
"]",
")",
"pid",
"=",
"content",
".",
"to_i",
"fail",
"(",
"\"Invalid pid file content #{content.inspect}\"",
")",
"if",
"pid",
"==",
"0",
"begin",
"Process",
".",
"kill",
"(",
"sig",
",",
"pid",
")",
"rescue",
"Errno",
"::",
"ESRCH",
"=>",
"e",
"fail",
"(",
"\"Could not find process with pid #{pid}\"",
")",
"rescue",
"Errno",
"::",
"EPERM",
"=>",
"e",
"fail",
"(",
"\"You don't have permissions to stop process #{pid}\"",
")",
"rescue",
"Exception",
"=>",
"e",
"fail",
"(",
"e",
".",
"message",
")",
"end",
"true",
"end"
] | Kill process defined in pid file
=== Parameters
sig(String):: Signal to be used for kill
=== Return
true:: Always return true | [
"Kill",
"process",
"defined",
"in",
"pid",
"file"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/scripts/agent_controller.rb#L308-L322 |
631 | rightscale/right_agent | lib/right_agent/scripts/agent_controller.rb | RightScale.AgentController.stop_agent | def stop_agent(agent_name)
res = false
if (pid_file = AgentConfig.pid_file(agent_name))
name = human_readable_name(agent_name, pid_file.identity)
if (pid = pid_file.read_pid[:pid])
begin
Process.kill('TERM', pid)
res = true
puts "#{name} stopped"
rescue Errno::ESRCH
puts "#{name} not running"
end
elsif File.file?(pid_file.to_s)
puts "Invalid pid file '#{pid_file.to_s}' content: #{IO.read(pid_file.to_s)}"
else
puts "#{name} not running"
end
else
puts "Non-existent pid file for #{agent_name}"
end
res
end | ruby | def stop_agent(agent_name)
res = false
if (pid_file = AgentConfig.pid_file(agent_name))
name = human_readable_name(agent_name, pid_file.identity)
if (pid = pid_file.read_pid[:pid])
begin
Process.kill('TERM', pid)
res = true
puts "#{name} stopped"
rescue Errno::ESRCH
puts "#{name} not running"
end
elsif File.file?(pid_file.to_s)
puts "Invalid pid file '#{pid_file.to_s}' content: #{IO.read(pid_file.to_s)}"
else
puts "#{name} not running"
end
else
puts "Non-existent pid file for #{agent_name}"
end
res
end | [
"def",
"stop_agent",
"(",
"agent_name",
")",
"res",
"=",
"false",
"if",
"(",
"pid_file",
"=",
"AgentConfig",
".",
"pid_file",
"(",
"agent_name",
")",
")",
"name",
"=",
"human_readable_name",
"(",
"agent_name",
",",
"pid_file",
".",
"identity",
")",
"if",
"(",
"pid",
"=",
"pid_file",
".",
"read_pid",
"[",
":pid",
"]",
")",
"begin",
"Process",
".",
"kill",
"(",
"'TERM'",
",",
"pid",
")",
"res",
"=",
"true",
"puts",
"\"#{name} stopped\"",
"rescue",
"Errno",
"::",
"ESRCH",
"puts",
"\"#{name} not running\"",
"end",
"elsif",
"File",
".",
"file?",
"(",
"pid_file",
".",
"to_s",
")",
"puts",
"\"Invalid pid file '#{pid_file.to_s}' content: #{IO.read(pid_file.to_s)}\"",
"else",
"puts",
"\"#{name} not running\"",
"end",
"else",
"puts",
"\"Non-existent pid file for #{agent_name}\"",
"end",
"res",
"end"
] | Stop agent process
=== Parameters
agent_name(String):: Agent name
=== Return
(Boolean):: true if process was stopped, otherwise false | [
"Stop",
"agent",
"process"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/scripts/agent_controller.rb#L371-L392 |
632 | rightscale/right_agent | lib/right_agent/scripts/agent_controller.rb | RightScale.AgentController.list_configured_agents | def list_configured_agents
agents = AgentConfig.cfg_agents
if agents.empty?
puts "Found no configured agents"
else
puts "Configured agents:"
agents.each { |a| puts " - #{a}" }
end
exit
end | ruby | def list_configured_agents
agents = AgentConfig.cfg_agents
if agents.empty?
puts "Found no configured agents"
else
puts "Configured agents:"
agents.each { |a| puts " - #{a}" }
end
exit
end | [
"def",
"list_configured_agents",
"agents",
"=",
"AgentConfig",
".",
"cfg_agents",
"if",
"agents",
".",
"empty?",
"puts",
"\"Found no configured agents\"",
"else",
"puts",
"\"Configured agents:\"",
"agents",
".",
"each",
"{",
"|",
"a",
"|",
"puts",
"\" - #{a}\"",
"}",
"end",
"exit",
"end"
] | List all configured agents
=== Return
never | [
"List",
"all",
"configured",
"agents"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/scripts/agent_controller.rb#L439-L448 |
633 | rightscale/right_agent | lib/right_agent/scripts/agent_controller.rb | RightScale.AgentController.configure_agent | def configure_agent(action, options)
agent_type = options[:agent_type]
agent_name = options[:agent_name]
if agent_name != agent_type && (cfg = AgentConfig.load_cfg(agent_type))
base_id = (options[:base_id] || AgentIdentity.parse(cfg[:identity]).base_id.to_s).to_i
unless (identity = AgentConfig.agent_options(agent_name)[:identity]) &&
AgentIdentity.parse(identity).base_id == base_id
identity = AgentIdentity.new(options[:prefix] || 'rs', options[:agent_type], base_id, options[:token]).to_s
end
cfg.merge!(:identity => identity)
cfg_file = AgentConfig.store_cfg(agent_name, cfg)
puts "Generated configuration file for #{agent_name} agent: #{cfg_file}"
elsif !(cfg = AgentConfig.load_cfg(agent_name))
fail("Deployment is missing configuration file #{AgentConfig.cfg_file(agent_name).inspect}")
end
cfg
end | ruby | def configure_agent(action, options)
agent_type = options[:agent_type]
agent_name = options[:agent_name]
if agent_name != agent_type && (cfg = AgentConfig.load_cfg(agent_type))
base_id = (options[:base_id] || AgentIdentity.parse(cfg[:identity]).base_id.to_s).to_i
unless (identity = AgentConfig.agent_options(agent_name)[:identity]) &&
AgentIdentity.parse(identity).base_id == base_id
identity = AgentIdentity.new(options[:prefix] || 'rs', options[:agent_type], base_id, options[:token]).to_s
end
cfg.merge!(:identity => identity)
cfg_file = AgentConfig.store_cfg(agent_name, cfg)
puts "Generated configuration file for #{agent_name} agent: #{cfg_file}"
elsif !(cfg = AgentConfig.load_cfg(agent_name))
fail("Deployment is missing configuration file #{AgentConfig.cfg_file(agent_name).inspect}")
end
cfg
end | [
"def",
"configure_agent",
"(",
"action",
",",
"options",
")",
"agent_type",
"=",
"options",
"[",
":agent_type",
"]",
"agent_name",
"=",
"options",
"[",
":agent_name",
"]",
"if",
"agent_name",
"!=",
"agent_type",
"&&",
"(",
"cfg",
"=",
"AgentConfig",
".",
"load_cfg",
"(",
"agent_type",
")",
")",
"base_id",
"=",
"(",
"options",
"[",
":base_id",
"]",
"||",
"AgentIdentity",
".",
"parse",
"(",
"cfg",
"[",
":identity",
"]",
")",
".",
"base_id",
".",
"to_s",
")",
".",
"to_i",
"unless",
"(",
"identity",
"=",
"AgentConfig",
".",
"agent_options",
"(",
"agent_name",
")",
"[",
":identity",
"]",
")",
"&&",
"AgentIdentity",
".",
"parse",
"(",
"identity",
")",
".",
"base_id",
"==",
"base_id",
"identity",
"=",
"AgentIdentity",
".",
"new",
"(",
"options",
"[",
":prefix",
"]",
"||",
"'rs'",
",",
"options",
"[",
":agent_type",
"]",
",",
"base_id",
",",
"options",
"[",
":token",
"]",
")",
".",
"to_s",
"end",
"cfg",
".",
"merge!",
"(",
":identity",
"=>",
"identity",
")",
"cfg_file",
"=",
"AgentConfig",
".",
"store_cfg",
"(",
"agent_name",
",",
"cfg",
")",
"puts",
"\"Generated configuration file for #{agent_name} agent: #{cfg_file}\"",
"elsif",
"!",
"(",
"cfg",
"=",
"AgentConfig",
".",
"load_cfg",
"(",
"agent_name",
")",
")",
"fail",
"(",
"\"Deployment is missing configuration file #{AgentConfig.cfg_file(agent_name).inspect}\"",
")",
"end",
"cfg",
"end"
] | Determine configuration settings for this agent and persist them if needed
Reuse existing agent identity when possible
=== Parameters
action(String):: Requested action
options(Hash):: Command line options
=== Return
cfg(Hash):: Persisted configuration options | [
"Determine",
"configuration",
"settings",
"for",
"this",
"agent",
"and",
"persist",
"them",
"if",
"needed",
"Reuse",
"existing",
"agent",
"identity",
"when",
"possible"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/scripts/agent_controller.rb#L481-L497 |
634 | rightscale/right_agent | lib/right_agent/scripts/agent_controller.rb | RightScale.AgentController.configure_proxy | def configure_proxy(proxy_setting, exceptions)
ENV['HTTP_PROXY'] = proxy_setting
ENV['http_proxy'] = proxy_setting
ENV['HTTPS_PROXY'] = proxy_setting
ENV['https_proxy'] = proxy_setting
ENV['NO_PROXY'] = exceptions
ENV['no_proxy'] = exceptions
true
end | ruby | def configure_proxy(proxy_setting, exceptions)
ENV['HTTP_PROXY'] = proxy_setting
ENV['http_proxy'] = proxy_setting
ENV['HTTPS_PROXY'] = proxy_setting
ENV['https_proxy'] = proxy_setting
ENV['NO_PROXY'] = exceptions
ENV['no_proxy'] = exceptions
true
end | [
"def",
"configure_proxy",
"(",
"proxy_setting",
",",
"exceptions",
")",
"ENV",
"[",
"'HTTP_PROXY'",
"]",
"=",
"proxy_setting",
"ENV",
"[",
"'http_proxy'",
"]",
"=",
"proxy_setting",
"ENV",
"[",
"'HTTPS_PROXY'",
"]",
"=",
"proxy_setting",
"ENV",
"[",
"'https_proxy'",
"]",
"=",
"proxy_setting",
"ENV",
"[",
"'NO_PROXY'",
"]",
"=",
"exceptions",
"ENV",
"[",
"'no_proxy'",
"]",
"=",
"exceptions",
"true",
"end"
] | Enable the use of an HTTP proxy for this process and its subprocesses
=== Parameters
proxy_setting(String):: Proxy to use
exceptions(String):: Comma-separated list of proxy exceptions (e.g. metadata server)
=== Return
true:: Always return true | [
"Enable",
"the",
"use",
"of",
"an",
"HTTP",
"proxy",
"for",
"this",
"process",
"and",
"its",
"subprocesses"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/scripts/agent_controller.rb#L507-L515 |
635 | rightscale/right_agent | lib/right_agent/serialize/serializer.rb | RightScale.Serializer.cascade_serializers | def cascade_serializers(action, packet, serializers, id = nil)
errors = []
serializers.map do |serializer|
obj = nil
begin
obj = serializer == SecureSerializer ? serializer.send(action, packet, id) : serializer.send(action, packet)
rescue RightSupport::Net::NoResult, SocketError => e
raise Exceptions::ConnectivityFailure.new("Failed to #{action} with #{serializer.name} due to external " +
"service access failures (#{e.class.name}: #{e.message})", e)
rescue SecureSerializer::MissingCertificate, SecureSerializer::MissingPrivateKey, SecureSerializer::InvalidSignature => e
errors << Log.format("Failed to #{action} with #{serializer.name}", e)
rescue StandardError => e
errors << Log.format("Failed to #{action} with #{serializer.name}", e, :trace)
end
return obj if obj
end
raise SerializationError.new(action, packet, serializers, errors.join("\n"))
end | ruby | def cascade_serializers(action, packet, serializers, id = nil)
errors = []
serializers.map do |serializer|
obj = nil
begin
obj = serializer == SecureSerializer ? serializer.send(action, packet, id) : serializer.send(action, packet)
rescue RightSupport::Net::NoResult, SocketError => e
raise Exceptions::ConnectivityFailure.new("Failed to #{action} with #{serializer.name} due to external " +
"service access failures (#{e.class.name}: #{e.message})", e)
rescue SecureSerializer::MissingCertificate, SecureSerializer::MissingPrivateKey, SecureSerializer::InvalidSignature => e
errors << Log.format("Failed to #{action} with #{serializer.name}", e)
rescue StandardError => e
errors << Log.format("Failed to #{action} with #{serializer.name}", e, :trace)
end
return obj if obj
end
raise SerializationError.new(action, packet, serializers, errors.join("\n"))
end | [
"def",
"cascade_serializers",
"(",
"action",
",",
"packet",
",",
"serializers",
",",
"id",
"=",
"nil",
")",
"errors",
"=",
"[",
"]",
"serializers",
".",
"map",
"do",
"|",
"serializer",
"|",
"obj",
"=",
"nil",
"begin",
"obj",
"=",
"serializer",
"==",
"SecureSerializer",
"?",
"serializer",
".",
"send",
"(",
"action",
",",
"packet",
",",
"id",
")",
":",
"serializer",
".",
"send",
"(",
"action",
",",
"packet",
")",
"rescue",
"RightSupport",
"::",
"Net",
"::",
"NoResult",
",",
"SocketError",
"=>",
"e",
"raise",
"Exceptions",
"::",
"ConnectivityFailure",
".",
"new",
"(",
"\"Failed to #{action} with #{serializer.name} due to external \"",
"+",
"\"service access failures (#{e.class.name}: #{e.message})\"",
",",
"e",
")",
"rescue",
"SecureSerializer",
"::",
"MissingCertificate",
",",
"SecureSerializer",
"::",
"MissingPrivateKey",
",",
"SecureSerializer",
"::",
"InvalidSignature",
"=>",
"e",
"errors",
"<<",
"Log",
".",
"format",
"(",
"\"Failed to #{action} with #{serializer.name}\"",
",",
"e",
")",
"rescue",
"StandardError",
"=>",
"e",
"errors",
"<<",
"Log",
".",
"format",
"(",
"\"Failed to #{action} with #{serializer.name}\"",
",",
"e",
",",
":trace",
")",
"end",
"return",
"obj",
"if",
"obj",
"end",
"raise",
"SerializationError",
".",
"new",
"(",
"action",
",",
"packet",
",",
"serializers",
",",
"errors",
".",
"join",
"(",
"\"\\n\"",
")",
")",
"end"
] | Apply serializers in order until one succeeds
=== Parameters
action(Symbol):: Serialization action: :dump or :load
packet(Object|String):: Object or serialized data on which action is to be performed
serializers(Array):: Serializers to apply in order
id(String):: Optional identifier of source of data for use in determining who is the receiver
=== Return
(String|Object):: Result of serialization action
=== Raises
SerializationError:: If none of the serializers can perform the requested action
RightScale::Exceptions::ConnectivityFailure:: If cannot access external services | [
"Apply",
"serializers",
"in",
"order",
"until",
"one",
"succeeds"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/serialize/serializer.rb#L135-L152 |
636 | rightscale/right_agent | lib/right_agent/multiplexer.rb | RightScale.Multiplexer.method_missing | def method_missing(m, *args)
res = @targets.inject([]) { |res, t| res << t.send(m, *args) }
res[0]
end | ruby | def method_missing(m, *args)
res = @targets.inject([]) { |res, t| res << t.send(m, *args) }
res[0]
end | [
"def",
"method_missing",
"(",
"m",
",",
"*",
"args",
")",
"res",
"=",
"@targets",
".",
"inject",
"(",
"[",
"]",
")",
"{",
"|",
"res",
",",
"t",
"|",
"res",
"<<",
"t",
".",
"send",
"(",
"m",
",",
"args",
")",
"}",
"res",
"[",
"0",
"]",
"end"
] | Forward any method invocation to targets
=== Parameters
m(Symbol):: Method that should be multiplexed
args(Array):: Arguments
=== Return
res(Object):: Result of first target in list | [
"Forward",
"any",
"method",
"invocation",
"to",
"targets"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/multiplexer.rb#L85-L88 |
637 | rightscale/right_agent | lib/right_agent/multiplexer.rb | RightScale.Multiplexer.respond_to? | def respond_to?(m, *args)
super(m, *args) || @targets.all? { |t| t.respond_to?(m, *args) }
end | ruby | def respond_to?(m, *args)
super(m, *args) || @targets.all? { |t| t.respond_to?(m, *args) }
end | [
"def",
"respond_to?",
"(",
"m",
",",
"*",
"args",
")",
"super",
"(",
"m",
",",
"args",
")",
"||",
"@targets",
".",
"all?",
"{",
"|",
"t",
"|",
"t",
".",
"respond_to?",
"(",
"m",
",",
"args",
")",
"}",
"end"
] | Determine whether this object, or ALL of its targets, responds to
the named method.
=== Parameters
m(Symbol):: Forwarded method name
=== Return
(true|false):: True if this object, or ALL targets, respond to the names method; false otherwise | [
"Determine",
"whether",
"this",
"object",
"or",
"ALL",
"of",
"its",
"targets",
"responds",
"to",
"the",
"named",
"method",
"."
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/multiplexer.rb#L98-L100 |
638 | rightscale/right_agent | lib/right_agent/operation_result.rb | RightScale.OperationResult.status | def status(reason = false)
case @status_code
when SUCCESS then 'success'
when ERROR then 'error' + (reason ? " (#{truncated_error})" : "")
when CONTINUE then 'continue'
when RETRY then 'retry' + (reason ? " (#{@content})" : "")
when NON_DELIVERY then 'non-delivery' + (reason ? " (#{@content})" : "")
when MULTICAST then 'multicast'
when CANCEL then 'cancel' + (reason ? " (#{@content})" : "")
end
end | ruby | def status(reason = false)
case @status_code
when SUCCESS then 'success'
when ERROR then 'error' + (reason ? " (#{truncated_error})" : "")
when CONTINUE then 'continue'
when RETRY then 'retry' + (reason ? " (#{@content})" : "")
when NON_DELIVERY then 'non-delivery' + (reason ? " (#{@content})" : "")
when MULTICAST then 'multicast'
when CANCEL then 'cancel' + (reason ? " (#{@content})" : "")
end
end | [
"def",
"status",
"(",
"reason",
"=",
"false",
")",
"case",
"@status_code",
"when",
"SUCCESS",
"then",
"'success'",
"when",
"ERROR",
"then",
"'error'",
"+",
"(",
"reason",
"?",
"\" (#{truncated_error})\"",
":",
"\"\"",
")",
"when",
"CONTINUE",
"then",
"'continue'",
"when",
"RETRY",
"then",
"'retry'",
"+",
"(",
"reason",
"?",
"\" (#{@content})\"",
":",
"\"\"",
")",
"when",
"NON_DELIVERY",
"then",
"'non-delivery'",
"+",
"(",
"reason",
"?",
"\" (#{@content})\"",
":",
"\"\"",
")",
"when",
"MULTICAST",
"then",
"'multicast'",
"when",
"CANCEL",
"then",
"'cancel'",
"+",
"(",
"reason",
"?",
"\" (#{@content})\"",
":",
"\"\"",
")",
"end",
"end"
] | User friendly result status
=== Parameters
reason(Boolean):: Whether to include failure reason information, default to false
=== Return
(String):: Name of result code | [
"User",
"friendly",
"result",
"status"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/operation_result.rb#L80-L90 |
639 | rightscale/right_agent | lib/right_agent/operation_result.rb | RightScale.OperationResult.truncated_error | def truncated_error
e = @content.is_a?(String) ? @content : @content.inspect
e = e[0, MAX_ERROR_SIZE - 3] + "..." if e.size > (MAX_ERROR_SIZE - 3)
e
end | ruby | def truncated_error
e = @content.is_a?(String) ? @content : @content.inspect
e = e[0, MAX_ERROR_SIZE - 3] + "..." if e.size > (MAX_ERROR_SIZE - 3)
e
end | [
"def",
"truncated_error",
"e",
"=",
"@content",
".",
"is_a?",
"(",
"String",
")",
"?",
"@content",
":",
"@content",
".",
"inspect",
"e",
"=",
"e",
"[",
"0",
",",
"MAX_ERROR_SIZE",
"-",
"3",
"]",
"+",
"\"...\"",
"if",
"e",
".",
"size",
">",
"(",
"MAX_ERROR_SIZE",
"-",
"3",
")",
"e",
"end"
] | Limited length error string
=== Return
e(String):: String of no more than MAX_ERROR_SIZE characters | [
"Limited",
"length",
"error",
"string"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/operation_result.rb#L96-L100 |
640 | rightscale/right_agent | lib/right_agent/command/command_io.rb | RightScale.CommandIO.listen | def listen(socket_port, &block)
raise ArgumentError, 'Missing listener block' unless block_given?
raise Exceptions::Application, 'Already listening' if listening
begin
@conn = EM.start_server('127.0.0.1', socket_port, ServerInputHandler, block)
rescue Exception => e
raise Exceptions::IO, 'Listen port unavailable' if e.message =~ /no acceptor/
end
true
end | ruby | def listen(socket_port, &block)
raise ArgumentError, 'Missing listener block' unless block_given?
raise Exceptions::Application, 'Already listening' if listening
begin
@conn = EM.start_server('127.0.0.1', socket_port, ServerInputHandler, block)
rescue Exception => e
raise Exceptions::IO, 'Listen port unavailable' if e.message =~ /no acceptor/
end
true
end | [
"def",
"listen",
"(",
"socket_port",
",",
"&",
"block",
")",
"raise",
"ArgumentError",
",",
"'Missing listener block'",
"unless",
"block_given?",
"raise",
"Exceptions",
"::",
"Application",
",",
"'Already listening'",
"if",
"listening",
"begin",
"@conn",
"=",
"EM",
".",
"start_server",
"(",
"'127.0.0.1'",
",",
"socket_port",
",",
"ServerInputHandler",
",",
"block",
")",
"rescue",
"Exception",
"=>",
"e",
"raise",
"Exceptions",
"::",
"IO",
",",
"'Listen port unavailable'",
"if",
"e",
".",
"message",
"=~",
"/",
"/",
"end",
"true",
"end"
] | Open command socket and wait for input on it
This can only be called again after 'stop_listening' was called
=== Parameters
socket_port(Integer):: Socket port on which to listen
=== Block
The given block should take two arguments:
* First argument will be given the commands sent through the socket
Commands should be serialized using RightScale::CommandSerializer.
* Second argument contains the connection that should be given back to
+reply+ to send reply
=== Return
true:: Always return true
=== Raise
(ArgumentError):: If block is missing
(Exceptions::Application):: If +listen+ has already been called and +stop+ hasn't since
(Exceptions::Application):: If port is already bound | [
"Open",
"command",
"socket",
"and",
"wait",
"for",
"input",
"on",
"it",
"This",
"can",
"only",
"be",
"called",
"again",
"after",
"stop_listening",
"was",
"called"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/command/command_io.rb#L82-L91 |
641 | rightscale/right_agent | lib/right_agent/command/command_io.rb | RightScale.CommandIO.reply | def reply(conn, data, close_after_writing=true)
conn.send_data(CommandSerializer.dump(data))
conn.close_connection_after_writing if close_after_writing
true
end | ruby | def reply(conn, data, close_after_writing=true)
conn.send_data(CommandSerializer.dump(data))
conn.close_connection_after_writing if close_after_writing
true
end | [
"def",
"reply",
"(",
"conn",
",",
"data",
",",
"close_after_writing",
"=",
"true",
")",
"conn",
".",
"send_data",
"(",
"CommandSerializer",
".",
"dump",
"(",
"data",
")",
")",
"conn",
".",
"close_connection_after_writing",
"if",
"close_after_writing",
"true",
"end"
] | Write given data to socket, must be listening
=== Parameters
conn(EM::Connection):: Connection used to send data
data(String):: Data that should be written
close_after_writing(TrueClass|FalseClass):: Whether TCP connection with client should be
closed after reply is sent
=== Return
true:: Always return true | [
"Write",
"given",
"data",
"to",
"socket",
"must",
"be",
"listening"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/command/command_io.rb#L118-L122 |
642 | rightscale/right_agent | lib/right_agent/scripts/log_level_manager.rb | RightScale.LogLevelManager.manage | def manage(options)
# Initialize configuration directory setting
AgentConfig.cfg_dir = options[:cfg_dir]
# Determine command
level = options[:level]
command = { :name => (level ? 'set_log_level' : 'get_log_level') }
command[:level] = level.to_sym if level
# Determine candidate agents
agent_names = if options[:agent_name]
[options[:agent_name]]
else
AgentConfig.cfg_agents
end
fail("No agents configured") if agent_names.empty?
# Perform command for each agent
count = 0
agent_names.each do |agent_name|
count += 1 if request_log_level(agent_name, command, options)
end
puts("No agents running") if count == 0
true
end | ruby | def manage(options)
# Initialize configuration directory setting
AgentConfig.cfg_dir = options[:cfg_dir]
# Determine command
level = options[:level]
command = { :name => (level ? 'set_log_level' : 'get_log_level') }
command[:level] = level.to_sym if level
# Determine candidate agents
agent_names = if options[:agent_name]
[options[:agent_name]]
else
AgentConfig.cfg_agents
end
fail("No agents configured") if agent_names.empty?
# Perform command for each agent
count = 0
agent_names.each do |agent_name|
count += 1 if request_log_level(agent_name, command, options)
end
puts("No agents running") if count == 0
true
end | [
"def",
"manage",
"(",
"options",
")",
"# Initialize configuration directory setting",
"AgentConfig",
".",
"cfg_dir",
"=",
"options",
"[",
":cfg_dir",
"]",
"# Determine command",
"level",
"=",
"options",
"[",
":level",
"]",
"command",
"=",
"{",
":name",
"=>",
"(",
"level",
"?",
"'set_log_level'",
":",
"'get_log_level'",
")",
"}",
"command",
"[",
":level",
"]",
"=",
"level",
".",
"to_sym",
"if",
"level",
"# Determine candidate agents",
"agent_names",
"=",
"if",
"options",
"[",
":agent_name",
"]",
"[",
"options",
"[",
":agent_name",
"]",
"]",
"else",
"AgentConfig",
".",
"cfg_agents",
"end",
"fail",
"(",
"\"No agents configured\"",
")",
"if",
"agent_names",
".",
"empty?",
"# Perform command for each agent",
"count",
"=",
"0",
"agent_names",
".",
"each",
"do",
"|",
"agent_name",
"|",
"count",
"+=",
"1",
"if",
"request_log_level",
"(",
"agent_name",
",",
"command",
",",
"options",
")",
"end",
"puts",
"(",
"\"No agents running\"",
")",
"if",
"count",
"==",
"0",
"true",
"end"
] | Handle log level request
=== Parameters
options(Hash):: Command line options
=== Return
true:: Always return true | [
"Handle",
"log",
"level",
"request"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/scripts/log_level_manager.rb#L60-L84 |
643 | rightscale/right_agent | lib/right_agent/scripts/log_level_manager.rb | RightScale.LogLevelManager.request_log_level | def request_log_level(agent_name, command, options)
res = false
config_options = AgentConfig.agent_options(agent_name)
unless config_options.empty? || (listen_port = config_options[:listen_port]).nil?
fail("Could not retrieve #{agent_name} agent listen port") unless listen_port
client = CommandClient.new(listen_port, config_options[:cookie])
begin
client.send_command(command, options[:verbose], timeout = 5) do |level|
puts "Agent #{agent_name} log level: #{level.to_s.upcase}"
end
res = true
rescue Exception => e
puts "Command #{command.inspect} to #{agent_name} agent failed (#{e})"
end
end
res
end | ruby | def request_log_level(agent_name, command, options)
res = false
config_options = AgentConfig.agent_options(agent_name)
unless config_options.empty? || (listen_port = config_options[:listen_port]).nil?
fail("Could not retrieve #{agent_name} agent listen port") unless listen_port
client = CommandClient.new(listen_port, config_options[:cookie])
begin
client.send_command(command, options[:verbose], timeout = 5) do |level|
puts "Agent #{agent_name} log level: #{level.to_s.upcase}"
end
res = true
rescue Exception => e
puts "Command #{command.inspect} to #{agent_name} agent failed (#{e})"
end
end
res
end | [
"def",
"request_log_level",
"(",
"agent_name",
",",
"command",
",",
"options",
")",
"res",
"=",
"false",
"config_options",
"=",
"AgentConfig",
".",
"agent_options",
"(",
"agent_name",
")",
"unless",
"config_options",
".",
"empty?",
"||",
"(",
"listen_port",
"=",
"config_options",
"[",
":listen_port",
"]",
")",
".",
"nil?",
"fail",
"(",
"\"Could not retrieve #{agent_name} agent listen port\"",
")",
"unless",
"listen_port",
"client",
"=",
"CommandClient",
".",
"new",
"(",
"listen_port",
",",
"config_options",
"[",
":cookie",
"]",
")",
"begin",
"client",
".",
"send_command",
"(",
"command",
",",
"options",
"[",
":verbose",
"]",
",",
"timeout",
"=",
"5",
")",
"do",
"|",
"level",
"|",
"puts",
"\"Agent #{agent_name} log level: #{level.to_s.upcase}\"",
"end",
"res",
"=",
"true",
"rescue",
"Exception",
"=>",
"e",
"puts",
"\"Command #{command.inspect} to #{agent_name} agent failed (#{e})\"",
"end",
"end",
"res",
"end"
] | Send log level request to agent
=== Parameters
agent_name(String):: Agent name
command(String):: Command request
options(Hash):: Command line options
=== Return
(Boolean):: true if agent running, otherwise false | [
"Send",
"log",
"level",
"request",
"to",
"agent"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/scripts/log_level_manager.rb#L136-L152 |
644 | rightscale/right_agent | lib/right_agent/scripts/common_parser.rb | RightScale.CommonParser.parse_common | def parse_common(opts, options)
opts.on("--test") do
options[:user] = 'test'
options[:pass] = 'testing'
options[:vhost] = '/right_net'
options[:test] = true
options[:pid_dir] = Dir.tmpdir
options[:base_id] = "#{rand(1000000)}"
options[:options][:log_dir] = Dir.tmpdir
end
opts.on("-i", "--identity ID") do |id|
options[:base_id] = id
end
opts.on("-t", "--token TOKEN") do |t|
options[:token] = t
end
opts.on("-S", "--secure-identity") do
options[:secure_identity] = true
end
opts.on("-x", "--prefix PREFIX") do |p|
options[:prefix] = p
end
opts.on("--url URL") do |url|
uri = URI.parse(url)
options[:user] = uri.user if uri.user
options[:pass] = uri.password if uri.password
options[:host] = uri.host
options[:port] = uri.port if uri.port
options[:vhost] = uri.path if (uri.path && !uri.path.empty?)
end
opts.on("-u", "--user USER") do |user|
options[:user] = user
end
opts.on("-p", "--pass PASSWORD") do |pass|
options[:pass] = pass
end
opts.on("-v", "--vhost VHOST") do |vhost|
options[:vhost] = vhost
end
opts.on("-P", "--port PORT") do |port|
options[:port] = port
end
opts.on("-h", "--host HOST") do |host|
options[:host] = host
end
opts.on('--type TYPE') do |t|
options[:agent_type] = t
end
opts.on_tail("--help") do
puts Usage.scan(__FILE__)
exit
end
opts.on_tail("--version") do
puts version
exit
end
true
end | ruby | def parse_common(opts, options)
opts.on("--test") do
options[:user] = 'test'
options[:pass] = 'testing'
options[:vhost] = '/right_net'
options[:test] = true
options[:pid_dir] = Dir.tmpdir
options[:base_id] = "#{rand(1000000)}"
options[:options][:log_dir] = Dir.tmpdir
end
opts.on("-i", "--identity ID") do |id|
options[:base_id] = id
end
opts.on("-t", "--token TOKEN") do |t|
options[:token] = t
end
opts.on("-S", "--secure-identity") do
options[:secure_identity] = true
end
opts.on("-x", "--prefix PREFIX") do |p|
options[:prefix] = p
end
opts.on("--url URL") do |url|
uri = URI.parse(url)
options[:user] = uri.user if uri.user
options[:pass] = uri.password if uri.password
options[:host] = uri.host
options[:port] = uri.port if uri.port
options[:vhost] = uri.path if (uri.path && !uri.path.empty?)
end
opts.on("-u", "--user USER") do |user|
options[:user] = user
end
opts.on("-p", "--pass PASSWORD") do |pass|
options[:pass] = pass
end
opts.on("-v", "--vhost VHOST") do |vhost|
options[:vhost] = vhost
end
opts.on("-P", "--port PORT") do |port|
options[:port] = port
end
opts.on("-h", "--host HOST") do |host|
options[:host] = host
end
opts.on('--type TYPE') do |t|
options[:agent_type] = t
end
opts.on_tail("--help") do
puts Usage.scan(__FILE__)
exit
end
opts.on_tail("--version") do
puts version
exit
end
true
end | [
"def",
"parse_common",
"(",
"opts",
",",
"options",
")",
"opts",
".",
"on",
"(",
"\"--test\"",
")",
"do",
"options",
"[",
":user",
"]",
"=",
"'test'",
"options",
"[",
":pass",
"]",
"=",
"'testing'",
"options",
"[",
":vhost",
"]",
"=",
"'/right_net'",
"options",
"[",
":test",
"]",
"=",
"true",
"options",
"[",
":pid_dir",
"]",
"=",
"Dir",
".",
"tmpdir",
"options",
"[",
":base_id",
"]",
"=",
"\"#{rand(1000000)}\"",
"options",
"[",
":options",
"]",
"[",
":log_dir",
"]",
"=",
"Dir",
".",
"tmpdir",
"end",
"opts",
".",
"on",
"(",
"\"-i\"",
",",
"\"--identity ID\"",
")",
"do",
"|",
"id",
"|",
"options",
"[",
":base_id",
"]",
"=",
"id",
"end",
"opts",
".",
"on",
"(",
"\"-t\"",
",",
"\"--token TOKEN\"",
")",
"do",
"|",
"t",
"|",
"options",
"[",
":token",
"]",
"=",
"t",
"end",
"opts",
".",
"on",
"(",
"\"-S\"",
",",
"\"--secure-identity\"",
")",
"do",
"options",
"[",
":secure_identity",
"]",
"=",
"true",
"end",
"opts",
".",
"on",
"(",
"\"-x\"",
",",
"\"--prefix PREFIX\"",
")",
"do",
"|",
"p",
"|",
"options",
"[",
":prefix",
"]",
"=",
"p",
"end",
"opts",
".",
"on",
"(",
"\"--url URL\"",
")",
"do",
"|",
"url",
"|",
"uri",
"=",
"URI",
".",
"parse",
"(",
"url",
")",
"options",
"[",
":user",
"]",
"=",
"uri",
".",
"user",
"if",
"uri",
".",
"user",
"options",
"[",
":pass",
"]",
"=",
"uri",
".",
"password",
"if",
"uri",
".",
"password",
"options",
"[",
":host",
"]",
"=",
"uri",
".",
"host",
"options",
"[",
":port",
"]",
"=",
"uri",
".",
"port",
"if",
"uri",
".",
"port",
"options",
"[",
":vhost",
"]",
"=",
"uri",
".",
"path",
"if",
"(",
"uri",
".",
"path",
"&&",
"!",
"uri",
".",
"path",
".",
"empty?",
")",
"end",
"opts",
".",
"on",
"(",
"\"-u\"",
",",
"\"--user USER\"",
")",
"do",
"|",
"user",
"|",
"options",
"[",
":user",
"]",
"=",
"user",
"end",
"opts",
".",
"on",
"(",
"\"-p\"",
",",
"\"--pass PASSWORD\"",
")",
"do",
"|",
"pass",
"|",
"options",
"[",
":pass",
"]",
"=",
"pass",
"end",
"opts",
".",
"on",
"(",
"\"-v\"",
",",
"\"--vhost VHOST\"",
")",
"do",
"|",
"vhost",
"|",
"options",
"[",
":vhost",
"]",
"=",
"vhost",
"end",
"opts",
".",
"on",
"(",
"\"-P\"",
",",
"\"--port PORT\"",
")",
"do",
"|",
"port",
"|",
"options",
"[",
":port",
"]",
"=",
"port",
"end",
"opts",
".",
"on",
"(",
"\"-h\"",
",",
"\"--host HOST\"",
")",
"do",
"|",
"host",
"|",
"options",
"[",
":host",
"]",
"=",
"host",
"end",
"opts",
".",
"on",
"(",
"'--type TYPE'",
")",
"do",
"|",
"t",
"|",
"options",
"[",
":agent_type",
"]",
"=",
"t",
"end",
"opts",
".",
"on_tail",
"(",
"\"--help\"",
")",
"do",
"puts",
"Usage",
".",
"scan",
"(",
"__FILE__",
")",
"exit",
"end",
"opts",
".",
"on_tail",
"(",
"\"--version\"",
")",
"do",
"puts",
"version",
"exit",
"end",
"true",
"end"
] | Parse common options between rad and rnac
=== Parameters
opts(OptionParser):: Options parser with options to be parsed
options(Hash):: Storage for options that are parsed
=== Return
true:: Always return true | [
"Parse",
"common",
"options",
"between",
"rad",
"and",
"rnac"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/scripts/common_parser.rb#L41-L112 |
645 | rightscale/right_agent | lib/right_agent/scripts/common_parser.rb | RightScale.CommonParser.resolve_identity | def resolve_identity(options)
options[:agent_type] = agent_type(options[:agent_type], options[:agent_name])
if options[:base_id]
base_id = options[:base_id].to_i
if base_id.abs.to_s != options[:base_id]
puts "** Identity needs to be a positive integer"
exit(1)
end
token = if options[:secure_identity]
RightScale::SecureIdentity.derive(base_id, options[:token])
else
options[:token]
end
options[:identity] = AgentIdentity.new(options[:prefix] || 'rs', options[:agent_type], base_id, token).to_s
end
end | ruby | def resolve_identity(options)
options[:agent_type] = agent_type(options[:agent_type], options[:agent_name])
if options[:base_id]
base_id = options[:base_id].to_i
if base_id.abs.to_s != options[:base_id]
puts "** Identity needs to be a positive integer"
exit(1)
end
token = if options[:secure_identity]
RightScale::SecureIdentity.derive(base_id, options[:token])
else
options[:token]
end
options[:identity] = AgentIdentity.new(options[:prefix] || 'rs', options[:agent_type], base_id, token).to_s
end
end | [
"def",
"resolve_identity",
"(",
"options",
")",
"options",
"[",
":agent_type",
"]",
"=",
"agent_type",
"(",
"options",
"[",
":agent_type",
"]",
",",
"options",
"[",
":agent_name",
"]",
")",
"if",
"options",
"[",
":base_id",
"]",
"base_id",
"=",
"options",
"[",
":base_id",
"]",
".",
"to_i",
"if",
"base_id",
".",
"abs",
".",
"to_s",
"!=",
"options",
"[",
":base_id",
"]",
"puts",
"\"** Identity needs to be a positive integer\"",
"exit",
"(",
"1",
")",
"end",
"token",
"=",
"if",
"options",
"[",
":secure_identity",
"]",
"RightScale",
"::",
"SecureIdentity",
".",
"derive",
"(",
"base_id",
",",
"options",
"[",
":token",
"]",
")",
"else",
"options",
"[",
":token",
"]",
"end",
"options",
"[",
":identity",
"]",
"=",
"AgentIdentity",
".",
"new",
"(",
"options",
"[",
":prefix",
"]",
"||",
"'rs'",
",",
"options",
"[",
":agent_type",
"]",
",",
"base_id",
",",
"token",
")",
".",
"to_s",
"end",
"end"
] | Generate agent identity from options
Build identity from base_id, token, prefix and agent name
=== Parameters
options(Hash):: Hash containing identity components
=== Return
options(Hash):: | [
"Generate",
"agent",
"identity",
"from",
"options",
"Build",
"identity",
"from",
"base_id",
"token",
"prefix",
"and",
"agent",
"name"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/scripts/common_parser.rb#L122-L137 |
646 | rightscale/right_agent | lib/right_agent/scripts/common_parser.rb | RightScale.CommonParser.agent_type | def agent_type(type, name)
unless type
if name =~ /^(.*)_[0-9]+$/
type = Regexp.last_match(1)
else
type = name || "instance"
end
end
type
end | ruby | def agent_type(type, name)
unless type
if name =~ /^(.*)_[0-9]+$/
type = Regexp.last_match(1)
else
type = name || "instance"
end
end
type
end | [
"def",
"agent_type",
"(",
"type",
",",
"name",
")",
"unless",
"type",
"if",
"name",
"=~",
"/",
"/",
"type",
"=",
"Regexp",
".",
"last_match",
"(",
"1",
")",
"else",
"type",
"=",
"name",
"||",
"\"instance\"",
"end",
"end",
"type",
"end"
] | Determine agent type
=== Parameters
type(String):: Agent type
name(String):: Agent name
=== Return
(String):: Agent type | [
"Determine",
"agent",
"type"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/scripts/common_parser.rb#L147-L156 |
647 | rightscale/right_agent | lib/right_agent/actor_registry.rb | RightScale.ActorRegistry.register | def register(actor, prefix)
raise ArgumentError, "#{actor.inspect} is not a RightScale::Actor subclass instance" unless RightScale::Actor === actor
log_msg = "[actor] #{actor.class.to_s}"
log_msg += ", prefix #{prefix}" if prefix && !prefix.empty?
Log.info(log_msg)
prefix ||= actor.class.default_prefix
@actors[prefix.to_s] = actor
end | ruby | def register(actor, prefix)
raise ArgumentError, "#{actor.inspect} is not a RightScale::Actor subclass instance" unless RightScale::Actor === actor
log_msg = "[actor] #{actor.class.to_s}"
log_msg += ", prefix #{prefix}" if prefix && !prefix.empty?
Log.info(log_msg)
prefix ||= actor.class.default_prefix
@actors[prefix.to_s] = actor
end | [
"def",
"register",
"(",
"actor",
",",
"prefix",
")",
"raise",
"ArgumentError",
",",
"\"#{actor.inspect} is not a RightScale::Actor subclass instance\"",
"unless",
"RightScale",
"::",
"Actor",
"===",
"actor",
"log_msg",
"=",
"\"[actor] #{actor.class.to_s}\"",
"log_msg",
"+=",
"\", prefix #{prefix}\"",
"if",
"prefix",
"&&",
"!",
"prefix",
".",
"empty?",
"Log",
".",
"info",
"(",
"log_msg",
")",
"prefix",
"||=",
"actor",
".",
"class",
".",
"default_prefix",
"@actors",
"[",
"prefix",
".",
"to_s",
"]",
"=",
"actor",
"end"
] | Initialize registry
Register as an actor
=== Parameters
actor(Actor):: Actor to be registered
prefix(String):: Prefix used in request to identify actor
=== Return
(Actor):: Actor registered
=== Raises
ArgumentError if actor is not an Actor | [
"Initialize",
"registry",
"Register",
"as",
"an",
"actor"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/actor_registry.rb#L46-L53 |
648 | rightscale/right_agent | lib/right_agent/security/certificate_cache.rb | RightScale.CertificateCache.put | def put(key, item)
if @items.include?(key)
delete(key)
end
if @list.size == @max_count
delete(@list.first)
end
@items[key] = item
@list.push(key)
item
end | ruby | def put(key, item)
if @items.include?(key)
delete(key)
end
if @list.size == @max_count
delete(@list.first)
end
@items[key] = item
@list.push(key)
item
end | [
"def",
"put",
"(",
"key",
",",
"item",
")",
"if",
"@items",
".",
"include?",
"(",
"key",
")",
"delete",
"(",
"key",
")",
"end",
"if",
"@list",
".",
"size",
"==",
"@max_count",
"delete",
"(",
"@list",
".",
"first",
")",
"end",
"@items",
"[",
"key",
"]",
"=",
"item",
"@list",
".",
"push",
"(",
"key",
")",
"item",
"end"
] | Initialize cache
Add item to cache | [
"Initialize",
"cache",
"Add",
"item",
"to",
"cache"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/security/certificate_cache.rb#L40-L50 |
649 | rightscale/right_agent | lib/right_agent/security/certificate_cache.rb | RightScale.CertificateCache.get | def get(key)
if @items.include?(key)
@list.each_index do |i|
if @list[i] == key
@list.delete_at(i)
break
end
end
@list.push(key)
@items[key]
else
return nil unless block_given?
self[key] = yield
end
end | ruby | def get(key)
if @items.include?(key)
@list.each_index do |i|
if @list[i] == key
@list.delete_at(i)
break
end
end
@list.push(key)
@items[key]
else
return nil unless block_given?
self[key] = yield
end
end | [
"def",
"get",
"(",
"key",
")",
"if",
"@items",
".",
"include?",
"(",
"key",
")",
"@list",
".",
"each_index",
"do",
"|",
"i",
"|",
"if",
"@list",
"[",
"i",
"]",
"==",
"key",
"@list",
".",
"delete_at",
"(",
"i",
")",
"break",
"end",
"end",
"@list",
".",
"push",
"(",
"key",
")",
"@items",
"[",
"key",
"]",
"else",
"return",
"nil",
"unless",
"block_given?",
"self",
"[",
"key",
"]",
"=",
"yield",
"end",
"end"
] | Retrieve item from cache
Store item returned by given block if any | [
"Retrieve",
"item",
"from",
"cache",
"Store",
"item",
"returned",
"by",
"given",
"block",
"if",
"any"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/security/certificate_cache.rb#L55-L69 |
650 | rightscale/right_agent | lib/right_agent/security/certificate_cache.rb | RightScale.CertificateCache.delete | def delete(key)
c = @items[key]
if c
@items.delete(key)
@list.each_index do |i|
if @list[i] == key
@list.delete_at(i)
break
end
end
c
end
end | ruby | def delete(key)
c = @items[key]
if c
@items.delete(key)
@list.each_index do |i|
if @list[i] == key
@list.delete_at(i)
break
end
end
c
end
end | [
"def",
"delete",
"(",
"key",
")",
"c",
"=",
"@items",
"[",
"key",
"]",
"if",
"c",
"@items",
".",
"delete",
"(",
"key",
")",
"@list",
".",
"each_index",
"do",
"|",
"i",
"|",
"if",
"@list",
"[",
"i",
"]",
"==",
"key",
"@list",
".",
"delete_at",
"(",
"i",
")",
"break",
"end",
"end",
"c",
"end",
"end"
] | Delete item from cache | [
"Delete",
"item",
"from",
"cache"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/security/certificate_cache.rb#L73-L85 |
651 | rightscale/right_agent | lib/right_agent/clients/balanced_http_client.rb | RightScale.BalancedHttpClient.check_health | def check_health(host = nil)
begin
@http_client.health_check_proc.call(host || @urls.first)
rescue StandardError => e
if e.respond_to?(:http_code) && RETRY_STATUS_CODES.include?(e.http_code)
raise NotResponding.new("#{@server_name || host} not responding", e)
else
raise
end
end
end | ruby | def check_health(host = nil)
begin
@http_client.health_check_proc.call(host || @urls.first)
rescue StandardError => e
if e.respond_to?(:http_code) && RETRY_STATUS_CODES.include?(e.http_code)
raise NotResponding.new("#{@server_name || host} not responding", e)
else
raise
end
end
end | [
"def",
"check_health",
"(",
"host",
"=",
"nil",
")",
"begin",
"@http_client",
".",
"health_check_proc",
".",
"call",
"(",
"host",
"||",
"@urls",
".",
"first",
")",
"rescue",
"StandardError",
"=>",
"e",
"if",
"e",
".",
"respond_to?",
"(",
":http_code",
")",
"&&",
"RETRY_STATUS_CODES",
".",
"include?",
"(",
"e",
".",
"http_code",
")",
"raise",
"NotResponding",
".",
"new",
"(",
"\"#{@server_name || host} not responding\"",
",",
"e",
")",
"else",
"raise",
"end",
"end",
"end"
] | Create client for making HTTP REST requests
@param [Array, String] urls of server being accessed as array or comma-separated string
@option options [String] :api_version for X-API-Version header
@option options [String] :server_name of server for use in exceptions; defaults to host name
@option options [String] :health_check_path in URI for health check resource;
defaults to DEFAULT_HEALTH_CHECK_PATH
@option options [Array] :filter_params symbols or strings for names of request parameters
whose values are to be hidden when logging; also applied to contents of any parameters
in CONTENT_FILTERED_PARAMS; can be augmented on individual requests
@option options [Boolean] :non_blocking i/o is to be used for HTTP requests by applying
EM::HttpRequest and fibers instead of RestClient; requests remain synchronous
Check health of server
@param [String] host name of server
@return [Object] health check result from server
@raise [NotResponding] server is not responding | [
"Create",
"client",
"for",
"making",
"HTTP",
"REST",
"requests"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/balanced_http_client.rb#L102-L112 |
652 | rightscale/right_agent | lib/right_agent/clients/balanced_http_client.rb | RightScale.BalancedHttpClient.request_headers | def request_headers(request_uuid, options)
headers = {"X-Request-Lineage-Uuid" => request_uuid, :accept => "application/json"}
headers["X-API-Version"] = @api_version if @api_version
headers.merge!(options[:headers]) if options[:headers]
headers["X-DEBUG"] = true if Log.level == :debug
headers
end | ruby | def request_headers(request_uuid, options)
headers = {"X-Request-Lineage-Uuid" => request_uuid, :accept => "application/json"}
headers["X-API-Version"] = @api_version if @api_version
headers.merge!(options[:headers]) if options[:headers]
headers["X-DEBUG"] = true if Log.level == :debug
headers
end | [
"def",
"request_headers",
"(",
"request_uuid",
",",
"options",
")",
"headers",
"=",
"{",
"\"X-Request-Lineage-Uuid\"",
"=>",
"request_uuid",
",",
":accept",
"=>",
"\"application/json\"",
"}",
"headers",
"[",
"\"X-API-Version\"",
"]",
"=",
"@api_version",
"if",
"@api_version",
"headers",
".",
"merge!",
"(",
"options",
"[",
":headers",
"]",
")",
"if",
"options",
"[",
":headers",
"]",
"headers",
"[",
"\"X-DEBUG\"",
"]",
"=",
"true",
"if",
"Log",
".",
"level",
"==",
":debug",
"headers",
"end"
] | Construct headers for request
@param [String] request_uuid uniquely identifying request
@param [Hash] options per #request
@return [Hash] headers for request | [
"Construct",
"headers",
"for",
"request"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/balanced_http_client.rb#L208-L214 |
653 | rightscale/right_agent | lib/right_agent/clients/balanced_http_client.rb | RightScale.BalancedHttpClient.rest_request | def rest_request(verb, path, connect_options, request_options, used)
result, code, body, headers = @balancer.request do |host|
uri = URI.parse(host)
uri.user = uri.password = nil
used[:host] = uri.to_s
@http_client.request(verb, path, host, connect_options, request_options)
end
[result, code, body, headers]
end | ruby | def rest_request(verb, path, connect_options, request_options, used)
result, code, body, headers = @balancer.request do |host|
uri = URI.parse(host)
uri.user = uri.password = nil
used[:host] = uri.to_s
@http_client.request(verb, path, host, connect_options, request_options)
end
[result, code, body, headers]
end | [
"def",
"rest_request",
"(",
"verb",
",",
"path",
",",
"connect_options",
",",
"request_options",
",",
"used",
")",
"result",
",",
"code",
",",
"body",
",",
"headers",
"=",
"@balancer",
".",
"request",
"do",
"|",
"host",
"|",
"uri",
"=",
"URI",
".",
"parse",
"(",
"host",
")",
"uri",
".",
"user",
"=",
"uri",
".",
"password",
"=",
"nil",
"used",
"[",
":host",
"]",
"=",
"uri",
".",
"to_s",
"@http_client",
".",
"request",
"(",
"verb",
",",
"path",
",",
"host",
",",
"connect_options",
",",
"request_options",
")",
"end",
"[",
"result",
",",
"code",
",",
"body",
",",
"headers",
"]",
"end"
] | Make REST request
@param [Symbol] verb for HTTP REST request
@param [String] path in URI for desired resource
@param [Hash] connect_options for HTTP connection
@param [Hash] request_options for HTTP request
@param [Hash] used container for returning :host used for request;
needed so that can return it even when the request fails with an exception
@return [Array] result to be returned followed by response code, body, and headers
@raise [NotResponding] server not responding, recommend retry
@raise [HttpException] HTTP failure with associated status code | [
"Make",
"REST",
"request"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/balanced_http_client.rb#L229-L237 |
654 | rightscale/right_agent | lib/right_agent/clients/balanced_http_client.rb | RightScale.BalancedHttpClient.poll_request | def poll_request(path, connect_options, request_options, request_timeout, started_at, used)
result = code = body = headers = nil
if (connection = @http_client.connections[path]).nil? || Time.now >= connection[:expires_at]
# Use normal :get request using request balancer for first poll
result, code, body, headers = rest_request(:get, path, connect_options, request_options.dup, used)
return [result, code, body, headers] if (Time.now - started_at) >= request_timeout
end
if result.nil? && (connection = @http_client.connections[path]) && Time.now < connection[:expires_at]
begin
# Continue to poll using same connection until get result, timeout, or hit error
used[:host] = connection[:host]
result, code, body, headers = @http_client.poll(connection, request_options, started_at + request_timeout)
rescue HttpException, RestClient::Exception => e
raise NotResponding.new(e.http_body, e) if RETRY_STATUS_CODES.include?(e.http_code)
raise NotResponding.new("Request timeout", e) if e.is_a?(RestClient::RequestTimeout)
raise
end
end
[result, code, body, headers]
end | ruby | def poll_request(path, connect_options, request_options, request_timeout, started_at, used)
result = code = body = headers = nil
if (connection = @http_client.connections[path]).nil? || Time.now >= connection[:expires_at]
# Use normal :get request using request balancer for first poll
result, code, body, headers = rest_request(:get, path, connect_options, request_options.dup, used)
return [result, code, body, headers] if (Time.now - started_at) >= request_timeout
end
if result.nil? && (connection = @http_client.connections[path]) && Time.now < connection[:expires_at]
begin
# Continue to poll using same connection until get result, timeout, or hit error
used[:host] = connection[:host]
result, code, body, headers = @http_client.poll(connection, request_options, started_at + request_timeout)
rescue HttpException, RestClient::Exception => e
raise NotResponding.new(e.http_body, e) if RETRY_STATUS_CODES.include?(e.http_code)
raise NotResponding.new("Request timeout", e) if e.is_a?(RestClient::RequestTimeout)
raise
end
end
[result, code, body, headers]
end | [
"def",
"poll_request",
"(",
"path",
",",
"connect_options",
",",
"request_options",
",",
"request_timeout",
",",
"started_at",
",",
"used",
")",
"result",
"=",
"code",
"=",
"body",
"=",
"headers",
"=",
"nil",
"if",
"(",
"connection",
"=",
"@http_client",
".",
"connections",
"[",
"path",
"]",
")",
".",
"nil?",
"||",
"Time",
".",
"now",
">=",
"connection",
"[",
":expires_at",
"]",
"# Use normal :get request using request balancer for first poll",
"result",
",",
"code",
",",
"body",
",",
"headers",
"=",
"rest_request",
"(",
":get",
",",
"path",
",",
"connect_options",
",",
"request_options",
".",
"dup",
",",
"used",
")",
"return",
"[",
"result",
",",
"code",
",",
"body",
",",
"headers",
"]",
"if",
"(",
"Time",
".",
"now",
"-",
"started_at",
")",
">=",
"request_timeout",
"end",
"if",
"result",
".",
"nil?",
"&&",
"(",
"connection",
"=",
"@http_client",
".",
"connections",
"[",
"path",
"]",
")",
"&&",
"Time",
".",
"now",
"<",
"connection",
"[",
":expires_at",
"]",
"begin",
"# Continue to poll using same connection until get result, timeout, or hit error",
"used",
"[",
":host",
"]",
"=",
"connection",
"[",
":host",
"]",
"result",
",",
"code",
",",
"body",
",",
"headers",
"=",
"@http_client",
".",
"poll",
"(",
"connection",
",",
"request_options",
",",
"started_at",
"+",
"request_timeout",
")",
"rescue",
"HttpException",
",",
"RestClient",
"::",
"Exception",
"=>",
"e",
"raise",
"NotResponding",
".",
"new",
"(",
"e",
".",
"http_body",
",",
"e",
")",
"if",
"RETRY_STATUS_CODES",
".",
"include?",
"(",
"e",
".",
"http_code",
")",
"raise",
"NotResponding",
".",
"new",
"(",
"\"Request timeout\"",
",",
"e",
")",
"if",
"e",
".",
"is_a?",
"(",
"RestClient",
"::",
"RequestTimeout",
")",
"raise",
"end",
"end",
"[",
"result",
",",
"code",
",",
"body",
",",
"headers",
"]",
"end"
] | Make long-polling request
@param [String] path in URI for desired resource
@param [Hash] connect_options for HTTP connection
@param [Hash] request_options for HTTP request
@param [Integer] request_timeout for a non-nil result
@param [Time] started_at time for request
@param [Hash] used container for returning :host used for request;
needed so that can return it even when the request fails with an exception
@return [Array] result to be returned followed by response code, body, and headers
@raise [NotResponding] server not responding, recommend retry
@raise [HttpException] HTTP failure with associated status code | [
"Make",
"long",
"-",
"polling",
"request"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/balanced_http_client.rb#L253-L272 |
655 | rightscale/right_agent | lib/right_agent/clients/balanced_http_client.rb | RightScale.BalancedHttpClient.handle_no_result | def handle_no_result(no_result, host)
server_name = @server_name || host
e = no_result.details.values.flatten.last
if no_result.details.empty?
yield(no_result)
raise NotResponding.new("#{server_name} not responding", no_result)
elsif e.respond_to?(:http_code) && RETRY_STATUS_CODES.include?(e.http_code)
yield(e)
if e.http_code == 504 && (e.http_body && !e.http_body.empty?)
raise NotResponding.new(e.http_body, e)
else
raise NotResponding.new("#{server_name} not responding", e)
end
elsif e.is_a?(RestClient::RequestTimeout)
# Special case RequestTimeout because http_code is typically nil given no actual response
yield(e)
raise NotResponding.new("Request timeout", e)
else
yield(e)
raise e
end
true
end | ruby | def handle_no_result(no_result, host)
server_name = @server_name || host
e = no_result.details.values.flatten.last
if no_result.details.empty?
yield(no_result)
raise NotResponding.new("#{server_name} not responding", no_result)
elsif e.respond_to?(:http_code) && RETRY_STATUS_CODES.include?(e.http_code)
yield(e)
if e.http_code == 504 && (e.http_body && !e.http_body.empty?)
raise NotResponding.new(e.http_body, e)
else
raise NotResponding.new("#{server_name} not responding", e)
end
elsif e.is_a?(RestClient::RequestTimeout)
# Special case RequestTimeout because http_code is typically nil given no actual response
yield(e)
raise NotResponding.new("Request timeout", e)
else
yield(e)
raise e
end
true
end | [
"def",
"handle_no_result",
"(",
"no_result",
",",
"host",
")",
"server_name",
"=",
"@server_name",
"||",
"host",
"e",
"=",
"no_result",
".",
"details",
".",
"values",
".",
"flatten",
".",
"last",
"if",
"no_result",
".",
"details",
".",
"empty?",
"yield",
"(",
"no_result",
")",
"raise",
"NotResponding",
".",
"new",
"(",
"\"#{server_name} not responding\"",
",",
"no_result",
")",
"elsif",
"e",
".",
"respond_to?",
"(",
":http_code",
")",
"&&",
"RETRY_STATUS_CODES",
".",
"include?",
"(",
"e",
".",
"http_code",
")",
"yield",
"(",
"e",
")",
"if",
"e",
".",
"http_code",
"==",
"504",
"&&",
"(",
"e",
".",
"http_body",
"&&",
"!",
"e",
".",
"http_body",
".",
"empty?",
")",
"raise",
"NotResponding",
".",
"new",
"(",
"e",
".",
"http_body",
",",
"e",
")",
"else",
"raise",
"NotResponding",
".",
"new",
"(",
"\"#{server_name} not responding\"",
",",
"e",
")",
"end",
"elsif",
"e",
".",
"is_a?",
"(",
"RestClient",
"::",
"RequestTimeout",
")",
"# Special case RequestTimeout because http_code is typically nil given no actual response",
"yield",
"(",
"e",
")",
"raise",
"NotResponding",
".",
"new",
"(",
"\"Request timeout\"",
",",
"e",
")",
"else",
"yield",
"(",
"e",
")",
"raise",
"e",
"end",
"true",
"end"
] | Handle no result from balancer
Distinguish the not responding case since it likely warrants a retry by the client
Also try to distinguish between the targeted server not responding and that server
gatewaying to another server that is not responding, so that the receiver of
the resulting exception is clearer as to the source of the problem
@param [RightSupport::Net::NoResult] no_result exception raised by request balancer when it
could not deliver request
@param [String] host server URL where request was attempted
@yield [exception] required block called for reporting exception of interest
@yieldparam [Exception] exception extracted
@return [TrueClass] always true
@raise [NotResponding] server not responding, recommend retry | [
"Handle",
"no",
"result",
"from",
"balancer",
"Distinguish",
"the",
"not",
"responding",
"case",
"since",
"it",
"likely",
"warrants",
"a",
"retry",
"by",
"the",
"client",
"Also",
"try",
"to",
"distinguish",
"between",
"the",
"targeted",
"server",
"not",
"responding",
"and",
"that",
"server",
"gatewaying",
"to",
"another",
"server",
"that",
"is",
"not",
"responding",
"so",
"that",
"the",
"receiver",
"of",
"the",
"resulting",
"exception",
"is",
"clearer",
"as",
"to",
"the",
"source",
"of",
"the",
"problem"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/balanced_http_client.rb#L290-L312 |
656 | rightscale/right_agent | lib/right_agent/clients/balanced_http_client.rb | RightScale.BalancedHttpClient.log_success | def log_success(result, code, body, headers, host, path, request_uuid, started_at, log_level)
length = (headers && headers[:content_length]) || (body && body.size) || "-"
duration = "%.0fms" % ((Time.now - started_at) * 1000)
completed = "Completed <#{request_uuid}> in #{duration} | #{code || "nil"} [#{host}#{path}] | #{length} bytes"
completed << " | #{result.inspect}" if Log.level == :debug
Log.send(log_level, completed)
true
end | ruby | def log_success(result, code, body, headers, host, path, request_uuid, started_at, log_level)
length = (headers && headers[:content_length]) || (body && body.size) || "-"
duration = "%.0fms" % ((Time.now - started_at) * 1000)
completed = "Completed <#{request_uuid}> in #{duration} | #{code || "nil"} [#{host}#{path}] | #{length} bytes"
completed << " | #{result.inspect}" if Log.level == :debug
Log.send(log_level, completed)
true
end | [
"def",
"log_success",
"(",
"result",
",",
"code",
",",
"body",
",",
"headers",
",",
"host",
",",
"path",
",",
"request_uuid",
",",
"started_at",
",",
"log_level",
")",
"length",
"=",
"(",
"headers",
"&&",
"headers",
"[",
":content_length",
"]",
")",
"||",
"(",
"body",
"&&",
"body",
".",
"size",
")",
"||",
"\"-\"",
"duration",
"=",
"\"%.0fms\"",
"%",
"(",
"(",
"Time",
".",
"now",
"-",
"started_at",
")",
"*",
"1000",
")",
"completed",
"=",
"\"Completed <#{request_uuid}> in #{duration} | #{code || \"nil\"} [#{host}#{path}] | #{length} bytes\"",
"completed",
"<<",
"\" | #{result.inspect}\"",
"if",
"Log",
".",
"level",
"==",
":debug",
"Log",
".",
"send",
"(",
"log_level",
",",
"completed",
")",
"true",
"end"
] | Log successful request completion
@param [Object] result to be returned to client
@param [Integer, NilClass] code for response status
@param [Object] body of response
@param [Hash] headers for response
@param [String] host server URL where request was completed
@param [String] path in URI for desired resource
@param [String] request_uuid uniquely identifying request
@param [Time] started_at time for request
@param [Symbol] log_level to use when logging information about the request
other than errors
@return [TrueClass] always true | [
"Log",
"successful",
"request",
"completion"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/balanced_http_client.rb#L328-L335 |
657 | rightscale/right_agent | lib/right_agent/clients/balanced_http_client.rb | RightScale.BalancedHttpClient.log_failure | def log_failure(host, path, params, filter, request_uuid, started_at, exception)
code = exception.respond_to?(:http_code) ? exception.http_code : "nil"
duration = "%.0fms" % ((Time.now - started_at) * 1000)
ErrorTracker.log(self, "Failed <#{request_uuid}> in #{duration} | #{code} " + log_text(path, params, filter, host, exception))
true
end | ruby | def log_failure(host, path, params, filter, request_uuid, started_at, exception)
code = exception.respond_to?(:http_code) ? exception.http_code : "nil"
duration = "%.0fms" % ((Time.now - started_at) * 1000)
ErrorTracker.log(self, "Failed <#{request_uuid}> in #{duration} | #{code} " + log_text(path, params, filter, host, exception))
true
end | [
"def",
"log_failure",
"(",
"host",
",",
"path",
",",
"params",
",",
"filter",
",",
"request_uuid",
",",
"started_at",
",",
"exception",
")",
"code",
"=",
"exception",
".",
"respond_to?",
"(",
":http_code",
")",
"?",
"exception",
".",
"http_code",
":",
"\"nil\"",
"duration",
"=",
"\"%.0fms\"",
"%",
"(",
"(",
"Time",
".",
"now",
"-",
"started_at",
")",
"*",
"1000",
")",
"ErrorTracker",
".",
"log",
"(",
"self",
",",
"\"Failed <#{request_uuid}> in #{duration} | #{code} \"",
"+",
"log_text",
"(",
"path",
",",
"params",
",",
"filter",
",",
"host",
",",
"exception",
")",
")",
"true",
"end"
] | Log request failure
Also report it as audit entry if an instance is targeted
@param [String] host server URL where request was attempted if known
@param [String] path in URI for desired resource
@param [Hash] params for request
@param [Array] filter list of parameters whose value is to be hidden
@param [String] request_uuid uniquely identifying request
@param [Time] started_at time for request
@param [Exception, String] exception or message that should be logged
@return [TrueClass] Always return true | [
"Log",
"request",
"failure",
"Also",
"report",
"it",
"as",
"audit",
"entry",
"if",
"an",
"instance",
"is",
"targeted"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/balanced_http_client.rb#L349-L354 |
658 | rightscale/right_agent | lib/right_agent/clients/balanced_http_client.rb | RightScale.BalancedHttpClient.log_text | def log_text(path, params, filter, host = nil, exception = nil)
text = "#{path} #{filter(params, filter).inspect}"
text = "[#{host}#{text}]" if host
text << " | #{self.class.exception_text(exception)}" if exception
text
end | ruby | def log_text(path, params, filter, host = nil, exception = nil)
text = "#{path} #{filter(params, filter).inspect}"
text = "[#{host}#{text}]" if host
text << " | #{self.class.exception_text(exception)}" if exception
text
end | [
"def",
"log_text",
"(",
"path",
",",
"params",
",",
"filter",
",",
"host",
"=",
"nil",
",",
"exception",
"=",
"nil",
")",
"text",
"=",
"\"#{path} #{filter(params, filter).inspect}\"",
"text",
"=",
"\"[#{host}#{text}]\"",
"if",
"host",
"text",
"<<",
"\" | #{self.class.exception_text(exception)}\"",
"if",
"exception",
"text",
"end"
] | Generate log text describing request and failure if any
@param [String] path in URI for desired resource
@param [Hash] params for HTTP request
@param [Array, NilClass] filter augmentation to base filter list
@param [String] host server URL where request was attempted if known
@param [Exception, String, NilClass] exception or failure message that should be logged
@return [String] Log text | [
"Generate",
"log",
"text",
"describing",
"request",
"and",
"failure",
"if",
"any"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/balanced_http_client.rb#L365-L370 |
659 | rightscale/right_agent | lib/right_agent/clients/balanced_http_client.rb | RightScale.BalancedHttpClient.filter | def filter(params, filter)
if filter.empty? || !params.is_a?(Hash)
params
else
filtered_params = {}
params.each do |k, p|
s = k.to_s
if filter.include?(s)
filtered_params[k] = FILTERED_PARAM_VALUE
else
filtered_params[k] = CONTENT_FILTERED_PARAMS.include?(s) ? filter(p, filter) : p
end
end
filtered_params
end
end | ruby | def filter(params, filter)
if filter.empty? || !params.is_a?(Hash)
params
else
filtered_params = {}
params.each do |k, p|
s = k.to_s
if filter.include?(s)
filtered_params[k] = FILTERED_PARAM_VALUE
else
filtered_params[k] = CONTENT_FILTERED_PARAMS.include?(s) ? filter(p, filter) : p
end
end
filtered_params
end
end | [
"def",
"filter",
"(",
"params",
",",
"filter",
")",
"if",
"filter",
".",
"empty?",
"||",
"!",
"params",
".",
"is_a?",
"(",
"Hash",
")",
"params",
"else",
"filtered_params",
"=",
"{",
"}",
"params",
".",
"each",
"do",
"|",
"k",
",",
"p",
"|",
"s",
"=",
"k",
".",
"to_s",
"if",
"filter",
".",
"include?",
"(",
"s",
")",
"filtered_params",
"[",
"k",
"]",
"=",
"FILTERED_PARAM_VALUE",
"else",
"filtered_params",
"[",
"k",
"]",
"=",
"CONTENT_FILTERED_PARAMS",
".",
"include?",
"(",
"s",
")",
"?",
"filter",
"(",
"p",
",",
"filter",
")",
":",
"p",
"end",
"end",
"filtered_params",
"end",
"end"
] | Apply parameter hiding filter
@param [Hash, Object] params to be filtered with strings or symbols as keys
@param [Array] filter names of params as strings (not symbols) whose value is to be hidden;
also filter the contents of any CONTENT_FILTERED_PARAMS
@return [Hash] filtered parameters | [
"Apply",
"parameter",
"hiding",
"filter"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/balanced_http_client.rb#L379-L394 |
660 | rightscale/right_agent | lib/right_agent/clients/balanced_http_client.rb | RightScale.BalancedHttpClient.split | def split(object, pattern = /,\s*/)
object ? (object.is_a?(Array) ? object : object.split(pattern)) : []
end | ruby | def split(object, pattern = /,\s*/)
object ? (object.is_a?(Array) ? object : object.split(pattern)) : []
end | [
"def",
"split",
"(",
"object",
",",
"pattern",
"=",
"/",
"\\s",
"/",
")",
"object",
"?",
"(",
"object",
".",
"is_a?",
"(",
"Array",
")",
"?",
"object",
":",
"object",
".",
"split",
"(",
"pattern",
")",
")",
":",
"[",
"]",
"end"
] | Split string into an array unless nil or already an array
@param [String, Array, NilClass] object to be split
@param [String, Regex] pattern on which to split; defaults to comma
@return [Array] split object | [
"Split",
"string",
"into",
"an",
"array",
"unless",
"nil",
"or",
"already",
"an",
"array"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/balanced_http_client.rb#L402-L404 |
661 | rightscale/right_agent | lib/right_agent/scripts/stats_manager.rb | RightScale.StatsManager.manage | def manage(options)
init_log if options[:verbose]
AgentConfig.cfg_dir = options[:cfg_dir]
options[:timeout] ||= DEFAULT_TIMEOUT
request_stats(options)
rescue Exception => e
fail("#{e}\n#{e.backtrace.join("\n")}") unless e.is_a?(SystemExit)
end | ruby | def manage(options)
init_log if options[:verbose]
AgentConfig.cfg_dir = options[:cfg_dir]
options[:timeout] ||= DEFAULT_TIMEOUT
request_stats(options)
rescue Exception => e
fail("#{e}\n#{e.backtrace.join("\n")}") unless e.is_a?(SystemExit)
end | [
"def",
"manage",
"(",
"options",
")",
"init_log",
"if",
"options",
"[",
":verbose",
"]",
"AgentConfig",
".",
"cfg_dir",
"=",
"options",
"[",
":cfg_dir",
"]",
"options",
"[",
":timeout",
"]",
"||=",
"DEFAULT_TIMEOUT",
"request_stats",
"(",
"options",
")",
"rescue",
"Exception",
"=>",
"e",
"fail",
"(",
"\"#{e}\\n#{e.backtrace.join(\"\\n\")}\"",
")",
"unless",
"e",
".",
"is_a?",
"(",
"SystemExit",
")",
"end"
] | Initialize manager
Handle stats request
=== Parameters
options(Hash):: Command line options
=== Return
true:: Always return true | [
"Initialize",
"manager",
"Handle",
"stats",
"request"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/scripts/stats_manager.rb#L65-L72 |
662 | rightscale/right_agent | lib/right_agent/scripts/stats_manager.rb | RightScale.StatsManager.request_stats | def request_stats(options)
# Determine candidate agents
agent_names = if options[:agent_name]
[options[:agent_name]]
else
AgentConfig.cfg_agents
end
fail("No agents configured") if agent_names.empty?
# Request stats from agents
count = 0
agent_names.each do |agent_name|
begin
count += 1 if request_agent_stats(agent_name, options)
rescue Exception => e
$stderr.puts "Command to #{agent_name} agent failed (#{e})" unless e.is_a?(SystemExit)
end
end
$stderr.puts("No agents running") if count == 0
end | ruby | def request_stats(options)
# Determine candidate agents
agent_names = if options[:agent_name]
[options[:agent_name]]
else
AgentConfig.cfg_agents
end
fail("No agents configured") if agent_names.empty?
# Request stats from agents
count = 0
agent_names.each do |agent_name|
begin
count += 1 if request_agent_stats(agent_name, options)
rescue Exception => e
$stderr.puts "Command to #{agent_name} agent failed (#{e})" unless e.is_a?(SystemExit)
end
end
$stderr.puts("No agents running") if count == 0
end | [
"def",
"request_stats",
"(",
"options",
")",
"# Determine candidate agents",
"agent_names",
"=",
"if",
"options",
"[",
":agent_name",
"]",
"[",
"options",
"[",
":agent_name",
"]",
"]",
"else",
"AgentConfig",
".",
"cfg_agents",
"end",
"fail",
"(",
"\"No agents configured\"",
")",
"if",
"agent_names",
".",
"empty?",
"# Request stats from agents",
"count",
"=",
"0",
"agent_names",
".",
"each",
"do",
"|",
"agent_name",
"|",
"begin",
"count",
"+=",
"1",
"if",
"request_agent_stats",
"(",
"agent_name",
",",
"options",
")",
"rescue",
"Exception",
"=>",
"e",
"$stderr",
".",
"puts",
"\"Command to #{agent_name} agent failed (#{e})\"",
"unless",
"e",
".",
"is_a?",
"(",
"SystemExit",
")",
"end",
"end",
"$stderr",
".",
"puts",
"(",
"\"No agents running\"",
")",
"if",
"count",
"==",
"0",
"end"
] | Request and display statistics for agents
=== Parameters
options(Hash):: Command line options
=== Return
true:: Always return true | [
"Request",
"and",
"display",
"statistics",
"for",
"agents"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/scripts/stats_manager.rb#L129-L148 |
663 | rightscale/right_agent | lib/right_agent/scripts/stats_manager.rb | RightScale.StatsManager.request_agent_stats | def request_agent_stats(agent_name, options)
res = false
config_options = AgentConfig.agent_options(agent_name)
unless config_options.empty? || (listen_port = config_options[:listen_port]).nil?
client = CommandClient.new(listen_port, config_options[:cookie])
command = {:name => :stats, :reset => options[:reset]}
begin
client.send_command(command, verbose = false, options[:timeout]) { |r| display(agent_name, r, options) }
res = true
rescue Exception => e
msg = "Could not retrieve #{agent_name} agent stats: #{e}"
msg += "\n" + e.backtrace.join("\n") unless e.message =~ /Timed out/
fail(msg)
end
end
res
end | ruby | def request_agent_stats(agent_name, options)
res = false
config_options = AgentConfig.agent_options(agent_name)
unless config_options.empty? || (listen_port = config_options[:listen_port]).nil?
client = CommandClient.new(listen_port, config_options[:cookie])
command = {:name => :stats, :reset => options[:reset]}
begin
client.send_command(command, verbose = false, options[:timeout]) { |r| display(agent_name, r, options) }
res = true
rescue Exception => e
msg = "Could not retrieve #{agent_name} agent stats: #{e}"
msg += "\n" + e.backtrace.join("\n") unless e.message =~ /Timed out/
fail(msg)
end
end
res
end | [
"def",
"request_agent_stats",
"(",
"agent_name",
",",
"options",
")",
"res",
"=",
"false",
"config_options",
"=",
"AgentConfig",
".",
"agent_options",
"(",
"agent_name",
")",
"unless",
"config_options",
".",
"empty?",
"||",
"(",
"listen_port",
"=",
"config_options",
"[",
":listen_port",
"]",
")",
".",
"nil?",
"client",
"=",
"CommandClient",
".",
"new",
"(",
"listen_port",
",",
"config_options",
"[",
":cookie",
"]",
")",
"command",
"=",
"{",
":name",
"=>",
":stats",
",",
":reset",
"=>",
"options",
"[",
":reset",
"]",
"}",
"begin",
"client",
".",
"send_command",
"(",
"command",
",",
"verbose",
"=",
"false",
",",
"options",
"[",
":timeout",
"]",
")",
"{",
"|",
"r",
"|",
"display",
"(",
"agent_name",
",",
"r",
",",
"options",
")",
"}",
"res",
"=",
"true",
"rescue",
"Exception",
"=>",
"e",
"msg",
"=",
"\"Could not retrieve #{agent_name} agent stats: #{e}\"",
"msg",
"+=",
"\"\\n\"",
"+",
"e",
".",
"backtrace",
".",
"join",
"(",
"\"\\n\"",
")",
"unless",
"e",
".",
"message",
"=~",
"/",
"/",
"fail",
"(",
"msg",
")",
"end",
"end",
"res",
"end"
] | Request and display statistics for agent
=== Parameters
agent_name(String):: Agent name
options(Hash):: Command line options
=== Return
(Boolean):: true if agent running, otherwise false | [
"Request",
"and",
"display",
"statistics",
"for",
"agent"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/scripts/stats_manager.rb#L158-L174 |
664 | rightscale/right_agent | lib/right_agent/offline_handler.rb | RightScale.OfflineHandler.disable | def disable
if offline? && @state != :created
Log.info("[offline] Connection to RightNet re-established")
@offline_stats.finish
cancel_timer
@state = :flushing
# Wait a bit to avoid flooding RightNet
EM.add_timer(rand(MAX_QUEUE_FLUSH_DELAY)) { flush }
end
true
end | ruby | def disable
if offline? && @state != :created
Log.info("[offline] Connection to RightNet re-established")
@offline_stats.finish
cancel_timer
@state = :flushing
# Wait a bit to avoid flooding RightNet
EM.add_timer(rand(MAX_QUEUE_FLUSH_DELAY)) { flush }
end
true
end | [
"def",
"disable",
"if",
"offline?",
"&&",
"@state",
"!=",
":created",
"Log",
".",
"info",
"(",
"\"[offline] Connection to RightNet re-established\"",
")",
"@offline_stats",
".",
"finish",
"cancel_timer",
"@state",
"=",
":flushing",
"# Wait a bit to avoid flooding RightNet",
"EM",
".",
"add_timer",
"(",
"rand",
"(",
"MAX_QUEUE_FLUSH_DELAY",
")",
")",
"{",
"flush",
"}",
"end",
"true",
"end"
] | Switch back to sending requests after in-memory queue gets flushed
Idempotent
=== Return
true:: Always return true | [
"Switch",
"back",
"to",
"sending",
"requests",
"after",
"in",
"-",
"memory",
"queue",
"gets",
"flushed",
"Idempotent"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/offline_handler.rb#L149-L159 |
665 | rightscale/right_agent | lib/right_agent/offline_handler.rb | RightScale.OfflineHandler.queue_request | def queue_request(kind, type, payload, target, token, expires_at, skewed_by, &callback)
request = {:kind => kind, :type => type, :payload => payload, :target => target,
:token => token, :expires_at => expires_at, :skewed_by => skewed_by,
:callback => callback}
Log.info("[offline] Queuing request: #{request.inspect}")
vote_to_restart if (@restart_vote_count += 1) >= MAX_QUEUED_REQUESTS
if @state == :initializing
# We are in the initialization callback, requests should be put at the head of the queue
@queue.unshift(request)
else
@queue << request
end
true
end | ruby | def queue_request(kind, type, payload, target, token, expires_at, skewed_by, &callback)
request = {:kind => kind, :type => type, :payload => payload, :target => target,
:token => token, :expires_at => expires_at, :skewed_by => skewed_by,
:callback => callback}
Log.info("[offline] Queuing request: #{request.inspect}")
vote_to_restart if (@restart_vote_count += 1) >= MAX_QUEUED_REQUESTS
if @state == :initializing
# We are in the initialization callback, requests should be put at the head of the queue
@queue.unshift(request)
else
@queue << request
end
true
end | [
"def",
"queue_request",
"(",
"kind",
",",
"type",
",",
"payload",
",",
"target",
",",
"token",
",",
"expires_at",
",",
"skewed_by",
",",
"&",
"callback",
")",
"request",
"=",
"{",
":kind",
"=>",
"kind",
",",
":type",
"=>",
"type",
",",
":payload",
"=>",
"payload",
",",
":target",
"=>",
"target",
",",
":token",
"=>",
"token",
",",
":expires_at",
"=>",
"expires_at",
",",
":skewed_by",
"=>",
"skewed_by",
",",
":callback",
"=>",
"callback",
"}",
"Log",
".",
"info",
"(",
"\"[offline] Queuing request: #{request.inspect}\"",
")",
"vote_to_restart",
"if",
"(",
"@restart_vote_count",
"+=",
"1",
")",
">=",
"MAX_QUEUED_REQUESTS",
"if",
"@state",
"==",
":initializing",
"# We are in the initialization callback, requests should be put at the head of the queue",
"@queue",
".",
"unshift",
"(",
"request",
")",
"else",
"@queue",
"<<",
"request",
"end",
"true",
"end"
] | Queue given request in memory
=== Parameters
kind(Symbol):: Kind of request: :send_push or :send_request
type(String):: Dispatch route for the request; typically identifies actor and action
payload(Object):: Data to be sent with marshalling en route
target(Hash|NilClass):: Target for request
token(String):: Token uniquely identifying request
expires_at(Integer):: Time in seconds in Unix-epoch when this request expires and
is to be ignored by the receiver; value 0 means never expire
skewed_by(Integer):: Amount of skew already applied to expires_at in seconds
=== Block
Optional block used to process response asynchronously with the following parameter:
result(Result):: Response with an OperationResult of SUCCESS, RETRY, NON_DELIVERY, or ERROR
=== Return
true:: Always return true | [
"Queue",
"given",
"request",
"in",
"memory"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/offline_handler.rb#L179-L192 |
666 | rightscale/right_agent | lib/right_agent/offline_handler.rb | RightScale.OfflineHandler.flush | def flush(again = false)
if @state == :flushing
Log.info("[offline] Starting to flush request queue of size #{@queue.size}") unless again || @mode == :initializing
if @queue.any?
r = @queue.shift
options = {:token => r[:token]}
if r[:expires_at] != 0 && (options[:time_to_live] = r[:expires_at] - Time.now.to_i) <= 0
Log.info("[offline] Dropping queued request <#{r[:token]}> because it expired " +
"#{(-options[:time_to_live]).round} sec ago")
else
Sender.instance.send(r[:kind], r[:type], r[:payload], r[:target], options, &r[:callback])
end
end
if @queue.empty?
Log.info("[offline] Request queue flushed, resuming normal operations") unless @mode == :initializing
@mode = :online
@state = :running
else
EM.next_tick { flush(true) }
end
end
true
end | ruby | def flush(again = false)
if @state == :flushing
Log.info("[offline] Starting to flush request queue of size #{@queue.size}") unless again || @mode == :initializing
if @queue.any?
r = @queue.shift
options = {:token => r[:token]}
if r[:expires_at] != 0 && (options[:time_to_live] = r[:expires_at] - Time.now.to_i) <= 0
Log.info("[offline] Dropping queued request <#{r[:token]}> because it expired " +
"#{(-options[:time_to_live]).round} sec ago")
else
Sender.instance.send(r[:kind], r[:type], r[:payload], r[:target], options, &r[:callback])
end
end
if @queue.empty?
Log.info("[offline] Request queue flushed, resuming normal operations") unless @mode == :initializing
@mode = :online
@state = :running
else
EM.next_tick { flush(true) }
end
end
true
end | [
"def",
"flush",
"(",
"again",
"=",
"false",
")",
"if",
"@state",
"==",
":flushing",
"Log",
".",
"info",
"(",
"\"[offline] Starting to flush request queue of size #{@queue.size}\"",
")",
"unless",
"again",
"||",
"@mode",
"==",
":initializing",
"if",
"@queue",
".",
"any?",
"r",
"=",
"@queue",
".",
"shift",
"options",
"=",
"{",
":token",
"=>",
"r",
"[",
":token",
"]",
"}",
"if",
"r",
"[",
":expires_at",
"]",
"!=",
"0",
"&&",
"(",
"options",
"[",
":time_to_live",
"]",
"=",
"r",
"[",
":expires_at",
"]",
"-",
"Time",
".",
"now",
".",
"to_i",
")",
"<=",
"0",
"Log",
".",
"info",
"(",
"\"[offline] Dropping queued request <#{r[:token]}> because it expired \"",
"+",
"\"#{(-options[:time_to_live]).round} sec ago\"",
")",
"else",
"Sender",
".",
"instance",
".",
"send",
"(",
"r",
"[",
":kind",
"]",
",",
"r",
"[",
":type",
"]",
",",
"r",
"[",
":payload",
"]",
",",
"r",
"[",
":target",
"]",
",",
"options",
",",
"r",
"[",
":callback",
"]",
")",
"end",
"end",
"if",
"@queue",
".",
"empty?",
"Log",
".",
"info",
"(",
"\"[offline] Request queue flushed, resuming normal operations\"",
")",
"unless",
"@mode",
"==",
":initializing",
"@mode",
"=",
":online",
"@state",
"=",
":running",
"else",
"EM",
".",
"next_tick",
"{",
"flush",
"(",
"true",
")",
"}",
"end",
"end",
"true",
"end"
] | Send any requests that were queued while in offline mode and have not yet timed out
Do this asynchronously to allow for agents to respond to requests
Once all in-memory requests have been flushed, switch off offline mode
=== Parameters
again(Boolean):: Whether being called in a loop
=== Return
true:: Always return true | [
"Send",
"any",
"requests",
"that",
"were",
"queued",
"while",
"in",
"offline",
"mode",
"and",
"have",
"not",
"yet",
"timed",
"out",
"Do",
"this",
"asynchronously",
"to",
"allow",
"for",
"agents",
"to",
"respond",
"to",
"requests",
"Once",
"all",
"in",
"-",
"memory",
"requests",
"have",
"been",
"flushed",
"switch",
"off",
"offline",
"mode"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/offline_handler.rb#L215-L237 |
667 | rightscale/right_agent | lib/right_agent/core_payload_types/login_policy.rb | RightScale.LoginPolicy.fingerprint | def fingerprint
h = Digest::SHA2.new
h << (self.exclusive ? 'true' : 'false')
users = self.users.sort { |a, b| a.uuid <=> b.uuid }
users.each do |u|
h << format(",(%d,%s,%s,%d,%s",
u.uuid, u.common_name,
(u.superuser ? 'true' : 'false'),
(u.expires_at ? u.expires_at.to_i : 0),
u.username)
u.public_key_fingerprints.each do |fp|
h << "," << fp
end
h << ')'
end
h.hexdigest
end | ruby | def fingerprint
h = Digest::SHA2.new
h << (self.exclusive ? 'true' : 'false')
users = self.users.sort { |a, b| a.uuid <=> b.uuid }
users.each do |u|
h << format(",(%d,%s,%s,%d,%s",
u.uuid, u.common_name,
(u.superuser ? 'true' : 'false'),
(u.expires_at ? u.expires_at.to_i : 0),
u.username)
u.public_key_fingerprints.each do |fp|
h << "," << fp
end
h << ')'
end
h.hexdigest
end | [
"def",
"fingerprint",
"h",
"=",
"Digest",
"::",
"SHA2",
".",
"new",
"h",
"<<",
"(",
"self",
".",
"exclusive",
"?",
"'true'",
":",
"'false'",
")",
"users",
"=",
"self",
".",
"users",
".",
"sort",
"{",
"|",
"a",
",",
"b",
"|",
"a",
".",
"uuid",
"<=>",
"b",
".",
"uuid",
"}",
"users",
".",
"each",
"do",
"|",
"u",
"|",
"h",
"<<",
"format",
"(",
"\",(%d,%s,%s,%d,%s\"",
",",
"u",
".",
"uuid",
",",
"u",
".",
"common_name",
",",
"(",
"u",
".",
"superuser",
"?",
"'true'",
":",
"'false'",
")",
",",
"(",
"u",
".",
"expires_at",
"?",
"u",
".",
"expires_at",
".",
"to_i",
":",
"0",
")",
",",
"u",
".",
"username",
")",
"u",
".",
"public_key_fingerprints",
".",
"each",
"do",
"|",
"fp",
"|",
"h",
"<<",
"\",\"",
"<<",
"fp",
"end",
"h",
"<<",
"')'",
"end",
"h",
".",
"hexdigest",
"end"
] | Compute a cryptographic hash of the information in this policy; helps
callers compare two policies to see if they are equivalent.
@see https://github.com/rightscale/cmaro/domain/login_policy.go | [
"Compute",
"a",
"cryptographic",
"hash",
"of",
"the",
"information",
"in",
"this",
"policy",
";",
"helps",
"callers",
"compare",
"two",
"policies",
"to",
"see",
"if",
"they",
"are",
"equivalent",
"."
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/core_payload_types/login_policy.rb#L52-L71 |
668 | rightscale/right_agent | lib/right_agent/clients/blocking_client.rb | RightScale.BlockingClient.request | def request(verb, path, host, connect_options, request_options)
url = host + path + request_options.delete(:query).to_s
result = request_once(verb, url, request_options)
@connections[path] = {:host => host, :path => path, :expires_at => Time.now + BalancedHttpClient::CONNECTION_REUSE_TIMEOUT }
result
end | ruby | def request(verb, path, host, connect_options, request_options)
url = host + path + request_options.delete(:query).to_s
result = request_once(verb, url, request_options)
@connections[path] = {:host => host, :path => path, :expires_at => Time.now + BalancedHttpClient::CONNECTION_REUSE_TIMEOUT }
result
end | [
"def",
"request",
"(",
"verb",
",",
"path",
",",
"host",
",",
"connect_options",
",",
"request_options",
")",
"url",
"=",
"host",
"+",
"path",
"+",
"request_options",
".",
"delete",
"(",
":query",
")",
".",
"to_s",
"result",
"=",
"request_once",
"(",
"verb",
",",
"url",
",",
"request_options",
")",
"@connections",
"[",
"path",
"]",
"=",
"{",
":host",
"=>",
"host",
",",
":path",
"=>",
"path",
",",
":expires_at",
"=>",
"Time",
".",
"now",
"+",
"BalancedHttpClient",
"::",
"CONNECTION_REUSE_TIMEOUT",
"}",
"result",
"end"
] | Make HTTP request
@param [Symbol] verb for HTTP REST request
@param [String] path in URI for desired resource
@param [String] host name of server
@param [Hash] connect_options for HTTP connection (ignored)
@param [Hash] request_options for HTTP request
@return [Array] result to be returned followed by response code, body, and headers
@raise [HttpException] HTTP failure with associated status code | [
"Make",
"HTTP",
"request"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/blocking_client.rb#L108-L113 |
669 | rightscale/right_agent | lib/right_agent/clients/blocking_client.rb | RightScale.BlockingClient.poll | def poll(connection, request_options, stop_at)
url = connection[:host] + connection[:path] + request_options.delete(:query).to_s
begin
result, code, body, headers = request_once(:get, url, request_options)
end until result || Time.now >= stop_at
connection[:expires_at] = Time.now + BalancedHttpClient::CONNECTION_REUSE_TIMEOUT
[result, code, body, headers]
end | ruby | def poll(connection, request_options, stop_at)
url = connection[:host] + connection[:path] + request_options.delete(:query).to_s
begin
result, code, body, headers = request_once(:get, url, request_options)
end until result || Time.now >= stop_at
connection[:expires_at] = Time.now + BalancedHttpClient::CONNECTION_REUSE_TIMEOUT
[result, code, body, headers]
end | [
"def",
"poll",
"(",
"connection",
",",
"request_options",
",",
"stop_at",
")",
"url",
"=",
"connection",
"[",
":host",
"]",
"+",
"connection",
"[",
":path",
"]",
"+",
"request_options",
".",
"delete",
"(",
":query",
")",
".",
"to_s",
"begin",
"result",
",",
"code",
",",
"body",
",",
"headers",
"=",
"request_once",
"(",
":get",
",",
"url",
",",
"request_options",
")",
"end",
"until",
"result",
"||",
"Time",
".",
"now",
">=",
"stop_at",
"connection",
"[",
":expires_at",
"]",
"=",
"Time",
".",
"now",
"+",
"BalancedHttpClient",
"::",
"CONNECTION_REUSE_TIMEOUT",
"[",
"result",
",",
"code",
",",
"body",
",",
"headers",
"]",
"end"
] | Make long-polling requests until receive data, hit error, or timeout
@param [Hash] connection to server from previous request with keys :host, :path,
and :expires_at, with the :expires_at being adjusted on return
@param [Hash] request_options for HTTP request
@param [Time] stop_at time for polling
@return [Array] result to be returned followed by response code, body, and headers
@raise [HttpException] HTTP failure with associated status code | [
"Make",
"long",
"-",
"polling",
"requests",
"until",
"receive",
"data",
"hit",
"error",
"or",
"timeout"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/blocking_client.rb#L125-L132 |
670 | rightscale/right_agent | lib/right_agent/clients/blocking_client.rb | RightScale.BlockingClient.request_once | def request_once(verb, url, request_options)
if (r = RightSupport::Net::HTTPClient.new.send(verb, url, request_options))
[BalancedHttpClient.response(r.code, r.body, r.headers, request_options[:headers][:accept]), r.code, r.body, r.headers]
else
[nil, nil, nil, nil]
end
end | ruby | def request_once(verb, url, request_options)
if (r = RightSupport::Net::HTTPClient.new.send(verb, url, request_options))
[BalancedHttpClient.response(r.code, r.body, r.headers, request_options[:headers][:accept]), r.code, r.body, r.headers]
else
[nil, nil, nil, nil]
end
end | [
"def",
"request_once",
"(",
"verb",
",",
"url",
",",
"request_options",
")",
"if",
"(",
"r",
"=",
"RightSupport",
"::",
"Net",
"::",
"HTTPClient",
".",
"new",
".",
"send",
"(",
"verb",
",",
"url",
",",
"request_options",
")",
")",
"[",
"BalancedHttpClient",
".",
"response",
"(",
"r",
".",
"code",
",",
"r",
".",
"body",
",",
"r",
".",
"headers",
",",
"request_options",
"[",
":headers",
"]",
"[",
":accept",
"]",
")",
",",
"r",
".",
"code",
",",
"r",
".",
"body",
",",
"r",
".",
"headers",
"]",
"else",
"[",
"nil",
",",
"nil",
",",
"nil",
",",
"nil",
"]",
"end",
"end"
] | Make HTTP request once
@param [Symbol] verb for HTTP REST request
@param [String] url for request
@param [Hash] request_options for HTTP request
@return [Array] result to be returned followed by response code, body, and headers
@raise [HttpException] HTTP failure with associated status code | [
"Make",
"HTTP",
"request",
"once"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/blocking_client.rb#L155-L161 |
671 | rightscale/right_agent | lib/right_agent/pending_requests.rb | RightScale.PendingRequests.[]= | def []=(token, pending_request)
now = Time.now
if (now - @last_cleanup) > MIN_CLEANUP_INTERVAL
self.reject! { |t, r| r.kind == :send_push && (now - r.receive_time) > MAX_PUSH_AGE }
@last_cleanup = now
end
super
end | ruby | def []=(token, pending_request)
now = Time.now
if (now - @last_cleanup) > MIN_CLEANUP_INTERVAL
self.reject! { |t, r| r.kind == :send_push && (now - r.receive_time) > MAX_PUSH_AGE }
@last_cleanup = now
end
super
end | [
"def",
"[]=",
"(",
"token",
",",
"pending_request",
")",
"now",
"=",
"Time",
".",
"now",
"if",
"(",
"now",
"-",
"@last_cleanup",
")",
">",
"MIN_CLEANUP_INTERVAL",
"self",
".",
"reject!",
"{",
"|",
"t",
",",
"r",
"|",
"r",
".",
"kind",
"==",
":send_push",
"&&",
"(",
"now",
"-",
"r",
".",
"receive_time",
")",
">",
"MAX_PUSH_AGE",
"}",
"@last_cleanup",
"=",
"now",
"end",
"super",
"end"
] | Create cache
Store pending request
=== Parameters
token(String):: Generated message identifier
pending_request(PendingRequest):: Pending request
=== Return
(PendingRequest):: Stored request | [
"Create",
"cache",
"Store",
"pending",
"request"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/pending_requests.rb#L78-L85 |
672 | rightscale/right_agent | lib/right_agent/scripts/agent_deployer.rb | RightScale.AgentDeployer.deploy | def deploy(options)
# Initialize directory settings
AgentConfig.root_dir = options[:root_dir]
AgentConfig.cfg_dir = options[:cfg_dir]
AgentConfig.pid_dir = options[:pid_dir]
# Configure agent
cfg = load_init_cfg
check_agent(options, cfg)
cfg = configure(options, cfg)
# Persist configuration
persist(options, cfg)
# Setup agent monitoring
monitor(options) if options[:monit]
true
end | ruby | def deploy(options)
# Initialize directory settings
AgentConfig.root_dir = options[:root_dir]
AgentConfig.cfg_dir = options[:cfg_dir]
AgentConfig.pid_dir = options[:pid_dir]
# Configure agent
cfg = load_init_cfg
check_agent(options, cfg)
cfg = configure(options, cfg)
# Persist configuration
persist(options, cfg)
# Setup agent monitoring
monitor(options) if options[:monit]
true
end | [
"def",
"deploy",
"(",
"options",
")",
"# Initialize directory settings",
"AgentConfig",
".",
"root_dir",
"=",
"options",
"[",
":root_dir",
"]",
"AgentConfig",
".",
"cfg_dir",
"=",
"options",
"[",
":cfg_dir",
"]",
"AgentConfig",
".",
"pid_dir",
"=",
"options",
"[",
":pid_dir",
"]",
"# Configure agent",
"cfg",
"=",
"load_init_cfg",
"check_agent",
"(",
"options",
",",
"cfg",
")",
"cfg",
"=",
"configure",
"(",
"options",
",",
"cfg",
")",
"# Persist configuration",
"persist",
"(",
"options",
",",
"cfg",
")",
"# Setup agent monitoring",
"monitor",
"(",
"options",
")",
"if",
"options",
"[",
":monit",
"]",
"true",
"end"
] | Generate configuration from specified options and the agent's base options
and write them to a file
=== Parameters
options(Hash):: Command line options
=== Return
true:: Always return true | [
"Generate",
"configuration",
"from",
"specified",
"options",
"and",
"the",
"agent",
"s",
"base",
"options",
"and",
"write",
"them",
"to",
"a",
"file"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/scripts/agent_deployer.rb#L86-L103 |
673 | rightscale/right_agent | lib/right_agent/scripts/agent_deployer.rb | RightScale.AgentDeployer.load_init_cfg | def load_init_cfg
cfg = {}
if (cfg_file = AgentConfig.init_cfg_file) && (cfg_data = YAML.load(IO.read(cfg_file)))
cfg = SerializationHelper.symbolize_keys(cfg_data) rescue nil
fail("Cannot read configuration for agent #{cfg_file.inspect}") unless cfg
end
cfg
end | ruby | def load_init_cfg
cfg = {}
if (cfg_file = AgentConfig.init_cfg_file) && (cfg_data = YAML.load(IO.read(cfg_file)))
cfg = SerializationHelper.symbolize_keys(cfg_data) rescue nil
fail("Cannot read configuration for agent #{cfg_file.inspect}") unless cfg
end
cfg
end | [
"def",
"load_init_cfg",
"cfg",
"=",
"{",
"}",
"if",
"(",
"cfg_file",
"=",
"AgentConfig",
".",
"init_cfg_file",
")",
"&&",
"(",
"cfg_data",
"=",
"YAML",
".",
"load",
"(",
"IO",
".",
"read",
"(",
"cfg_file",
")",
")",
")",
"cfg",
"=",
"SerializationHelper",
".",
"symbolize_keys",
"(",
"cfg_data",
")",
"rescue",
"nil",
"fail",
"(",
"\"Cannot read configuration for agent #{cfg_file.inspect}\"",
")",
"unless",
"cfg",
"end",
"cfg",
"end"
] | Load initial configuration for agent, if any
=== Return
cfg(Hash):: Initial agent configuration options | [
"Load",
"initial",
"configuration",
"for",
"agent",
"if",
"any"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/scripts/agent_deployer.rb#L261-L268 |
674 | rightscale/right_agent | lib/right_agent/scripts/agent_deployer.rb | RightScale.AgentDeployer.check_agent | def check_agent(options, cfg)
identity = options[:identity]
agent_type = options[:agent_type]
type = AgentIdentity.parse(identity).agent_type if identity
fail("Agent type #{agent_type.inspect} and identity #{identity.inspect} are inconsistent") if agent_type != type
fail("Cannot find agent init.rb file in init directory of #{AgentConfig.root_dir.inspect}") unless AgentConfig.init_file
actors = cfg[:actors]
fail('Agent configuration is missing actors') unless actors && actors.respond_to?(:each)
actors_dirs = AgentConfig.actors_dirs
actors.each do |a|
found = false
actors_dirs.each { |d| break if (found = File.exist?(File.normalize_path(File.join(d, "#{a}.rb")))) }
fail("Cannot find source for actor #{a.inspect} in #{actors_dirs.inspect}") unless found
end
true
end | ruby | def check_agent(options, cfg)
identity = options[:identity]
agent_type = options[:agent_type]
type = AgentIdentity.parse(identity).agent_type if identity
fail("Agent type #{agent_type.inspect} and identity #{identity.inspect} are inconsistent") if agent_type != type
fail("Cannot find agent init.rb file in init directory of #{AgentConfig.root_dir.inspect}") unless AgentConfig.init_file
actors = cfg[:actors]
fail('Agent configuration is missing actors') unless actors && actors.respond_to?(:each)
actors_dirs = AgentConfig.actors_dirs
actors.each do |a|
found = false
actors_dirs.each { |d| break if (found = File.exist?(File.normalize_path(File.join(d, "#{a}.rb")))) }
fail("Cannot find source for actor #{a.inspect} in #{actors_dirs.inspect}") unless found
end
true
end | [
"def",
"check_agent",
"(",
"options",
",",
"cfg",
")",
"identity",
"=",
"options",
"[",
":identity",
"]",
"agent_type",
"=",
"options",
"[",
":agent_type",
"]",
"type",
"=",
"AgentIdentity",
".",
"parse",
"(",
"identity",
")",
".",
"agent_type",
"if",
"identity",
"fail",
"(",
"\"Agent type #{agent_type.inspect} and identity #{identity.inspect} are inconsistent\"",
")",
"if",
"agent_type",
"!=",
"type",
"fail",
"(",
"\"Cannot find agent init.rb file in init directory of #{AgentConfig.root_dir.inspect}\"",
")",
"unless",
"AgentConfig",
".",
"init_file",
"actors",
"=",
"cfg",
"[",
":actors",
"]",
"fail",
"(",
"'Agent configuration is missing actors'",
")",
"unless",
"actors",
"&&",
"actors",
".",
"respond_to?",
"(",
":each",
")",
"actors_dirs",
"=",
"AgentConfig",
".",
"actors_dirs",
"actors",
".",
"each",
"do",
"|",
"a",
"|",
"found",
"=",
"false",
"actors_dirs",
".",
"each",
"{",
"|",
"d",
"|",
"break",
"if",
"(",
"found",
"=",
"File",
".",
"exist?",
"(",
"File",
".",
"normalize_path",
"(",
"File",
".",
"join",
"(",
"d",
",",
"\"#{a}.rb\"",
")",
")",
")",
")",
"}",
"fail",
"(",
"\"Cannot find source for actor #{a.inspect} in #{actors_dirs.inspect}\"",
")",
"unless",
"found",
"end",
"true",
"end"
] | Check agent type consistency and existence of initialization file and actors directory
=== Parameters
options(Hash):: Command line options
cfg(Hash):: Initial configuration settings
=== Return
true:: Always return true | [
"Check",
"agent",
"type",
"consistency",
"and",
"existence",
"of",
"initialization",
"file",
"and",
"actors",
"directory"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/scripts/agent_deployer.rb#L278-L294 |
675 | rightscale/right_agent | lib/right_agent/scripts/agent_deployer.rb | RightScale.AgentDeployer.persist | def persist(options, cfg)
overrides = options[:options]
overrides.each { |k, v| cfg[k] = v } if overrides
cfg_file = AgentConfig.store_cfg(options[:agent_name], cfg)
unless options[:quiet]
puts "Generated configuration file for #{options[:agent_name]} agent: #{cfg_file}" unless options[:quiet]
end
true
end | ruby | def persist(options, cfg)
overrides = options[:options]
overrides.each { |k, v| cfg[k] = v } if overrides
cfg_file = AgentConfig.store_cfg(options[:agent_name], cfg)
unless options[:quiet]
puts "Generated configuration file for #{options[:agent_name]} agent: #{cfg_file}" unless options[:quiet]
end
true
end | [
"def",
"persist",
"(",
"options",
",",
"cfg",
")",
"overrides",
"=",
"options",
"[",
":options",
"]",
"overrides",
".",
"each",
"{",
"|",
"k",
",",
"v",
"|",
"cfg",
"[",
"k",
"]",
"=",
"v",
"}",
"if",
"overrides",
"cfg_file",
"=",
"AgentConfig",
".",
"store_cfg",
"(",
"options",
"[",
":agent_name",
"]",
",",
"cfg",
")",
"unless",
"options",
"[",
":quiet",
"]",
"puts",
"\"Generated configuration file for #{options[:agent_name]} agent: #{cfg_file}\"",
"unless",
"options",
"[",
":quiet",
"]",
"end",
"true",
"end"
] | Write configuration options to file after applying any overrides
=== Parameters
options(Hash):: Command line options
cfg(Hash):: Configurations options with which specified options are to be merged
=== Return
true:: Always return true | [
"Write",
"configuration",
"options",
"to",
"file",
"after",
"applying",
"any",
"overrides"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/scripts/agent_deployer.rb#L344-L352 |
676 | rightscale/right_agent | lib/right_agent/core_payload_types/dev_repositories.rb | RightScale.DevRepositories.add_repo | def add_repo(repo_sha, repo_detail, cookbook_positions)
@repositories ||= {}
@repositories[repo_sha] = DevRepository.new(repo_detail[:repo_type],
repo_detail[:url],
repo_detail[:tag],
repo_detail[:cookboooks_path],
repo_detail[:ssh_key],
repo_detail[:username],
repo_detail[:password],
repo_sha,
cookbook_positions)
end | ruby | def add_repo(repo_sha, repo_detail, cookbook_positions)
@repositories ||= {}
@repositories[repo_sha] = DevRepository.new(repo_detail[:repo_type],
repo_detail[:url],
repo_detail[:tag],
repo_detail[:cookboooks_path],
repo_detail[:ssh_key],
repo_detail[:username],
repo_detail[:password],
repo_sha,
cookbook_positions)
end | [
"def",
"add_repo",
"(",
"repo_sha",
",",
"repo_detail",
",",
"cookbook_positions",
")",
"@repositories",
"||=",
"{",
"}",
"@repositories",
"[",
"repo_sha",
"]",
"=",
"DevRepository",
".",
"new",
"(",
"repo_detail",
"[",
":repo_type",
"]",
",",
"repo_detail",
"[",
":url",
"]",
",",
"repo_detail",
"[",
":tag",
"]",
",",
"repo_detail",
"[",
":cookboooks_path",
"]",
",",
"repo_detail",
"[",
":ssh_key",
"]",
",",
"repo_detail",
"[",
":username",
"]",
",",
"repo_detail",
"[",
":password",
"]",
",",
"repo_sha",
",",
"cookbook_positions",
")",
"end"
] | Add a repository...
=== Parameters
(Hash):: collection of repos to be checked out on the instance
:repo_sha (String):: the hash id (SHA) of the repository
:repo_detail (Hash):: info needed to checkout this repo
{
<Symbol> Type of repository: one of :git, :svn, :download or :local
* :git denotes a 'git' repository that should be retrieved via 'git clone'
* :svn denotes a 'svn' repository that should be retrieved via 'svn checkout'
* :download denotes a tar ball that should be retrieved via HTTP GET (HTTPS if uri starts with https://)
* :local denotes cookbook that is already local and doesn't need to be retrieved
:repo_type => <Symbol>,
<String> URL to repository (e.g. git://github.com/opscode/chef-repo.git)
:url => <String>,
<String> git commit or svn branch that should be used to retrieve repository
Optional, use 'master' for git and 'trunk' for svn if tag is nil.
Not used for raw repositories.
:tag => <String>,
<Array> Path to cookbooks inside repostory
Optional (use location of repository as cookbook path if nil)
:cookbooks_path => <Array>,
<String> Private SSH key used to retrieve git repositories
Optional, not used for svn and raw repositories.
:ssh_key => <String>,
<String> Username used to retrieve svn and raw repositories
Optional, not used for git repositories.
:username => <String>,
<String> Password used to retrieve svn and raw repositories
Optional, not used for git repositories.
:password => <String>
}
:cookbook_positions (Array):: List of CookbookPositions to be developed. Represents the subset of cookbooks identified as the "dev cookbooks"
=== Return
result(Hash):: The entry added to the collection of repositories | [
"Add",
"a",
"repository",
"..."
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/core_payload_types/dev_repositories.rb#L79-L90 |
677 | rightscale/right_agent | lib/right_agent/command/agent_manager_commands.rb | RightScale.AgentManagerCommands.list_command | def list_command(opts)
usage = "Agent exposes the following commands:\n"
COMMANDS.reject { |k, _| k == :list || k.to_s =~ /test/ }.each do |c|
c.each { |k, v| usage += " - #{k.to_s}: #{v}\n" }
end
CommandIO.instance.reply(opts[:conn], usage)
end | ruby | def list_command(opts)
usage = "Agent exposes the following commands:\n"
COMMANDS.reject { |k, _| k == :list || k.to_s =~ /test/ }.each do |c|
c.each { |k, v| usage += " - #{k.to_s}: #{v}\n" }
end
CommandIO.instance.reply(opts[:conn], usage)
end | [
"def",
"list_command",
"(",
"opts",
")",
"usage",
"=",
"\"Agent exposes the following commands:\\n\"",
"COMMANDS",
".",
"reject",
"{",
"|",
"k",
",",
"_",
"|",
"k",
"==",
":list",
"||",
"k",
".",
"to_s",
"=~",
"/",
"/",
"}",
".",
"each",
"do",
"|",
"c",
"|",
"c",
".",
"each",
"{",
"|",
"k",
",",
"v",
"|",
"usage",
"+=",
"\" - #{k.to_s}: #{v}\\n\"",
"}",
"end",
"CommandIO",
".",
"instance",
".",
"reply",
"(",
"opts",
"[",
":conn",
"]",
",",
"usage",
")",
"end"
] | List command implementation
=== Parameters
opts(Hash):: Should contain the connection for sending data
=== Return
true:: Always return true | [
"List",
"command",
"implementation"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/command/agent_manager_commands.rb#L73-L79 |
678 | rightscale/right_agent | lib/right_agent/command/agent_manager_commands.rb | RightScale.AgentManagerCommands.set_log_level_command | def set_log_level_command(opts)
Log.level = opts[:level] if [ :debug, :info, :warn, :error, :fatal ].include?(opts[:level])
CommandIO.instance.reply(opts[:conn], Log.level)
end | ruby | def set_log_level_command(opts)
Log.level = opts[:level] if [ :debug, :info, :warn, :error, :fatal ].include?(opts[:level])
CommandIO.instance.reply(opts[:conn], Log.level)
end | [
"def",
"set_log_level_command",
"(",
"opts",
")",
"Log",
".",
"level",
"=",
"opts",
"[",
":level",
"]",
"if",
"[",
":debug",
",",
":info",
",",
":warn",
",",
":error",
",",
":fatal",
"]",
".",
"include?",
"(",
"opts",
"[",
":level",
"]",
")",
"CommandIO",
".",
"instance",
".",
"reply",
"(",
"opts",
"[",
":conn",
"]",
",",
"Log",
".",
"level",
")",
"end"
] | Set log level command
=== Return
true:: Always return true | [
"Set",
"log",
"level",
"command"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/command/agent_manager_commands.rb#L85-L88 |
679 | rightscale/right_agent | lib/right_agent/sender.rb | RightScale.Sender.send_push | def send_push(type, payload = nil, target = nil, options = {}, &callback)
build_and_send_packet(:send_push, type, payload, target, options, &callback)
end | ruby | def send_push(type, payload = nil, target = nil, options = {}, &callback)
build_and_send_packet(:send_push, type, payload, target, options, &callback)
end | [
"def",
"send_push",
"(",
"type",
",",
"payload",
"=",
"nil",
",",
"target",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
",",
"&",
"callback",
")",
"build_and_send_packet",
"(",
":send_push",
",",
"type",
",",
"payload",
",",
"target",
",",
"options",
",",
"callback",
")",
"end"
] | Send a request to a single target or multiple targets with no response expected other
than routing failures
Persist the request en route to reduce the chance of it being lost at the expense of some
additional network overhead
Enqueue the request if the target is not currently available
Never automatically retry the request if there is the possibility of it being duplicated
Set time-to-live to be forever
=== Parameters
type(String):: Dispatch route for the request; typically identifies actor and action
payload(Object):: Data to be sent with marshalling en route
target(Hash|NilClass) Target for request, which may be a specific agent (using :agent_id),
potentially multiple targets (using :tags, :scope, :selector), or nil to route solely
using type:
:agent_id(String):: serialized identity of specific target
:tags(Array):: Tags that must all be associated with a target for it to be selected
:scope(Hash):: Scoping to be used to restrict routing
:account(Integer):: Restrict to agents with this account id
:shard(Integer):: Restrict to agents with this shard id, or if value is Packet::GLOBAL,
ones with no shard id
:selector(Symbol):: Which of the matched targets to be selected, either :any or :all,
defaults to :any
options(Hash):: Request options
:token(String):: Universally unique ID for request; defaults to random generated
:time_to_live(Numeric):: Number of seconds before a request expires and is to be ignored;
non-positive value or nil means never expire; defaults to 0
=== Block
Optional block used to process routing responses asynchronously with the following parameter:
result(Result):: Response with an OperationResult of SUCCESS, RETRY, NON_DELIVERY, or ERROR,
with an initial SUCCESS response containing the targets to which the request was sent
and any additional responses indicating any failures to actually route the request
to those targets, use RightScale::OperationResult.from_results to decode
=== Return
true:: Always return true
=== Raise
ArgumentError:: If target invalid
SendFailure:: If sending of request failed unexpectedly
TemporarilyOffline:: If cannot send request because RightNet client currently disconnected
and offline queueing is disabled | [
"Send",
"a",
"request",
"to",
"a",
"single",
"target",
"or",
"multiple",
"targets",
"with",
"no",
"response",
"expected",
"other",
"than",
"routing",
"failures",
"Persist",
"the",
"request",
"en",
"route",
"to",
"reduce",
"the",
"chance",
"of",
"it",
"being",
"lost",
"at",
"the",
"expense",
"of",
"some",
"additional",
"network",
"overhead",
"Enqueue",
"the",
"request",
"if",
"the",
"target",
"is",
"not",
"currently",
"available",
"Never",
"automatically",
"retry",
"the",
"request",
"if",
"there",
"is",
"the",
"possibility",
"of",
"it",
"being",
"duplicated",
"Set",
"time",
"-",
"to",
"-",
"live",
"to",
"be",
"forever"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/sender.rb#L207-L209 |
680 | rightscale/right_agent | lib/right_agent/sender.rb | RightScale.Sender.send_request | def send_request(type, payload = nil, target = nil, options = {}, &callback)
raise ArgumentError, "Missing block for response callback" unless callback
build_and_send_packet(:send_request, type, payload, target, options, &callback)
end | ruby | def send_request(type, payload = nil, target = nil, options = {}, &callback)
raise ArgumentError, "Missing block for response callback" unless callback
build_and_send_packet(:send_request, type, payload, target, options, &callback)
end | [
"def",
"send_request",
"(",
"type",
",",
"payload",
"=",
"nil",
",",
"target",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
",",
"&",
"callback",
")",
"raise",
"ArgumentError",
",",
"\"Missing block for response callback\"",
"unless",
"callback",
"build_and_send_packet",
"(",
":send_request",
",",
"type",
",",
"payload",
",",
"target",
",",
"options",
",",
"callback",
")",
"end"
] | Send a request to a single target with a response expected
Automatically retry the request if a response is not received in a reasonable amount of time
or if there is a non-delivery response indicating the target is not currently available
Timeout the request if a response is not received in time, typically configured to 2 minutes
Because of retries there is the possibility of duplicated requests, and these are detected and
discarded automatically for non-idempotent actions
Allow the request to expire per the agent's configured time-to-live, typically 1 minute
Note that receiving a response does not guarantee that the request activity has actually
completed since the request processing may involve other asynchronous requests
=== Parameters
type(String):: Dispatch route for the request; typically identifies actor and action
payload(Object):: Data to be sent with marshalling en route
target(Hash|NilClass) Target for request, which may be a specific agent (using :agent_id),
one chosen randomly from potentially multiple targets (using :tags, :scope), or nil to
route solely using type:
:agent_id(String):: serialized identity of specific target
:tags(Array):: Tags that must all be associated with a target for it to be selected
:scope(Hash):: Scoping to be used to restrict routing
:account(Integer):: Restrict to agents with this account id
:shard(Integer):: Restrict to agents with this shard id, or if value is Packet::GLOBAL,
ones with no shard id
options(Hash):: Request options
:token(String):: Universally unique ID for request; defaults to random generated
:time_to_live(Numeric):: Number of seconds before a request expires and is to be ignored;
non-positive value or nil means never expire; defaults to configured :time_to_live
=== Block
Required block used to process response asynchronously with the following parameter:
result(Result):: Response with an OperationResult of SUCCESS, RETRY, NON_DELIVERY, or ERROR,
use RightScale::OperationResult.from_results to decode
=== Return
true:: Always return true
=== Raise
ArgumentError:: If target invalid or block missing | [
"Send",
"a",
"request",
"to",
"a",
"single",
"target",
"with",
"a",
"response",
"expected",
"Automatically",
"retry",
"the",
"request",
"if",
"a",
"response",
"is",
"not",
"received",
"in",
"a",
"reasonable",
"amount",
"of",
"time",
"or",
"if",
"there",
"is",
"a",
"non",
"-",
"delivery",
"response",
"indicating",
"the",
"target",
"is",
"not",
"currently",
"available",
"Timeout",
"the",
"request",
"if",
"a",
"response",
"is",
"not",
"received",
"in",
"time",
"typically",
"configured",
"to",
"2",
"minutes",
"Because",
"of",
"retries",
"there",
"is",
"the",
"possibility",
"of",
"duplicated",
"requests",
"and",
"these",
"are",
"detected",
"and",
"discarded",
"automatically",
"for",
"non",
"-",
"idempotent",
"actions",
"Allow",
"the",
"request",
"to",
"expire",
"per",
"the",
"agent",
"s",
"configured",
"time",
"-",
"to",
"-",
"live",
"typically",
"1",
"minute",
"Note",
"that",
"receiving",
"a",
"response",
"does",
"not",
"guarantee",
"that",
"the",
"request",
"activity",
"has",
"actually",
"completed",
"since",
"the",
"request",
"processing",
"may",
"involve",
"other",
"asynchronous",
"requests"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/sender.rb#L248-L251 |
681 | rightscale/right_agent | lib/right_agent/sender.rb | RightScale.Sender.build_and_send_packet | def build_and_send_packet(kind, type, payload, target, options = {}, &callback)
if (packet = build_packet(kind, type, payload, target, options, &callback))
action = type.split('/').last
received_at = @request_stats.update(action, packet.token)
@request_kind_stats.update((packet.selector == :all ? "fanout" : kind.to_s)[5..-1])
send("#{@mode}_send", kind, target, packet, received_at, &callback)
end
true
end | ruby | def build_and_send_packet(kind, type, payload, target, options = {}, &callback)
if (packet = build_packet(kind, type, payload, target, options, &callback))
action = type.split('/').last
received_at = @request_stats.update(action, packet.token)
@request_kind_stats.update((packet.selector == :all ? "fanout" : kind.to_s)[5..-1])
send("#{@mode}_send", kind, target, packet, received_at, &callback)
end
true
end | [
"def",
"build_and_send_packet",
"(",
"kind",
",",
"type",
",",
"payload",
",",
"target",
",",
"options",
"=",
"{",
"}",
",",
"&",
"callback",
")",
"if",
"(",
"packet",
"=",
"build_packet",
"(",
"kind",
",",
"type",
",",
"payload",
",",
"target",
",",
"options",
",",
"callback",
")",
")",
"action",
"=",
"type",
".",
"split",
"(",
"'/'",
")",
".",
"last",
"received_at",
"=",
"@request_stats",
".",
"update",
"(",
"action",
",",
"packet",
".",
"token",
")",
"@request_kind_stats",
".",
"update",
"(",
"(",
"packet",
".",
"selector",
"==",
":all",
"?",
"\"fanout\"",
":",
"kind",
".",
"to_s",
")",
"[",
"5",
"..",
"-",
"1",
"]",
")",
"send",
"(",
"\"#{@mode}_send\"",
",",
"kind",
",",
"target",
",",
"packet",
",",
"received_at",
",",
"callback",
")",
"end",
"true",
"end"
] | Build and send packet
=== Parameters
kind(Symbol):: Kind of request: :send_push or :send_request
type(String):: Dispatch route for the request; typically identifies actor and action
payload(Object):: Data to be sent with marshalling en route
target(Hash|NilClass):: Target for request
:agent_id(String):: Identity of specific target
:tags(Array):: Tags that must all be associated with a target for it to be selected
:scope(Hash):: Scoping to be used to restrict routing
:account(Integer):: Restrict to agents with this account id
:shard(Integer):: Restrict to agents with this shard id, or if value is Packet::GLOBAL,
ones with no shard id
:selector(Symbol):: Which of the matched targets to be selected: :any or :all
options(Hash):: Request options
:token(String):: Universally unique ID for request; defaults to random generated
:time_to_live(Numeric):: Number of seconds before a request expires and is to be ignored;
non-positive value or nil means never expire for :send_push and means use configured
time-to-live for :send_request
=== Block
Optional block used to process response asynchronously with the following parameter:
result(Result):: Response with an OperationResult of SUCCESS, RETRY, NON_DELIVERY, or ERROR
=== Return
true:: Always return true
=== Raise
ArgumentError:: If target invalid | [
"Build",
"and",
"send",
"packet"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/sender.rb#L282-L290 |
682 | rightscale/right_agent | lib/right_agent/sender.rb | RightScale.Sender.build_packet | def build_packet(kind, type, payload, target, options = {}, &callback)
validate_target(target, kind == :send_push)
if kind == :send_push
packet = Push.new(type, payload)
packet.selector = target[:selector] || :any if target.is_a?(Hash)
packet.persistent = true
packet.confirm = true if callback
time_to_live = options[:time_to_live] || 0
else
packet = Request.new(type, payload)
packet.selector = :any
time_to_live = options[:time_to_live] || @options[:time_to_live]
end
packet.from = @identity
packet.token = options[:token] || RightSupport::Data::UUID.generate
packet.expires_at = Time.now.to_i + time_to_live if time_to_live && time_to_live > 0
if target.is_a?(Hash)
if (agent_id = target[:agent_id])
packet.target = agent_id
else
packet.tags = target[:tags] || []
packet.scope = target[:scope]
end
else
packet.target = target
end
if queueing?
@offline_handler.queue_request(kind, type, payload, target, packet.token, packet.expires_at, packet.skewed_by, &callback)
nil
else
packet
end
end | ruby | def build_packet(kind, type, payload, target, options = {}, &callback)
validate_target(target, kind == :send_push)
if kind == :send_push
packet = Push.new(type, payload)
packet.selector = target[:selector] || :any if target.is_a?(Hash)
packet.persistent = true
packet.confirm = true if callback
time_to_live = options[:time_to_live] || 0
else
packet = Request.new(type, payload)
packet.selector = :any
time_to_live = options[:time_to_live] || @options[:time_to_live]
end
packet.from = @identity
packet.token = options[:token] || RightSupport::Data::UUID.generate
packet.expires_at = Time.now.to_i + time_to_live if time_to_live && time_to_live > 0
if target.is_a?(Hash)
if (agent_id = target[:agent_id])
packet.target = agent_id
else
packet.tags = target[:tags] || []
packet.scope = target[:scope]
end
else
packet.target = target
end
if queueing?
@offline_handler.queue_request(kind, type, payload, target, packet.token, packet.expires_at, packet.skewed_by, &callback)
nil
else
packet
end
end | [
"def",
"build_packet",
"(",
"kind",
",",
"type",
",",
"payload",
",",
"target",
",",
"options",
"=",
"{",
"}",
",",
"&",
"callback",
")",
"validate_target",
"(",
"target",
",",
"kind",
"==",
":send_push",
")",
"if",
"kind",
"==",
":send_push",
"packet",
"=",
"Push",
".",
"new",
"(",
"type",
",",
"payload",
")",
"packet",
".",
"selector",
"=",
"target",
"[",
":selector",
"]",
"||",
":any",
"if",
"target",
".",
"is_a?",
"(",
"Hash",
")",
"packet",
".",
"persistent",
"=",
"true",
"packet",
".",
"confirm",
"=",
"true",
"if",
"callback",
"time_to_live",
"=",
"options",
"[",
":time_to_live",
"]",
"||",
"0",
"else",
"packet",
"=",
"Request",
".",
"new",
"(",
"type",
",",
"payload",
")",
"packet",
".",
"selector",
"=",
":any",
"time_to_live",
"=",
"options",
"[",
":time_to_live",
"]",
"||",
"@options",
"[",
":time_to_live",
"]",
"end",
"packet",
".",
"from",
"=",
"@identity",
"packet",
".",
"token",
"=",
"options",
"[",
":token",
"]",
"||",
"RightSupport",
"::",
"Data",
"::",
"UUID",
".",
"generate",
"packet",
".",
"expires_at",
"=",
"Time",
".",
"now",
".",
"to_i",
"+",
"time_to_live",
"if",
"time_to_live",
"&&",
"time_to_live",
">",
"0",
"if",
"target",
".",
"is_a?",
"(",
"Hash",
")",
"if",
"(",
"agent_id",
"=",
"target",
"[",
":agent_id",
"]",
")",
"packet",
".",
"target",
"=",
"agent_id",
"else",
"packet",
".",
"tags",
"=",
"target",
"[",
":tags",
"]",
"||",
"[",
"]",
"packet",
".",
"scope",
"=",
"target",
"[",
":scope",
"]",
"end",
"else",
"packet",
".",
"target",
"=",
"target",
"end",
"if",
"queueing?",
"@offline_handler",
".",
"queue_request",
"(",
"kind",
",",
"type",
",",
"payload",
",",
"target",
",",
"packet",
".",
"token",
",",
"packet",
".",
"expires_at",
",",
"packet",
".",
"skewed_by",
",",
"callback",
")",
"nil",
"else",
"packet",
"end",
"end"
] | Build packet or queue it if offline
=== Parameters
kind(Symbol):: Kind of request: :send_push or :send_request
type(String):: Dispatch route for the request; typically identifies actor and action
payload(Object):: Data to be sent with marshalling en route
target(Hash|NilClass):: Target for request
:agent_id(String):: Identity of specific target
:tags(Array):: Tags that must all be associated with a target for it to be selected
:scope(Hash):: Scoping to be used to restrict routing
:account(Integer):: Restrict to agents with this account id
:shard(Integer):: Restrict to agents with this shard id, or if value is Packet::GLOBAL,
ones with no shard id
:selector(Symbol):: Which of the matched targets to be selected: :any or :all
options(Hash):: Request options
:token(String):: Universally unique ID for request; defaults to random generated
:time_to_live(Numeric):: Number of seconds before a request expires and is to be ignored;
non-positive value or nil means never expire for :send_push and means use configured
time-to-live for :send_request
=== Block
Optional block used to process response asynchronously with the following parameter:
result(Result):: Response with an OperationResult of SUCCESS, RETRY, NON_DELIVERY, or ERROR
=== Return
(Push|Request|NilClass):: Packet created, or nil if queued instead
=== Raise
ArgumentError:: If target is invalid | [
"Build",
"packet",
"or",
"queue",
"it",
"if",
"offline"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/sender.rb#L321-L354 |
683 | rightscale/right_agent | lib/right_agent/sender.rb | RightScale.Sender.handle_response | def handle_response(response)
if response.is_a?(Result)
token = response.token
if (result = OperationResult.from_results(response))
if result.non_delivery?
@non_delivery_stats.update(result.content.nil? ? "nil" : result.content)
elsif result.error?
@result_error_stats.update(result.content.nil? ? "nil" : result.content)
end
@result_stats.update(result.status)
else
@result_stats.update(response.results.nil? ? "nil" : response.results)
end
if (pending_request = @pending_requests[token])
if result && result.non_delivery? && pending_request.kind == :send_request
if result.content == OperationResult::TARGET_NOT_CONNECTED
# Log and temporarily ignore so that timeout retry mechanism continues, but save reason for use below if timeout
# Leave purging of associated request until final response, i.e., success response or retry timeout
if (parent_token = pending_request.retry_parent_token)
@pending_requests[parent_token].non_delivery = result.content
else
pending_request.non_delivery = result.content
end
Log.info("Non-delivery of <#{token}> because #{result.content}")
elsif result.content == OperationResult::RETRY_TIMEOUT && pending_request.non_delivery
# Request timed out but due to another non-delivery reason, so use that reason since more germane
response.results = OperationResult.non_delivery(pending_request.non_delivery)
deliver_response(response, pending_request)
else
deliver_response(response, pending_request)
end
else
deliver_response(response, pending_request)
end
elsif result && result.non_delivery?
Log.info("Non-delivery of <#{token}> because #{result.content}")
else
Log.debug("No pending request for response #{response.to_s([])}")
end
end
true
end | ruby | def handle_response(response)
if response.is_a?(Result)
token = response.token
if (result = OperationResult.from_results(response))
if result.non_delivery?
@non_delivery_stats.update(result.content.nil? ? "nil" : result.content)
elsif result.error?
@result_error_stats.update(result.content.nil? ? "nil" : result.content)
end
@result_stats.update(result.status)
else
@result_stats.update(response.results.nil? ? "nil" : response.results)
end
if (pending_request = @pending_requests[token])
if result && result.non_delivery? && pending_request.kind == :send_request
if result.content == OperationResult::TARGET_NOT_CONNECTED
# Log and temporarily ignore so that timeout retry mechanism continues, but save reason for use below if timeout
# Leave purging of associated request until final response, i.e., success response or retry timeout
if (parent_token = pending_request.retry_parent_token)
@pending_requests[parent_token].non_delivery = result.content
else
pending_request.non_delivery = result.content
end
Log.info("Non-delivery of <#{token}> because #{result.content}")
elsif result.content == OperationResult::RETRY_TIMEOUT && pending_request.non_delivery
# Request timed out but due to another non-delivery reason, so use that reason since more germane
response.results = OperationResult.non_delivery(pending_request.non_delivery)
deliver_response(response, pending_request)
else
deliver_response(response, pending_request)
end
else
deliver_response(response, pending_request)
end
elsif result && result.non_delivery?
Log.info("Non-delivery of <#{token}> because #{result.content}")
else
Log.debug("No pending request for response #{response.to_s([])}")
end
end
true
end | [
"def",
"handle_response",
"(",
"response",
")",
"if",
"response",
".",
"is_a?",
"(",
"Result",
")",
"token",
"=",
"response",
".",
"token",
"if",
"(",
"result",
"=",
"OperationResult",
".",
"from_results",
"(",
"response",
")",
")",
"if",
"result",
".",
"non_delivery?",
"@non_delivery_stats",
".",
"update",
"(",
"result",
".",
"content",
".",
"nil?",
"?",
"\"nil\"",
":",
"result",
".",
"content",
")",
"elsif",
"result",
".",
"error?",
"@result_error_stats",
".",
"update",
"(",
"result",
".",
"content",
".",
"nil?",
"?",
"\"nil\"",
":",
"result",
".",
"content",
")",
"end",
"@result_stats",
".",
"update",
"(",
"result",
".",
"status",
")",
"else",
"@result_stats",
".",
"update",
"(",
"response",
".",
"results",
".",
"nil?",
"?",
"\"nil\"",
":",
"response",
".",
"results",
")",
"end",
"if",
"(",
"pending_request",
"=",
"@pending_requests",
"[",
"token",
"]",
")",
"if",
"result",
"&&",
"result",
".",
"non_delivery?",
"&&",
"pending_request",
".",
"kind",
"==",
":send_request",
"if",
"result",
".",
"content",
"==",
"OperationResult",
"::",
"TARGET_NOT_CONNECTED",
"# Log and temporarily ignore so that timeout retry mechanism continues, but save reason for use below if timeout",
"# Leave purging of associated request until final response, i.e., success response or retry timeout",
"if",
"(",
"parent_token",
"=",
"pending_request",
".",
"retry_parent_token",
")",
"@pending_requests",
"[",
"parent_token",
"]",
".",
"non_delivery",
"=",
"result",
".",
"content",
"else",
"pending_request",
".",
"non_delivery",
"=",
"result",
".",
"content",
"end",
"Log",
".",
"info",
"(",
"\"Non-delivery of <#{token}> because #{result.content}\"",
")",
"elsif",
"result",
".",
"content",
"==",
"OperationResult",
"::",
"RETRY_TIMEOUT",
"&&",
"pending_request",
".",
"non_delivery",
"# Request timed out but due to another non-delivery reason, so use that reason since more germane",
"response",
".",
"results",
"=",
"OperationResult",
".",
"non_delivery",
"(",
"pending_request",
".",
"non_delivery",
")",
"deliver_response",
"(",
"response",
",",
"pending_request",
")",
"else",
"deliver_response",
"(",
"response",
",",
"pending_request",
")",
"end",
"else",
"deliver_response",
"(",
"response",
",",
"pending_request",
")",
"end",
"elsif",
"result",
"&&",
"result",
".",
"non_delivery?",
"Log",
".",
"info",
"(",
"\"Non-delivery of <#{token}> because #{result.content}\"",
")",
"else",
"Log",
".",
"debug",
"(",
"\"No pending request for response #{response.to_s([])}\"",
")",
"end",
"end",
"true",
"end"
] | Handle response to a request
=== Parameters
response(Result):: Packet received as result of request
=== Return
true:: Always return true | [
"Handle",
"response",
"to",
"a",
"request"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/sender.rb#L363-L405 |
684 | rightscale/right_agent | lib/right_agent/sender.rb | RightScale.Sender.terminate | def terminate
if @offline_handler
@offline_handler.terminate
@connectivity_checker.terminate if @connectivity_checker
pending = @pending_requests.kind(:send_request)
[pending.size, PendingRequests.youngest_age(pending)]
else
[0, nil]
end
end | ruby | def terminate
if @offline_handler
@offline_handler.terminate
@connectivity_checker.terminate if @connectivity_checker
pending = @pending_requests.kind(:send_request)
[pending.size, PendingRequests.youngest_age(pending)]
else
[0, nil]
end
end | [
"def",
"terminate",
"if",
"@offline_handler",
"@offline_handler",
".",
"terminate",
"@connectivity_checker",
".",
"terminate",
"if",
"@connectivity_checker",
"pending",
"=",
"@pending_requests",
".",
"kind",
"(",
":send_request",
")",
"[",
"pending",
".",
"size",
",",
"PendingRequests",
".",
"youngest_age",
"(",
"pending",
")",
"]",
"else",
"[",
"0",
",",
"nil",
"]",
"end",
"end"
] | Take any actions necessary to quiesce client interaction in preparation
for agent termination but allow message receipt to continue
=== Return
(Array):: Number of pending non-push requests and age of youngest request | [
"Take",
"any",
"actions",
"necessary",
"to",
"quiesce",
"client",
"interaction",
"in",
"preparation",
"for",
"agent",
"termination",
"but",
"allow",
"message",
"receipt",
"to",
"continue"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/sender.rb#L412-L421 |
685 | rightscale/right_agent | lib/right_agent/sender.rb | RightScale.Sender.dump_requests | def dump_requests
info = []
if @pending_requests
@pending_requests.kind(:send_request).each do |token, request|
info << "#{request.receive_time.localtime} <#{token}>"
end
info.sort!.reverse!
info = info[0..49] + ["..."] if info.size > 50
end
info
end | ruby | def dump_requests
info = []
if @pending_requests
@pending_requests.kind(:send_request).each do |token, request|
info << "#{request.receive_time.localtime} <#{token}>"
end
info.sort!.reverse!
info = info[0..49] + ["..."] if info.size > 50
end
info
end | [
"def",
"dump_requests",
"info",
"=",
"[",
"]",
"if",
"@pending_requests",
"@pending_requests",
".",
"kind",
"(",
":send_request",
")",
".",
"each",
"do",
"|",
"token",
",",
"request",
"|",
"info",
"<<",
"\"#{request.receive_time.localtime} <#{token}>\"",
"end",
"info",
".",
"sort!",
".",
"reverse!",
"info",
"=",
"info",
"[",
"0",
"..",
"49",
"]",
"+",
"[",
"\"...\"",
"]",
"if",
"info",
".",
"size",
">",
"50",
"end",
"info",
"end"
] | Create displayable dump of unfinished non-push request information
Truncate list if there are more than 50 requests
=== Return
info(Array(String)):: Receive time and token for each request in descending time order | [
"Create",
"displayable",
"dump",
"of",
"unfinished",
"non",
"-",
"push",
"request",
"information",
"Truncate",
"list",
"if",
"there",
"are",
"more",
"than",
"50",
"requests"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/sender.rb#L428-L438 |
686 | rightscale/right_agent | lib/right_agent/sender.rb | RightScale.Sender.stats | def stats(reset = false)
stats = {}
if @agent
offlines = @offline_stats.all
offlines.merge!("duration" => @offline_stats.avg_duration) if offlines
if @pending_requests.size > 0
pending = {}
pending["pushes"] = @pending_requests.kind(:send_push).size
requests = @pending_requests.kind(:send_request)
if (pending["requests"] = requests.size) > 0
pending["oldest age"] = PendingRequests.oldest_age(requests)
end
end
stats = {
"non-deliveries" => @non_delivery_stats.all,
"offlines" => offlines,
"pings" => @ping_stats.all,
"request kinds" => @request_kind_stats.all,
"requests" => @request_stats.all,
"requests pending" => pending,
"result errors" => @result_error_stats.all,
"results" => @result_stats.all,
"retries" => @retry_stats.all,
"send failures" => @send_failure_stats.all
}
reset_stats if reset
end
stats
end | ruby | def stats(reset = false)
stats = {}
if @agent
offlines = @offline_stats.all
offlines.merge!("duration" => @offline_stats.avg_duration) if offlines
if @pending_requests.size > 0
pending = {}
pending["pushes"] = @pending_requests.kind(:send_push).size
requests = @pending_requests.kind(:send_request)
if (pending["requests"] = requests.size) > 0
pending["oldest age"] = PendingRequests.oldest_age(requests)
end
end
stats = {
"non-deliveries" => @non_delivery_stats.all,
"offlines" => offlines,
"pings" => @ping_stats.all,
"request kinds" => @request_kind_stats.all,
"requests" => @request_stats.all,
"requests pending" => pending,
"result errors" => @result_error_stats.all,
"results" => @result_stats.all,
"retries" => @retry_stats.all,
"send failures" => @send_failure_stats.all
}
reset_stats if reset
end
stats
end | [
"def",
"stats",
"(",
"reset",
"=",
"false",
")",
"stats",
"=",
"{",
"}",
"if",
"@agent",
"offlines",
"=",
"@offline_stats",
".",
"all",
"offlines",
".",
"merge!",
"(",
"\"duration\"",
"=>",
"@offline_stats",
".",
"avg_duration",
")",
"if",
"offlines",
"if",
"@pending_requests",
".",
"size",
">",
"0",
"pending",
"=",
"{",
"}",
"pending",
"[",
"\"pushes\"",
"]",
"=",
"@pending_requests",
".",
"kind",
"(",
":send_push",
")",
".",
"size",
"requests",
"=",
"@pending_requests",
".",
"kind",
"(",
":send_request",
")",
"if",
"(",
"pending",
"[",
"\"requests\"",
"]",
"=",
"requests",
".",
"size",
")",
">",
"0",
"pending",
"[",
"\"oldest age\"",
"]",
"=",
"PendingRequests",
".",
"oldest_age",
"(",
"requests",
")",
"end",
"end",
"stats",
"=",
"{",
"\"non-deliveries\"",
"=>",
"@non_delivery_stats",
".",
"all",
",",
"\"offlines\"",
"=>",
"offlines",
",",
"\"pings\"",
"=>",
"@ping_stats",
".",
"all",
",",
"\"request kinds\"",
"=>",
"@request_kind_stats",
".",
"all",
",",
"\"requests\"",
"=>",
"@request_stats",
".",
"all",
",",
"\"requests pending\"",
"=>",
"pending",
",",
"\"result errors\"",
"=>",
"@result_error_stats",
".",
"all",
",",
"\"results\"",
"=>",
"@result_stats",
".",
"all",
",",
"\"retries\"",
"=>",
"@retry_stats",
".",
"all",
",",
"\"send failures\"",
"=>",
"@send_failure_stats",
".",
"all",
"}",
"reset_stats",
"if",
"reset",
"end",
"stats",
"end"
] | Get sender statistics
=== Parameters
reset(Boolean):: Whether to reset the statistics after getting the current ones
=== Return
stats(Hash):: Current statistics:
"non-deliveries"(Hash|nil):: Non-delivery activity stats with keys "total", "percent", "last",
and 'rate' with percentage breakdown per reason, or nil if none
"offlines"(Hash|nil):: Offline activity stats with keys "total", "last", and "duration",
or nil if none
"pings"(Hash|nil):: Request activity stats with keys "total", "percent", "last", and "rate"
with percentage breakdown for "success" vs. "timeout", or nil if none
"request kinds"(Hash|nil):: Request kind activity stats with keys "total", "percent", and "last"
with percentage breakdown per kind, or nil if none
"requests"(Hash|nil):: Request activity stats with keys "total", "percent", "last", and "rate"
with percentage breakdown per request type, or nil if none
"requests pending"(Hash|nil):: Number of requests waiting for response and age of oldest,
or nil if none
"result errors"(Hash|nil):: Error result activity stats with keys "total", "percent", "last",
and 'rate' with percentage breakdown per error, or nil if none
"results"(Hash|nil):: Results activity stats with keys "total", "percent", "last", and "rate"
with percentage breakdown per operation result type, or nil if none
"retries"(Hash|nil):: Retry activity stats with keys "total", "percent", "last", and "rate"
with percentage breakdown per request type, or nil if none
"send failure"(Hash|nil):: Send failure activity stats with keys "total", "percent", "last", and "rate"
with percentage breakdown per failure type, or nil if none | [
"Get",
"sender",
"statistics"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/sender.rb#L467-L495 |
687 | rightscale/right_agent | lib/right_agent/sender.rb | RightScale.Sender.reset_stats | def reset_stats
@ping_stats = RightSupport::Stats::Activity.new
@retry_stats = RightSupport::Stats::Activity.new
@request_stats = RightSupport::Stats::Activity.new
@result_stats = RightSupport::Stats::Activity.new
@result_error_stats = RightSupport::Stats::Activity.new
@non_delivery_stats = RightSupport::Stats::Activity.new
@offline_stats = RightSupport::Stats::Activity.new(measure_rate = false)
@request_kind_stats = RightSupport::Stats::Activity.new(measure_rate = false)
@send_failure_stats = RightSupport::Stats::Activity.new
true
end | ruby | def reset_stats
@ping_stats = RightSupport::Stats::Activity.new
@retry_stats = RightSupport::Stats::Activity.new
@request_stats = RightSupport::Stats::Activity.new
@result_stats = RightSupport::Stats::Activity.new
@result_error_stats = RightSupport::Stats::Activity.new
@non_delivery_stats = RightSupport::Stats::Activity.new
@offline_stats = RightSupport::Stats::Activity.new(measure_rate = false)
@request_kind_stats = RightSupport::Stats::Activity.new(measure_rate = false)
@send_failure_stats = RightSupport::Stats::Activity.new
true
end | [
"def",
"reset_stats",
"@ping_stats",
"=",
"RightSupport",
"::",
"Stats",
"::",
"Activity",
".",
"new",
"@retry_stats",
"=",
"RightSupport",
"::",
"Stats",
"::",
"Activity",
".",
"new",
"@request_stats",
"=",
"RightSupport",
"::",
"Stats",
"::",
"Activity",
".",
"new",
"@result_stats",
"=",
"RightSupport",
"::",
"Stats",
"::",
"Activity",
".",
"new",
"@result_error_stats",
"=",
"RightSupport",
"::",
"Stats",
"::",
"Activity",
".",
"new",
"@non_delivery_stats",
"=",
"RightSupport",
"::",
"Stats",
"::",
"Activity",
".",
"new",
"@offline_stats",
"=",
"RightSupport",
"::",
"Stats",
"::",
"Activity",
".",
"new",
"(",
"measure_rate",
"=",
"false",
")",
"@request_kind_stats",
"=",
"RightSupport",
"::",
"Stats",
"::",
"Activity",
".",
"new",
"(",
"measure_rate",
"=",
"false",
")",
"@send_failure_stats",
"=",
"RightSupport",
"::",
"Stats",
"::",
"Activity",
".",
"new",
"true",
"end"
] | Reset dispatch statistics
=== Return
true:: Always return true | [
"Reset",
"dispatch",
"statistics"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/sender.rb#L503-L514 |
688 | rightscale/right_agent | lib/right_agent/sender.rb | RightScale.Sender.http_send | def http_send(kind, target, packet, received_at, &callback)
if @options[:async_response]
EM_S.next_tick do
begin
http_send_once(kind, target, packet, received_at, &callback)
rescue StandardError => e
ErrorTracker.log(self, "Failed sending or handling response for #{packet.trace} #{packet.type}", e)
end
end
else
http_send_once(kind, target, packet, received_at, &callback)
end
true
end | ruby | def http_send(kind, target, packet, received_at, &callback)
if @options[:async_response]
EM_S.next_tick do
begin
http_send_once(kind, target, packet, received_at, &callback)
rescue StandardError => e
ErrorTracker.log(self, "Failed sending or handling response for #{packet.trace} #{packet.type}", e)
end
end
else
http_send_once(kind, target, packet, received_at, &callback)
end
true
end | [
"def",
"http_send",
"(",
"kind",
",",
"target",
",",
"packet",
",",
"received_at",
",",
"&",
"callback",
")",
"if",
"@options",
"[",
":async_response",
"]",
"EM_S",
".",
"next_tick",
"do",
"begin",
"http_send_once",
"(",
"kind",
",",
"target",
",",
"packet",
",",
"received_at",
",",
"callback",
")",
"rescue",
"StandardError",
"=>",
"e",
"ErrorTracker",
".",
"log",
"(",
"self",
",",
"\"Failed sending or handling response for #{packet.trace} #{packet.type}\"",
",",
"e",
")",
"end",
"end",
"else",
"http_send_once",
"(",
"kind",
",",
"target",
",",
"packet",
",",
"received_at",
",",
"callback",
")",
"end",
"true",
"end"
] | Send request via HTTP
Use next_tick for asynchronous response and to ensure
that the request is sent using the main EM reactor thread
=== Parameters
kind(Symbol):: Kind of request: :send_push or :send_request
target(Hash|NilClass):: Target for request
packet(Push|Request):: Request packet to send
received_at(Time):: Time when request received
=== Block
Optional block used to process response asynchronously with the following parameter:
result(Result):: Response with an OperationResult of SUCCESS, RETRY, NON_DELIVERY, or ERROR
=== Return
true:: Always return true | [
"Send",
"request",
"via",
"HTTP",
"Use",
"next_tick",
"for",
"asynchronous",
"response",
"and",
"to",
"ensure",
"that",
"the",
"request",
"is",
"sent",
"using",
"the",
"main",
"EM",
"reactor",
"thread"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/sender.rb#L601-L614 |
689 | rightscale/right_agent | lib/right_agent/sender.rb | RightScale.Sender.http_send_once | def http_send_once(kind, target, packet, received_at, &callback)
begin
method = packet.class.name.split("::").last.downcase
options = {:request_uuid => packet.token}
options[:time_to_live] = (packet.expires_at - Time.now.to_i) if packet.expires_at > 0
result = success_result(@agent.client.send(method, packet.type, packet.payload, target, options))
rescue Exceptions::Unauthorized => e
result = error_result(e.message)
rescue Exceptions::ConnectivityFailure => e
if queueing?
@offline_handler.queue_request(kind, packet.type, packet.payload, target, packet.token, packet.expires_at, packet.skewed_by, &callback)
result = nil
else
result = retry_result(e.message)
end
rescue Exceptions::RetryableError => e
result = retry_result(e.message)
rescue Exceptions::InternalServerError => e
result = error_result("#{e.server} internal error")
rescue Exceptions::Terminating => e
result = nil
rescue StandardError => e
# These errors are either unexpected errors or HttpExceptions with an http_body
# giving details about the error that are conveyed in the error_result
if e.respond_to?(:http_body)
# No need to log here since any HTTP request errors have already been logged
result = error_result(e.inspect)
else
agent_type = AgentIdentity.parse(@identity).agent_type
ErrorTracker.log(self, "Failed to send #{packet.trace} #{packet.type}", e)
result = error_result("#{agent_type.capitalize} agent internal error")
end
end
if result && packet.is_a?(Request)
result = Result.new(packet.token, @identity, result, from = packet.target)
result.received_at = received_at.to_f
@pending_requests[packet.token] = PendingRequest.new(kind, received_at, callback) if callback
handle_response(result)
end
true
end | ruby | def http_send_once(kind, target, packet, received_at, &callback)
begin
method = packet.class.name.split("::").last.downcase
options = {:request_uuid => packet.token}
options[:time_to_live] = (packet.expires_at - Time.now.to_i) if packet.expires_at > 0
result = success_result(@agent.client.send(method, packet.type, packet.payload, target, options))
rescue Exceptions::Unauthorized => e
result = error_result(e.message)
rescue Exceptions::ConnectivityFailure => e
if queueing?
@offline_handler.queue_request(kind, packet.type, packet.payload, target, packet.token, packet.expires_at, packet.skewed_by, &callback)
result = nil
else
result = retry_result(e.message)
end
rescue Exceptions::RetryableError => e
result = retry_result(e.message)
rescue Exceptions::InternalServerError => e
result = error_result("#{e.server} internal error")
rescue Exceptions::Terminating => e
result = nil
rescue StandardError => e
# These errors are either unexpected errors or HttpExceptions with an http_body
# giving details about the error that are conveyed in the error_result
if e.respond_to?(:http_body)
# No need to log here since any HTTP request errors have already been logged
result = error_result(e.inspect)
else
agent_type = AgentIdentity.parse(@identity).agent_type
ErrorTracker.log(self, "Failed to send #{packet.trace} #{packet.type}", e)
result = error_result("#{agent_type.capitalize} agent internal error")
end
end
if result && packet.is_a?(Request)
result = Result.new(packet.token, @identity, result, from = packet.target)
result.received_at = received_at.to_f
@pending_requests[packet.token] = PendingRequest.new(kind, received_at, callback) if callback
handle_response(result)
end
true
end | [
"def",
"http_send_once",
"(",
"kind",
",",
"target",
",",
"packet",
",",
"received_at",
",",
"&",
"callback",
")",
"begin",
"method",
"=",
"packet",
".",
"class",
".",
"name",
".",
"split",
"(",
"\"::\"",
")",
".",
"last",
".",
"downcase",
"options",
"=",
"{",
":request_uuid",
"=>",
"packet",
".",
"token",
"}",
"options",
"[",
":time_to_live",
"]",
"=",
"(",
"packet",
".",
"expires_at",
"-",
"Time",
".",
"now",
".",
"to_i",
")",
"if",
"packet",
".",
"expires_at",
">",
"0",
"result",
"=",
"success_result",
"(",
"@agent",
".",
"client",
".",
"send",
"(",
"method",
",",
"packet",
".",
"type",
",",
"packet",
".",
"payload",
",",
"target",
",",
"options",
")",
")",
"rescue",
"Exceptions",
"::",
"Unauthorized",
"=>",
"e",
"result",
"=",
"error_result",
"(",
"e",
".",
"message",
")",
"rescue",
"Exceptions",
"::",
"ConnectivityFailure",
"=>",
"e",
"if",
"queueing?",
"@offline_handler",
".",
"queue_request",
"(",
"kind",
",",
"packet",
".",
"type",
",",
"packet",
".",
"payload",
",",
"target",
",",
"packet",
".",
"token",
",",
"packet",
".",
"expires_at",
",",
"packet",
".",
"skewed_by",
",",
"callback",
")",
"result",
"=",
"nil",
"else",
"result",
"=",
"retry_result",
"(",
"e",
".",
"message",
")",
"end",
"rescue",
"Exceptions",
"::",
"RetryableError",
"=>",
"e",
"result",
"=",
"retry_result",
"(",
"e",
".",
"message",
")",
"rescue",
"Exceptions",
"::",
"InternalServerError",
"=>",
"e",
"result",
"=",
"error_result",
"(",
"\"#{e.server} internal error\"",
")",
"rescue",
"Exceptions",
"::",
"Terminating",
"=>",
"e",
"result",
"=",
"nil",
"rescue",
"StandardError",
"=>",
"e",
"# These errors are either unexpected errors or HttpExceptions with an http_body",
"# giving details about the error that are conveyed in the error_result",
"if",
"e",
".",
"respond_to?",
"(",
":http_body",
")",
"# No need to log here since any HTTP request errors have already been logged",
"result",
"=",
"error_result",
"(",
"e",
".",
"inspect",
")",
"else",
"agent_type",
"=",
"AgentIdentity",
".",
"parse",
"(",
"@identity",
")",
".",
"agent_type",
"ErrorTracker",
".",
"log",
"(",
"self",
",",
"\"Failed to send #{packet.trace} #{packet.type}\"",
",",
"e",
")",
"result",
"=",
"error_result",
"(",
"\"#{agent_type.capitalize} agent internal error\"",
")",
"end",
"end",
"if",
"result",
"&&",
"packet",
".",
"is_a?",
"(",
"Request",
")",
"result",
"=",
"Result",
".",
"new",
"(",
"packet",
".",
"token",
",",
"@identity",
",",
"result",
",",
"from",
"=",
"packet",
".",
"target",
")",
"result",
".",
"received_at",
"=",
"received_at",
".",
"to_f",
"@pending_requests",
"[",
"packet",
".",
"token",
"]",
"=",
"PendingRequest",
".",
"new",
"(",
"kind",
",",
"received_at",
",",
"callback",
")",
"if",
"callback",
"handle_response",
"(",
"result",
")",
"end",
"true",
"end"
] | Send request via HTTP and then immediately handle response
=== Parameters
kind(Symbol):: Kind of request: :send_push or :send_request
target(Hash|NilClass):: Target for request
packet(Push|Request):: Request packet to send
received_at(Time):: Time when request received
=== Block
Optional block used to process response asynchronously with the following parameter:
result(Result):: Response with an OperationResult of SUCCESS, RETRY, NON_DELIVERY, or ERROR
=== Return
true:: Always return true | [
"Send",
"request",
"via",
"HTTP",
"and",
"then",
"immediately",
"handle",
"response"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/sender.rb#L630-L671 |
690 | rightscale/right_agent | lib/right_agent/sender.rb | RightScale.Sender.amqp_send | def amqp_send(kind, target, packet, received_at, &callback)
begin
@pending_requests[packet.token] = PendingRequest.new(kind, received_at, callback) if callback
if packet.class == Request
amqp_send_retry(packet, packet.token)
else
amqp_send_once(packet)
end
rescue TemporarilyOffline => e
if queueing?
# Queue request until come back online
@offline_handler.queue_request(kind, packet.type, packet.payload, target, packet.token, packet.expires_at, packet.skewed_by, &callback)
@pending_requests.delete(packet.token) if callback
else
# Send retry response so that requester, e.g., RetryableRequest, can retry
result = OperationResult.retry("lost RightNet connectivity")
handle_response(Result.new(packet.token, @identity, result, @identity))
end
rescue SendFailure => e
# Send non-delivery response so that requester, e.g., RetryableRequest, can retry
result = OperationResult.non_delivery("send failed unexpectedly")
handle_response(Result.new(packet.token, @identity, result, @identity))
end
true
end | ruby | def amqp_send(kind, target, packet, received_at, &callback)
begin
@pending_requests[packet.token] = PendingRequest.new(kind, received_at, callback) if callback
if packet.class == Request
amqp_send_retry(packet, packet.token)
else
amqp_send_once(packet)
end
rescue TemporarilyOffline => e
if queueing?
# Queue request until come back online
@offline_handler.queue_request(kind, packet.type, packet.payload, target, packet.token, packet.expires_at, packet.skewed_by, &callback)
@pending_requests.delete(packet.token) if callback
else
# Send retry response so that requester, e.g., RetryableRequest, can retry
result = OperationResult.retry("lost RightNet connectivity")
handle_response(Result.new(packet.token, @identity, result, @identity))
end
rescue SendFailure => e
# Send non-delivery response so that requester, e.g., RetryableRequest, can retry
result = OperationResult.non_delivery("send failed unexpectedly")
handle_response(Result.new(packet.token, @identity, result, @identity))
end
true
end | [
"def",
"amqp_send",
"(",
"kind",
",",
"target",
",",
"packet",
",",
"received_at",
",",
"&",
"callback",
")",
"begin",
"@pending_requests",
"[",
"packet",
".",
"token",
"]",
"=",
"PendingRequest",
".",
"new",
"(",
"kind",
",",
"received_at",
",",
"callback",
")",
"if",
"callback",
"if",
"packet",
".",
"class",
"==",
"Request",
"amqp_send_retry",
"(",
"packet",
",",
"packet",
".",
"token",
")",
"else",
"amqp_send_once",
"(",
"packet",
")",
"end",
"rescue",
"TemporarilyOffline",
"=>",
"e",
"if",
"queueing?",
"# Queue request until come back online",
"@offline_handler",
".",
"queue_request",
"(",
"kind",
",",
"packet",
".",
"type",
",",
"packet",
".",
"payload",
",",
"target",
",",
"packet",
".",
"token",
",",
"packet",
".",
"expires_at",
",",
"packet",
".",
"skewed_by",
",",
"callback",
")",
"@pending_requests",
".",
"delete",
"(",
"packet",
".",
"token",
")",
"if",
"callback",
"else",
"# Send retry response so that requester, e.g., RetryableRequest, can retry",
"result",
"=",
"OperationResult",
".",
"retry",
"(",
"\"lost RightNet connectivity\"",
")",
"handle_response",
"(",
"Result",
".",
"new",
"(",
"packet",
".",
"token",
",",
"@identity",
",",
"result",
",",
"@identity",
")",
")",
"end",
"rescue",
"SendFailure",
"=>",
"e",
"# Send non-delivery response so that requester, e.g., RetryableRequest, can retry",
"result",
"=",
"OperationResult",
".",
"non_delivery",
"(",
"\"send failed unexpectedly\"",
")",
"handle_response",
"(",
"Result",
".",
"new",
"(",
"packet",
".",
"token",
",",
"@identity",
",",
"result",
",",
"@identity",
")",
")",
"end",
"true",
"end"
] | Send request via AMQP
If lack connectivity and queueing enabled, queue request
=== Parameters
kind(Symbol):: Kind of request: :send_push or :send_request
target(Hash|NilClass):: Target for request
packet(Push|Request):: Request packet to send
received_at(Time):: Time when request received
=== Block
Optional block used to process response asynchronously with the following parameter:
result(Result):: Response with an OperationResult of SUCCESS, RETRY, NON_DELIVERY, or ERROR
=== Return
true:: Always return true | [
"Send",
"request",
"via",
"AMQP",
"If",
"lack",
"connectivity",
"and",
"queueing",
"enabled",
"queue",
"request"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/sender.rb#L688-L712 |
691 | rightscale/right_agent | lib/right_agent/sender.rb | RightScale.Sender.amqp_send_once | def amqp_send_once(packet, ids = nil)
exchange = {:type => :fanout, :name => @request_queue, :options => {:durable => true, :no_declare => @secure}}
@agent.client.publish(exchange, packet, :persistent => packet.persistent, :mandatory => true,
:log_filter => [:tags, :target, :tries, :persistent], :brokers => ids)
rescue RightAMQP::HABrokerClient::NoConnectedBrokers => e
ErrorTracker.log(self, error = "Failed to publish request #{packet.trace} #{packet.type}", e, packet)
@send_failure_stats.update("NoConnectedBrokers")
raise TemporarilyOffline.new(error + " (#{e.class}: #{e.message})")
rescue StandardError => e
ErrorTracker.log(self, error = "Failed to publish request #{packet.trace} #{packet.type}", e, packet)
@send_failure_stats.update(e.class.name)
raise SendFailure.new(error + " (#{e.class}: #{e.message})")
end | ruby | def amqp_send_once(packet, ids = nil)
exchange = {:type => :fanout, :name => @request_queue, :options => {:durable => true, :no_declare => @secure}}
@agent.client.publish(exchange, packet, :persistent => packet.persistent, :mandatory => true,
:log_filter => [:tags, :target, :tries, :persistent], :brokers => ids)
rescue RightAMQP::HABrokerClient::NoConnectedBrokers => e
ErrorTracker.log(self, error = "Failed to publish request #{packet.trace} #{packet.type}", e, packet)
@send_failure_stats.update("NoConnectedBrokers")
raise TemporarilyOffline.new(error + " (#{e.class}: #{e.message})")
rescue StandardError => e
ErrorTracker.log(self, error = "Failed to publish request #{packet.trace} #{packet.type}", e, packet)
@send_failure_stats.update(e.class.name)
raise SendFailure.new(error + " (#{e.class}: #{e.message})")
end | [
"def",
"amqp_send_once",
"(",
"packet",
",",
"ids",
"=",
"nil",
")",
"exchange",
"=",
"{",
":type",
"=>",
":fanout",
",",
":name",
"=>",
"@request_queue",
",",
":options",
"=>",
"{",
":durable",
"=>",
"true",
",",
":no_declare",
"=>",
"@secure",
"}",
"}",
"@agent",
".",
"client",
".",
"publish",
"(",
"exchange",
",",
"packet",
",",
":persistent",
"=>",
"packet",
".",
"persistent",
",",
":mandatory",
"=>",
"true",
",",
":log_filter",
"=>",
"[",
":tags",
",",
":target",
",",
":tries",
",",
":persistent",
"]",
",",
":brokers",
"=>",
"ids",
")",
"rescue",
"RightAMQP",
"::",
"HABrokerClient",
"::",
"NoConnectedBrokers",
"=>",
"e",
"ErrorTracker",
".",
"log",
"(",
"self",
",",
"error",
"=",
"\"Failed to publish request #{packet.trace} #{packet.type}\"",
",",
"e",
",",
"packet",
")",
"@send_failure_stats",
".",
"update",
"(",
"\"NoConnectedBrokers\"",
")",
"raise",
"TemporarilyOffline",
".",
"new",
"(",
"error",
"+",
"\" (#{e.class}: #{e.message})\"",
")",
"rescue",
"StandardError",
"=>",
"e",
"ErrorTracker",
".",
"log",
"(",
"self",
",",
"error",
"=",
"\"Failed to publish request #{packet.trace} #{packet.type}\"",
",",
"e",
",",
"packet",
")",
"@send_failure_stats",
".",
"update",
"(",
"e",
".",
"class",
".",
"name",
")",
"raise",
"SendFailure",
".",
"new",
"(",
"error",
"+",
"\" (#{e.class}: #{e.message})\"",
")",
"end"
] | Send request via AMQP without retrying
Use mandatory flag to request return of message if it cannot be delivered
=== Parameters
packet(Push|Request):: Request packet to send
ids(Array|nil):: Identity of specific brokers to choose from, or nil if any okay
=== Return
(Array):: Identity of brokers to which request was published
=== Raise
SendFailure:: If sending of request failed unexpectedly
TemporarilyOffline:: If cannot send request because RightNet client currently disconnected
and offline queueing is disabled | [
"Send",
"request",
"via",
"AMQP",
"without",
"retrying",
"Use",
"mandatory",
"flag",
"to",
"request",
"return",
"of",
"message",
"if",
"it",
"cannot",
"be",
"delivered"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/sender.rb#L728-L740 |
692 | rightscale/right_agent | lib/right_agent/sender.rb | RightScale.Sender.amqp_send_retry | def amqp_send_retry(packet, parent_token, count = 0, multiplier = 1, elapsed = 0, broker_ids = nil)
check_broker_ids = amqp_send_once(packet, broker_ids)
if @retry_interval && @retry_timeout && parent_token
interval = [(@retry_interval * multiplier) + (@request_stats.avg_duration || 0), @retry_timeout - elapsed].min
EM.add_timer(interval) do
begin
if @pending_requests[parent_token]
count += 1
elapsed += interval
if elapsed < @retry_timeout && (packet.expires_at <= 0 || Time.now.to_i < packet.expires_at)
packet.tries << packet.token
packet.token = RightSupport::Data::UUID.generate
@pending_requests[parent_token].retry_parent_token = parent_token if count == 1
@pending_requests[packet.token] = @pending_requests[parent_token]
broker_ids ||= @agent.client.all
amqp_send_retry(packet, parent_token, count, multiplier * RETRY_BACKOFF_FACTOR, elapsed,
broker_ids.push(broker_ids.shift))
@retry_stats.update(packet.type.split('/').last)
else
Log.warning("RE-SEND TIMEOUT after #{elapsed.to_i} seconds for #{packet.trace} #{packet.type}")
result = OperationResult.non_delivery(OperationResult::RETRY_TIMEOUT)
handle_response(Result.new(packet.token, @identity, result, @identity))
end
@connectivity_checker.check(check_broker_ids.first) if check_broker_ids.any? && count == 1
end
rescue TemporarilyOffline => e
ErrorTracker.log(self, "Failed retry for #{packet.trace} #{packet.type} because temporarily offline")
rescue SendFailure => e
ErrorTracker.log(self, "Failed retry for #{packet.trace} #{packet.type} because of send failure")
rescue Exception => e
# Not sending a response here because something more basic is broken in the retry
# mechanism and don't want an error response to preempt a delayed actual response
ErrorTracker.log(self, "Failed retry for #{packet.trace} #{packet.type} without responding", e, packet)
end
end
end
true
end | ruby | def amqp_send_retry(packet, parent_token, count = 0, multiplier = 1, elapsed = 0, broker_ids = nil)
check_broker_ids = amqp_send_once(packet, broker_ids)
if @retry_interval && @retry_timeout && parent_token
interval = [(@retry_interval * multiplier) + (@request_stats.avg_duration || 0), @retry_timeout - elapsed].min
EM.add_timer(interval) do
begin
if @pending_requests[parent_token]
count += 1
elapsed += interval
if elapsed < @retry_timeout && (packet.expires_at <= 0 || Time.now.to_i < packet.expires_at)
packet.tries << packet.token
packet.token = RightSupport::Data::UUID.generate
@pending_requests[parent_token].retry_parent_token = parent_token if count == 1
@pending_requests[packet.token] = @pending_requests[parent_token]
broker_ids ||= @agent.client.all
amqp_send_retry(packet, parent_token, count, multiplier * RETRY_BACKOFF_FACTOR, elapsed,
broker_ids.push(broker_ids.shift))
@retry_stats.update(packet.type.split('/').last)
else
Log.warning("RE-SEND TIMEOUT after #{elapsed.to_i} seconds for #{packet.trace} #{packet.type}")
result = OperationResult.non_delivery(OperationResult::RETRY_TIMEOUT)
handle_response(Result.new(packet.token, @identity, result, @identity))
end
@connectivity_checker.check(check_broker_ids.first) if check_broker_ids.any? && count == 1
end
rescue TemporarilyOffline => e
ErrorTracker.log(self, "Failed retry for #{packet.trace} #{packet.type} because temporarily offline")
rescue SendFailure => e
ErrorTracker.log(self, "Failed retry for #{packet.trace} #{packet.type} because of send failure")
rescue Exception => e
# Not sending a response here because something more basic is broken in the retry
# mechanism and don't want an error response to preempt a delayed actual response
ErrorTracker.log(self, "Failed retry for #{packet.trace} #{packet.type} without responding", e, packet)
end
end
end
true
end | [
"def",
"amqp_send_retry",
"(",
"packet",
",",
"parent_token",
",",
"count",
"=",
"0",
",",
"multiplier",
"=",
"1",
",",
"elapsed",
"=",
"0",
",",
"broker_ids",
"=",
"nil",
")",
"check_broker_ids",
"=",
"amqp_send_once",
"(",
"packet",
",",
"broker_ids",
")",
"if",
"@retry_interval",
"&&",
"@retry_timeout",
"&&",
"parent_token",
"interval",
"=",
"[",
"(",
"@retry_interval",
"*",
"multiplier",
")",
"+",
"(",
"@request_stats",
".",
"avg_duration",
"||",
"0",
")",
",",
"@retry_timeout",
"-",
"elapsed",
"]",
".",
"min",
"EM",
".",
"add_timer",
"(",
"interval",
")",
"do",
"begin",
"if",
"@pending_requests",
"[",
"parent_token",
"]",
"count",
"+=",
"1",
"elapsed",
"+=",
"interval",
"if",
"elapsed",
"<",
"@retry_timeout",
"&&",
"(",
"packet",
".",
"expires_at",
"<=",
"0",
"||",
"Time",
".",
"now",
".",
"to_i",
"<",
"packet",
".",
"expires_at",
")",
"packet",
".",
"tries",
"<<",
"packet",
".",
"token",
"packet",
".",
"token",
"=",
"RightSupport",
"::",
"Data",
"::",
"UUID",
".",
"generate",
"@pending_requests",
"[",
"parent_token",
"]",
".",
"retry_parent_token",
"=",
"parent_token",
"if",
"count",
"==",
"1",
"@pending_requests",
"[",
"packet",
".",
"token",
"]",
"=",
"@pending_requests",
"[",
"parent_token",
"]",
"broker_ids",
"||=",
"@agent",
".",
"client",
".",
"all",
"amqp_send_retry",
"(",
"packet",
",",
"parent_token",
",",
"count",
",",
"multiplier",
"*",
"RETRY_BACKOFF_FACTOR",
",",
"elapsed",
",",
"broker_ids",
".",
"push",
"(",
"broker_ids",
".",
"shift",
")",
")",
"@retry_stats",
".",
"update",
"(",
"packet",
".",
"type",
".",
"split",
"(",
"'/'",
")",
".",
"last",
")",
"else",
"Log",
".",
"warning",
"(",
"\"RE-SEND TIMEOUT after #{elapsed.to_i} seconds for #{packet.trace} #{packet.type}\"",
")",
"result",
"=",
"OperationResult",
".",
"non_delivery",
"(",
"OperationResult",
"::",
"RETRY_TIMEOUT",
")",
"handle_response",
"(",
"Result",
".",
"new",
"(",
"packet",
".",
"token",
",",
"@identity",
",",
"result",
",",
"@identity",
")",
")",
"end",
"@connectivity_checker",
".",
"check",
"(",
"check_broker_ids",
".",
"first",
")",
"if",
"check_broker_ids",
".",
"any?",
"&&",
"count",
"==",
"1",
"end",
"rescue",
"TemporarilyOffline",
"=>",
"e",
"ErrorTracker",
".",
"log",
"(",
"self",
",",
"\"Failed retry for #{packet.trace} #{packet.type} because temporarily offline\"",
")",
"rescue",
"SendFailure",
"=>",
"e",
"ErrorTracker",
".",
"log",
"(",
"self",
",",
"\"Failed retry for #{packet.trace} #{packet.type} because of send failure\"",
")",
"rescue",
"Exception",
"=>",
"e",
"# Not sending a response here because something more basic is broken in the retry",
"# mechanism and don't want an error response to preempt a delayed actual response",
"ErrorTracker",
".",
"log",
"(",
"self",
",",
"\"Failed retry for #{packet.trace} #{packet.type} without responding\"",
",",
"e",
",",
"packet",
")",
"end",
"end",
"end",
"true",
"end"
] | Send request via AMQP with one or more retries if do not receive a response in time
Send timeout result if reach configured retry timeout limit
Use exponential backoff with RETRY_BACKOFF_FACTOR for retry spacing
Adjust retry interval by average response time to avoid adding to system load
when system gets slow
Rotate through brokers on retries
Check connectivity after first retry timeout
=== Parameters
packet(Request):: Request packet to send
parent_token(String):: Token for original request
count(Integer):: Number of retries so far
multiplier(Integer):: Multiplier for retry interval for exponential backoff
elapsed(Integer):: Elapsed time in seconds since this request was first attempted
broker_ids(Array):: Identity of brokers to be used in priority order
=== Return
true:: Always return true | [
"Send",
"request",
"via",
"AMQP",
"with",
"one",
"or",
"more",
"retries",
"if",
"do",
"not",
"receive",
"a",
"response",
"in",
"time",
"Send",
"timeout",
"result",
"if",
"reach",
"configured",
"retry",
"timeout",
"limit",
"Use",
"exponential",
"backoff",
"with",
"RETRY_BACKOFF_FACTOR",
"for",
"retry",
"spacing",
"Adjust",
"retry",
"interval",
"by",
"average",
"response",
"time",
"to",
"avoid",
"adding",
"to",
"system",
"load",
"when",
"system",
"gets",
"slow",
"Rotate",
"through",
"brokers",
"on",
"retries",
"Check",
"connectivity",
"after",
"first",
"retry",
"timeout"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/sender.rb#L760-L798 |
693 | rightscale/right_agent | lib/right_agent/sender.rb | RightScale.Sender.deliver_response | def deliver_response(response, pending_request)
@request_stats.finish(pending_request.receive_time, response.token)
@pending_requests.delete(response.token) if pending_request.kind == :send_request
if (parent_token = pending_request.retry_parent_token)
@pending_requests.reject! { |k, v| k == parent_token || v.retry_parent_token == parent_token }
end
pending_request.response_handler.call(response) if pending_request.response_handler
true
end | ruby | def deliver_response(response, pending_request)
@request_stats.finish(pending_request.receive_time, response.token)
@pending_requests.delete(response.token) if pending_request.kind == :send_request
if (parent_token = pending_request.retry_parent_token)
@pending_requests.reject! { |k, v| k == parent_token || v.retry_parent_token == parent_token }
end
pending_request.response_handler.call(response) if pending_request.response_handler
true
end | [
"def",
"deliver_response",
"(",
"response",
",",
"pending_request",
")",
"@request_stats",
".",
"finish",
"(",
"pending_request",
".",
"receive_time",
",",
"response",
".",
"token",
")",
"@pending_requests",
".",
"delete",
"(",
"response",
".",
"token",
")",
"if",
"pending_request",
".",
"kind",
"==",
":send_request",
"if",
"(",
"parent_token",
"=",
"pending_request",
".",
"retry_parent_token",
")",
"@pending_requests",
".",
"reject!",
"{",
"|",
"k",
",",
"v",
"|",
"k",
"==",
"parent_token",
"||",
"v",
".",
"retry_parent_token",
"==",
"parent_token",
"}",
"end",
"pending_request",
".",
"response_handler",
".",
"call",
"(",
"response",
")",
"if",
"pending_request",
".",
"response_handler",
"true",
"end"
] | Deliver the response and remove associated non-push requests from pending
including all associated retry requests
=== Parameters
response(Result):: Packet received as result of request
pending_request(Hash):: Associated pending request
=== Return
true:: Always return true | [
"Deliver",
"the",
"response",
"and",
"remove",
"associated",
"non",
"-",
"push",
"requests",
"from",
"pending",
"including",
"all",
"associated",
"retry",
"requests"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/sender.rb#L809-L819 |
694 | rightscale/right_agent | lib/right_agent/clients/right_http_client.rb | RightScale.RightHttpClient.init | def init(auth_client, options = {})
raise ArgumentError, "No authorization client provided" unless auth_client.is_a?(AuthClient)
@status = {}
callback = lambda { |type, state| update_status(type, state) }
@auth = auth_client
@status[:auth] = @auth.status(&callback)
@router = RouterClient.new(@auth, options)
@status[:router] = @router.status(&callback)
if @auth.api_url
@api = ApiClient.new(@auth, options)
@status[:api] = @api.status(&callback)
end
true
end | ruby | def init(auth_client, options = {})
raise ArgumentError, "No authorization client provided" unless auth_client.is_a?(AuthClient)
@status = {}
callback = lambda { |type, state| update_status(type, state) }
@auth = auth_client
@status[:auth] = @auth.status(&callback)
@router = RouterClient.new(@auth, options)
@status[:router] = @router.status(&callback)
if @auth.api_url
@api = ApiClient.new(@auth, options)
@status[:api] = @api.status(&callback)
end
true
end | [
"def",
"init",
"(",
"auth_client",
",",
"options",
"=",
"{",
"}",
")",
"raise",
"ArgumentError",
",",
"\"No authorization client provided\"",
"unless",
"auth_client",
".",
"is_a?",
"(",
"AuthClient",
")",
"@status",
"=",
"{",
"}",
"callback",
"=",
"lambda",
"{",
"|",
"type",
",",
"state",
"|",
"update_status",
"(",
"type",
",",
"state",
")",
"}",
"@auth",
"=",
"auth_client",
"@status",
"[",
":auth",
"]",
"=",
"@auth",
".",
"status",
"(",
"callback",
")",
"@router",
"=",
"RouterClient",
".",
"new",
"(",
"@auth",
",",
"options",
")",
"@status",
"[",
":router",
"]",
"=",
"@router",
".",
"status",
"(",
"callback",
")",
"if",
"@auth",
".",
"api_url",
"@api",
"=",
"ApiClient",
".",
"new",
"(",
"@auth",
",",
"options",
")",
"@status",
"[",
":api",
"]",
"=",
"@api",
".",
"status",
"(",
"callback",
")",
"end",
"true",
"end"
] | Initialize RightNet client
Must be called before any other functions are usable
@param [AuthClient] auth_client providing authorization session for HTTP requests
@option options [Numeric] :open_timeout maximum wait for connection
@option options [Numeric] :request_timeout maximum wait for response
@option options [Numeric] :listen_timeout maximum wait for event when long-polling
@option options [Numeric] :retry_timeout maximum before stop retrying
@option options [Array] :retry_intervals between successive retries
@option options [Boolean] :retry_enabled for requests that fail to connect or that return a retry result
@option options [Boolean] :non_blocking i/o is to be used for HTTP requests by applying
EM::HttpRequest and fibers instead of RestClient; requests remain synchronous
@option options [Boolean] :long_polling_only never attempt to create a WebSocket, always long-polling instead
@option options [Array] :filter_params symbols or strings for names of request parameters whose
values are to be hidden when logging; also applied to contents of any parameters named :payload
@return [TrueClass] always true
@raise [ArgumentError] no auth client | [
"Initialize",
"RightNet",
"client",
"Must",
"be",
"called",
"before",
"any",
"other",
"functions",
"are",
"usable"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/right_http_client.rb#L58-L71 |
695 | rightscale/right_agent | lib/right_agent/clients/right_http_client.rb | RightScale.RightHttpClient.push | def push(type, payload = nil, target = nil, options = {})
raise RuntimeError, "#{self.class.name}#init was not called" unless @auth
client = (@api && @api.support?(type)) ? @api : @router
client.push(type, payload, target, options)
end | ruby | def push(type, payload = nil, target = nil, options = {})
raise RuntimeError, "#{self.class.name}#init was not called" unless @auth
client = (@api && @api.support?(type)) ? @api : @router
client.push(type, payload, target, options)
end | [
"def",
"push",
"(",
"type",
",",
"payload",
"=",
"nil",
",",
"target",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
")",
"raise",
"RuntimeError",
",",
"\"#{self.class.name}#init was not called\"",
"unless",
"@auth",
"client",
"=",
"(",
"@api",
"&&",
"@api",
".",
"support?",
"(",
"type",
")",
")",
"?",
"@api",
":",
"@router",
"client",
".",
"push",
"(",
"type",
",",
"payload",
",",
"target",
",",
"options",
")",
"end"
] | Route a request to a single target or multiple targets with no response expected
Persist the request en route to reduce the chance of it being lost at the expense of some
additional network overhead
Enqueue the request if the target is not currently available
Never automatically retry the request if there is the possibility of it being duplicated
Set time-to-live to be forever
@param [String] type of request as path specifying actor and action
@param [Hash, NilClass] payload for request
@param [String, Hash, NilClass] target for request, which may be identity of specific
target, hash for selecting potentially multiple targets, or nil if routing solely
using type; hash may contain:
[Array] :tags that must all be associated with a target for it to be selected
[Hash] :scope for restricting routing which may contain:
[Integer] :account id that agents must be associated with to be included
[Integer] :shard id that agents must be in to be included, or if value is
Packet::GLOBAL, ones with no shard id
[Symbol] :selector for picking from qualified targets: :any or :all;
defaults to :any
@option options [String] :request_uuid uniquely identifying this request; defaults to
randomly generated
@option options [Numeric] :time_to_live seconds before request expires and is to be ignored;
non-positive value or nil means never expire
@return [NilClass] always nil since there is no expected response to the request
@raise [RuntimeError] init was not called
@raise [Exceptions::Unauthorized] authorization failed
@raise [Exceptions::ConnectivityFailure] cannot connect to server, lost connection
to it, or it is out of service or too busy to respond
@raise [Exceptions::RetryableError] request failed but if retried may succeed
@raise [Exceptions::Terminating] closing client and terminating service
@raise [Exceptions::InternalServerError] internal error in server being accessed | [
"Route",
"a",
"request",
"to",
"a",
"single",
"target",
"or",
"multiple",
"targets",
"with",
"no",
"response",
"expected",
"Persist",
"the",
"request",
"en",
"route",
"to",
"reduce",
"the",
"chance",
"of",
"it",
"being",
"lost",
"at",
"the",
"expense",
"of",
"some",
"additional",
"network",
"overhead",
"Enqueue",
"the",
"request",
"if",
"the",
"target",
"is",
"not",
"currently",
"available",
"Never",
"automatically",
"retry",
"the",
"request",
"if",
"there",
"is",
"the",
"possibility",
"of",
"it",
"being",
"duplicated",
"Set",
"time",
"-",
"to",
"-",
"live",
"to",
"be",
"forever"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/right_http_client.rb#L107-L111 |
696 | rightscale/right_agent | lib/right_agent/clients/right_http_client.rb | RightScale.RightHttpClient.communicated | def communicated(types = [], &callback)
raise RuntimeError, "#{self.class.name}#init was not called" unless @auth
@auth.communicated(&callback) if types.empty? || types.include?(:auth)
@api.communicated(&callback) if @api && (types.empty? || types.include?(:api))
@router.communicated(&callback) if @router && (types.empty? || types.include?(:router))
true
end | ruby | def communicated(types = [], &callback)
raise RuntimeError, "#{self.class.name}#init was not called" unless @auth
@auth.communicated(&callback) if types.empty? || types.include?(:auth)
@api.communicated(&callback) if @api && (types.empty? || types.include?(:api))
@router.communicated(&callback) if @router && (types.empty? || types.include?(:router))
true
end | [
"def",
"communicated",
"(",
"types",
"=",
"[",
"]",
",",
"&",
"callback",
")",
"raise",
"RuntimeError",
",",
"\"#{self.class.name}#init was not called\"",
"unless",
"@auth",
"@auth",
".",
"communicated",
"(",
"callback",
")",
"if",
"types",
".",
"empty?",
"||",
"types",
".",
"include?",
"(",
":auth",
")",
"@api",
".",
"communicated",
"(",
"callback",
")",
"if",
"@api",
"&&",
"(",
"types",
".",
"empty?",
"||",
"types",
".",
"include?",
"(",
":api",
")",
")",
"@router",
".",
"communicated",
"(",
"callback",
")",
"if",
"@router",
"&&",
"(",
"types",
".",
"empty?",
"||",
"types",
".",
"include?",
"(",
":router",
")",
")",
"true",
"end"
] | Set callback for each successful communication excluding health checks
@param [Array] types of server: :auth, :api, or :router; defaults to all
@yield [] required block executed after successful communication
@return [TrueClass] always true
@raise [RuntimeError] init was not called | [
"Set",
"callback",
"for",
"each",
"successful",
"communication",
"excluding",
"health",
"checks"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/right_http_client.rb#L221-L227 |
697 | rightscale/right_agent | lib/right_agent/enrollment_result.rb | RightScale.EnrollmentResult.to_s | def to_s
@serializer.dump({
'r_s_version' => @r_s_version.to_s,
'timestamp' => @timestamp.to_i.to_s,
'iv' => Base64::encode64(@iv).chop,
'ciphertext' => Base64::encode64(@ciphertext).chop,
'mac' => Base64::encode64(@mac).chop
})
end | ruby | def to_s
@serializer.dump({
'r_s_version' => @r_s_version.to_s,
'timestamp' => @timestamp.to_i.to_s,
'iv' => Base64::encode64(@iv).chop,
'ciphertext' => Base64::encode64(@ciphertext).chop,
'mac' => Base64::encode64(@mac).chop
})
end | [
"def",
"to_s",
"@serializer",
".",
"dump",
"(",
"{",
"'r_s_version'",
"=>",
"@r_s_version",
".",
"to_s",
",",
"'timestamp'",
"=>",
"@timestamp",
".",
"to_i",
".",
"to_s",
",",
"'iv'",
"=>",
"Base64",
"::",
"encode64",
"(",
"@iv",
")",
".",
"chop",
",",
"'ciphertext'",
"=>",
"Base64",
"::",
"encode64",
"(",
"@ciphertext",
")",
".",
"chop",
",",
"'mac'",
"=>",
"Base64",
"::",
"encode64",
"(",
"@mac",
")",
".",
"chop",
"}",
")",
"end"
] | Create a new instance of this class
=== Parameters
timestamp(Time):: Timestamp associated with this result
router_cert(String):: Arbitrary string
id_cert(String):: Arbitrary string
id_key(String):: Arbitrary string
secret(String):: Shared secret with which the result is encrypted
Serialize an enrollment result
=== Parameters
obj(EnrollmentResult):: Object to serialize
=== Return
(String):: Serialized object | [
"Create",
"a",
"new",
"instance",
"of",
"this",
"class"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/enrollment_result.rb#L76-L84 |
698 | rightscale/right_agent | lib/right_agent/clients/auth_client.rb | RightScale.AuthClient.check_authorized | def check_authorized
if state == :expired
raise Exceptions::RetryableError, "Authorization expired"
elsif state != :authorized
raise Exceptions::Unauthorized, "Not authorized with RightScale" if state != :authorized
end
true
end | ruby | def check_authorized
if state == :expired
raise Exceptions::RetryableError, "Authorization expired"
elsif state != :authorized
raise Exceptions::Unauthorized, "Not authorized with RightScale" if state != :authorized
end
true
end | [
"def",
"check_authorized",
"if",
"state",
"==",
":expired",
"raise",
"Exceptions",
"::",
"RetryableError",
",",
"\"Authorization expired\"",
"elsif",
"state",
"!=",
":authorized",
"raise",
"Exceptions",
"::",
"Unauthorized",
",",
"\"Not authorized with RightScale\"",
"if",
"state",
"!=",
":authorized",
"end",
"true",
"end"
] | Check whether authorized
@return [TrueClass] always true if don't raise exception
@raise [Exceptions::Unauthorized] not authorized
@raise [Exceptions::RetryableError] authorization expired, but retry may succeed | [
"Check",
"whether",
"authorized"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/auth_client.rb#L201-L208 |
699 | rightscale/right_agent | lib/right_agent/core_payload_types/dev_repository.rb | RightScale.DevRepository.to_scraper_hash | def to_scraper_hash
repo = {}
repo[:repo_type] = repo_type.to_sym unless repo_type.nil?
repo[:url] = url
repo[:tag] = tag
repo[:resources_path] = cookbooks_path
if !ssh_key.nil?
repo[:first_credential] = ssh_key
elsif !(username.nil? && password.nil?)
repo[:first_credential] = dev_repo.username
repo[:second_credential] = dev_repo.password
end
repo
end | ruby | def to_scraper_hash
repo = {}
repo[:repo_type] = repo_type.to_sym unless repo_type.nil?
repo[:url] = url
repo[:tag] = tag
repo[:resources_path] = cookbooks_path
if !ssh_key.nil?
repo[:first_credential] = ssh_key
elsif !(username.nil? && password.nil?)
repo[:first_credential] = dev_repo.username
repo[:second_credential] = dev_repo.password
end
repo
end | [
"def",
"to_scraper_hash",
"repo",
"=",
"{",
"}",
"repo",
"[",
":repo_type",
"]",
"=",
"repo_type",
".",
"to_sym",
"unless",
"repo_type",
".",
"nil?",
"repo",
"[",
":url",
"]",
"=",
"url",
"repo",
"[",
":tag",
"]",
"=",
"tag",
"repo",
"[",
":resources_path",
"]",
"=",
"cookbooks_path",
"if",
"!",
"ssh_key",
".",
"nil?",
"repo",
"[",
":first_credential",
"]",
"=",
"ssh_key",
"elsif",
"!",
"(",
"username",
".",
"nil?",
"&&",
"password",
".",
"nil?",
")",
"repo",
"[",
":first_credential",
"]",
"=",
"dev_repo",
".",
"username",
"repo",
"[",
":second_credential",
"]",
"=",
"dev_repo",
".",
"password",
"end",
"repo",
"end"
] | Maps the given DevRepository to a has that can be consumed by the RightScraper gem
=== Returns
(Hash)::
:repo_type (Symbol):: Type of repository: one of :git, :svn, :download or :local
* :git denotes a 'git' repository that should be retrieved via 'git clone'
* :svn denotes a 'svn' repository that should be retrieved via 'svn checkout'
* :download denotes a tar ball that should be retrieved via HTTP GET (HTTPS if uri starts with https://)
* :local denotes cookbook that is already local and doesn't need to be retrieved
:url (String):: URL to repository (e.g. git://github.com/opscode/chef-repo.git)
:tag (String):: git commit or svn branch that should be used to retrieve repository
Optional, use 'master' for git and 'trunk' for svn if tag is nil.
Not used for raw repositories.
:cookbooks_path (Array):: Path to cookbooks inside repostory
Optional (use location of repository as cookbook path if nil)
:first_credential (String):: Either the Private SSH key used to retrieve git repositories, or the Username used to retrieve svn and raw repositories
:second_credential (String):: Password used to retrieve svn and raw repositories | [
"Maps",
"the",
"given",
"DevRepository",
"to",
"a",
"has",
"that",
"can",
"be",
"consumed",
"by",
"the",
"RightScraper",
"gem"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/core_payload_types/dev_repository.rb#L93-L106 |
Subsets and Splits