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
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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", "]", "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", "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
train
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", ")", "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
train
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
train
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
train
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
train
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
train
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
train
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
train
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", ")", "agent_names", "=", "if", "options", "[", ":agent_name", "]", "[", "options", "[", ":agent_name", "]", "]", "else", "AgentConfig", ".", "cfg_agents", "end", "fail", "(", "\"No agents configured\"", ")", "if", "agent_names", ".", "empty?", "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
train
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
train
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", "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
train
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", "@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
train
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
train
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
train
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
train
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
train
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
train
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
train
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", ")", "AgentConfig", ".", "root_dir", "=", "options", "[", ":root_dir", "]", "AgentConfig", ".", "cfg_dir", "=", "options", "[", ":cfg_dir", "]", "AgentConfig", ".", "pid_dir", "=", "options", "[", ":pid_dir", "]", "cfg", "=", "load_init_cfg", "check_agent", "(", "options", ",", "cfg", ")", "cfg", "=", "configure", "(", "options", ",", "cfg", ")", "persist", "(", "options", ",", "cfg", ")", "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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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", "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", "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
train
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
train
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
train
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
train
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
train
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
train
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", "if", "e", ".", "respond_to?", "(", ":http_body", ")", "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
train
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?", "@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", "result", "=", "OperationResult", ".", "retry", "(", "\"lost RightNet connectivity\"", ")", "handle_response", "(", "Result", ".", "new", "(", "packet", ".", "token", ",", "@identity", ",", "result", ",", "@identity", ")", ")", "end", "rescue", "SendFailure", "=>", "e", "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
train
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
train
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", "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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
rightscale/right_agent
lib/right_agent/core_payload_types/planned_volume.rb
RightScale.PlannedVolume.is_valid?
def is_valid? result = false == is_blank?(@volume_id) && false == is_blank?(@device_name) && false == is_blank?(@volume_status) && false == is_blank?(@mount_points) && nil == @mount_points.find { |mount_point| is_blank?(mount_point) } return result end
ruby
def is_valid? result = false == is_blank?(@volume_id) && false == is_blank?(@device_name) && false == is_blank?(@volume_status) && false == is_blank?(@mount_points) && nil == @mount_points.find { |mount_point| is_blank?(mount_point) } return result end
[ "def", "is_valid?", "result", "=", "false", "==", "is_blank?", "(", "@volume_id", ")", "&&", "false", "==", "is_blank?", "(", "@device_name", ")", "&&", "false", "==", "is_blank?", "(", "@volume_status", ")", "&&", "false", "==", "is_blank?", "(", "@mount_points", ")", "&&", "nil", "==", "@mount_points", ".", "find", "{", "|", "mount_point", "|", "is_blank?", "(", "mount_point", ")", "}", "return", "result", "end" ]
Determines if this object is valid. === Return result(Boolean):: true if this object is valid, false if required fields are nil or empty
[ "Determines", "if", "this", "object", "is", "valid", "." ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/core_payload_types/planned_volume.rb#L71-L78
train
rightscale/right_agent
lib/right_agent/agent.rb
RightScale.Agent.run
def run Log.init(@identity, @options[:log_path], :print => true) Log.level = @options[:log_level] if @options[:log_level] RightSupport::Log::Mixin.default_logger = Log ErrorTracker.init(self, @options[:agent_name], :shard_id => @options[:shard_id], :trace_level => TRACE_LEVEL, :airbrake_endpoint => @options[:airbrake_endpoint], :airbrake_api_key => @options[:airbrake_api_key]) @history.update("start") now = Time.now Log.info("[start] Agent #{@identity} starting; time: #{now.utc}; utc_offset: #{now.utc_offset}") @options.each { |k, v| Log.info("- #{k}: #{k.to_s =~ /pass/ ? '****' : (v.respond_to?(:each) ? v.inspect : v)}") } begin # Capture process id in file after optional daemonize pid_file = PidFile.new(@identity) pid_file.check daemonize(@identity, @options) if @options[:daemonize] pid_file.write at_exit { pid_file.remove } if @mode == :http # HTTP is being used for RightNet communication instead of AMQP # The code loaded with the actors specific to this application # is responsible to call setup_http at the appropriate time start_service else # Initiate AMQP broker connection, wait for connection before proceeding # otherwise messages published on failed connection will be lost @client = RightAMQP::HABrokerClient.new(Serializer.new(:secure), @options.merge(:exception_stats => ErrorTracker.exception_stats)) @queues.each { |s| @remaining_queue_setup[s] = @client.all } @client.connection_status(:one_off => @options[:connect_timeout]) do |status| if status == :connected # Need to give EM (on Windows) a chance to respond to the AMQP handshake # before doing anything interesting to prevent AMQP handshake from # timing-out; delay post-connected activity a second EM_S.add_timer(1) { start_service } elsif status == :failed terminate("failed to connect to any brokers during startup") elsif status == :timeout terminate("failed to connect to any brokers after #{@options[:connect_timeout]} seconds during startup") else terminate("broker connect attempt failed unexpectedly with status #{status} during startup") end end end rescue PidFile::AlreadyRunning EM.stop if EM.reactor_running? raise rescue StandardError => e terminate("failed startup", e) end true end
ruby
def run Log.init(@identity, @options[:log_path], :print => true) Log.level = @options[:log_level] if @options[:log_level] RightSupport::Log::Mixin.default_logger = Log ErrorTracker.init(self, @options[:agent_name], :shard_id => @options[:shard_id], :trace_level => TRACE_LEVEL, :airbrake_endpoint => @options[:airbrake_endpoint], :airbrake_api_key => @options[:airbrake_api_key]) @history.update("start") now = Time.now Log.info("[start] Agent #{@identity} starting; time: #{now.utc}; utc_offset: #{now.utc_offset}") @options.each { |k, v| Log.info("- #{k}: #{k.to_s =~ /pass/ ? '****' : (v.respond_to?(:each) ? v.inspect : v)}") } begin # Capture process id in file after optional daemonize pid_file = PidFile.new(@identity) pid_file.check daemonize(@identity, @options) if @options[:daemonize] pid_file.write at_exit { pid_file.remove } if @mode == :http # HTTP is being used for RightNet communication instead of AMQP # The code loaded with the actors specific to this application # is responsible to call setup_http at the appropriate time start_service else # Initiate AMQP broker connection, wait for connection before proceeding # otherwise messages published on failed connection will be lost @client = RightAMQP::HABrokerClient.new(Serializer.new(:secure), @options.merge(:exception_stats => ErrorTracker.exception_stats)) @queues.each { |s| @remaining_queue_setup[s] = @client.all } @client.connection_status(:one_off => @options[:connect_timeout]) do |status| if status == :connected # Need to give EM (on Windows) a chance to respond to the AMQP handshake # before doing anything interesting to prevent AMQP handshake from # timing-out; delay post-connected activity a second EM_S.add_timer(1) { start_service } elsif status == :failed terminate("failed to connect to any brokers during startup") elsif status == :timeout terminate("failed to connect to any brokers after #{@options[:connect_timeout]} seconds during startup") else terminate("broker connect attempt failed unexpectedly with status #{status} during startup") end end end rescue PidFile::AlreadyRunning EM.stop if EM.reactor_running? raise rescue StandardError => e terminate("failed startup", e) end true end
[ "def", "run", "Log", ".", "init", "(", "@identity", ",", "@options", "[", ":log_path", "]", ",", ":print", "=>", "true", ")", "Log", ".", "level", "=", "@options", "[", ":log_level", "]", "if", "@options", "[", ":log_level", "]", "RightSupport", "::", "Log", "::", "Mixin", ".", "default_logger", "=", "Log", "ErrorTracker", ".", "init", "(", "self", ",", "@options", "[", ":agent_name", "]", ",", ":shard_id", "=>", "@options", "[", ":shard_id", "]", ",", ":trace_level", "=>", "TRACE_LEVEL", ",", ":airbrake_endpoint", "=>", "@options", "[", ":airbrake_endpoint", "]", ",", ":airbrake_api_key", "=>", "@options", "[", ":airbrake_api_key", "]", ")", "@history", ".", "update", "(", "\"start\"", ")", "now", "=", "Time", ".", "now", "Log", ".", "info", "(", "\"[start] Agent #{@identity} starting; time: #{now.utc}; utc_offset: #{now.utc_offset}\"", ")", "@options", ".", "each", "{", "|", "k", ",", "v", "|", "Log", ".", "info", "(", "\"- #{k}: #{k.to_s =~ /pass/ ? '****' : (v.respond_to?(:each) ? v.inspect : v)}\"", ")", "}", "begin", "pid_file", "=", "PidFile", ".", "new", "(", "@identity", ")", "pid_file", ".", "check", "daemonize", "(", "@identity", ",", "@options", ")", "if", "@options", "[", ":daemonize", "]", "pid_file", ".", "write", "at_exit", "{", "pid_file", ".", "remove", "}", "if", "@mode", "==", ":http", "start_service", "else", "@client", "=", "RightAMQP", "::", "HABrokerClient", ".", "new", "(", "Serializer", ".", "new", "(", ":secure", ")", ",", "@options", ".", "merge", "(", ":exception_stats", "=>", "ErrorTracker", ".", "exception_stats", ")", ")", "@queues", ".", "each", "{", "|", "s", "|", "@remaining_queue_setup", "[", "s", "]", "=", "@client", ".", "all", "}", "@client", ".", "connection_status", "(", ":one_off", "=>", "@options", "[", ":connect_timeout", "]", ")", "do", "|", "status", "|", "if", "status", "==", ":connected", "EM_S", ".", "add_timer", "(", "1", ")", "{", "start_service", "}", "elsif", "status", "==", ":failed", "terminate", "(", "\"failed to connect to any brokers during startup\"", ")", "elsif", "status", "==", ":timeout", "terminate", "(", "\"failed to connect to any brokers after #{@options[:connect_timeout]} seconds during startup\"", ")", "else", "terminate", "(", "\"broker connect attempt failed unexpectedly with status #{status} during startup\"", ")", "end", "end", "end", "rescue", "PidFile", "::", "AlreadyRunning", "EM", ".", "stop", "if", "EM", ".", "reactor_running?", "raise", "rescue", "StandardError", "=>", "e", "terminate", "(", "\"failed startup\"", ",", "e", ")", "end", "true", "end" ]
Initialize the new agent === Parameters opts(Hash):: Configuration options per start method above === Return true:: Always return true Put the agent in service This requires making a RightNet connection via HTTP or AMQP and other initialization like loading actors === Return true:: Always return true
[ "Initialize", "the", "new", "agent" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/agent.rb#L196-L248
train
rightscale/right_agent
lib/right_agent/agent.rb
RightScale.Agent.connect
def connect(host, port, index, priority = nil, force = false) @connect_request_stats.update("connect b#{index}") even_if = " even if already connected" if force Log.info("Connecting to broker at host #{host.inspect} port #{port.inspect} " + "index #{index.inspect} priority #{priority.inspect}#{even_if}") Log.info("Current broker configuration: #{@client.status.inspect}") result = nil begin @client.connect(host, port, index, priority, force) do |id| @client.connection_status(:one_off => @options[:connect_timeout], :brokers => [id]) do |status| begin if status == :connected setup_queues([id]) remaining = 0 @remaining_queue_setup.each_value { |ids| remaining += ids.size } Log.info("[setup] Finished subscribing to queues after reconnecting to broker #{id}") if remaining == 0 unless update_configuration(:host => @client.hosts, :port => @client.ports) Log.warning("Successfully connected to broker #{id} but failed to update config file") end else ErrorTracker.log(self, "Failed to connect to broker #{id}, status #{status.inspect}") end rescue Exception => e ErrorTracker.log(self, "Failed to connect to broker #{id}, status #{status.inspect}", e) end end end rescue StandardError => e ErrorTracker.log(self, msg = "Failed to connect to broker at host #{host.inspect} and port #{port.inspect}", e) result = Log.format(msg, e) end result end
ruby
def connect(host, port, index, priority = nil, force = false) @connect_request_stats.update("connect b#{index}") even_if = " even if already connected" if force Log.info("Connecting to broker at host #{host.inspect} port #{port.inspect} " + "index #{index.inspect} priority #{priority.inspect}#{even_if}") Log.info("Current broker configuration: #{@client.status.inspect}") result = nil begin @client.connect(host, port, index, priority, force) do |id| @client.connection_status(:one_off => @options[:connect_timeout], :brokers => [id]) do |status| begin if status == :connected setup_queues([id]) remaining = 0 @remaining_queue_setup.each_value { |ids| remaining += ids.size } Log.info("[setup] Finished subscribing to queues after reconnecting to broker #{id}") if remaining == 0 unless update_configuration(:host => @client.hosts, :port => @client.ports) Log.warning("Successfully connected to broker #{id} but failed to update config file") end else ErrorTracker.log(self, "Failed to connect to broker #{id}, status #{status.inspect}") end rescue Exception => e ErrorTracker.log(self, "Failed to connect to broker #{id}, status #{status.inspect}", e) end end end rescue StandardError => e ErrorTracker.log(self, msg = "Failed to connect to broker at host #{host.inspect} and port #{port.inspect}", e) result = Log.format(msg, e) end result end
[ "def", "connect", "(", "host", ",", "port", ",", "index", ",", "priority", "=", "nil", ",", "force", "=", "false", ")", "@connect_request_stats", ".", "update", "(", "\"connect b#{index}\"", ")", "even_if", "=", "\" even if already connected\"", "if", "force", "Log", ".", "info", "(", "\"Connecting to broker at host #{host.inspect} port #{port.inspect} \"", "+", "\"index #{index.inspect} priority #{priority.inspect}#{even_if}\"", ")", "Log", ".", "info", "(", "\"Current broker configuration: #{@client.status.inspect}\"", ")", "result", "=", "nil", "begin", "@client", ".", "connect", "(", "host", ",", "port", ",", "index", ",", "priority", ",", "force", ")", "do", "|", "id", "|", "@client", ".", "connection_status", "(", ":one_off", "=>", "@options", "[", ":connect_timeout", "]", ",", ":brokers", "=>", "[", "id", "]", ")", "do", "|", "status", "|", "begin", "if", "status", "==", ":connected", "setup_queues", "(", "[", "id", "]", ")", "remaining", "=", "0", "@remaining_queue_setup", ".", "each_value", "{", "|", "ids", "|", "remaining", "+=", "ids", ".", "size", "}", "Log", ".", "info", "(", "\"[setup] Finished subscribing to queues after reconnecting to broker #{id}\"", ")", "if", "remaining", "==", "0", "unless", "update_configuration", "(", ":host", "=>", "@client", ".", "hosts", ",", ":port", "=>", "@client", ".", "ports", ")", "Log", ".", "warning", "(", "\"Successfully connected to broker #{id} but failed to update config file\"", ")", "end", "else", "ErrorTracker", ".", "log", "(", "self", ",", "\"Failed to connect to broker #{id}, status #{status.inspect}\"", ")", "end", "rescue", "Exception", "=>", "e", "ErrorTracker", ".", "log", "(", "self", ",", "\"Failed to connect to broker #{id}, status #{status.inspect}\"", ",", "e", ")", "end", "end", "end", "rescue", "StandardError", "=>", "e", "ErrorTracker", ".", "log", "(", "self", ",", "msg", "=", "\"Failed to connect to broker at host #{host.inspect} and port #{port.inspect}\"", ",", "e", ")", "result", "=", "Log", ".", "format", "(", "msg", ",", "e", ")", "end", "result", "end" ]
Connect to an additional AMQP broker or reconnect it if connection has failed Subscribe to identity queue on this broker Update config file if this is a new broker Assumes already has credentials on this broker and identity queue exists === Parameters host(String):: Host name of broker port(Integer):: Port number of broker index(Integer):: Small unique id associated with this broker for use in forming alias priority(Integer|nil):: Priority position of this broker in list for use by this agent with nil meaning add to end of list force(Boolean):: Reconnect even if already connected === Return (String|nil):: Error message if failed, otherwise nil
[ "Connect", "to", "an", "additional", "AMQP", "broker", "or", "reconnect", "it", "if", "connection", "has", "failed", "Subscribe", "to", "identity", "queue", "on", "this", "broker", "Update", "config", "file", "if", "this", "is", "a", "new", "broker", "Assumes", "already", "has", "credentials", "on", "this", "broker", "and", "identity", "queue", "exists" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/agent.rb#L299-L331
train
rightscale/right_agent
lib/right_agent/agent.rb
RightScale.Agent.disconnect
def disconnect(host, port, remove = false) and_remove = " and removing" if remove Log.info("Disconnecting#{and_remove} broker at host #{host.inspect} port #{port.inspect}") Log.info("Current broker configuration: #{@client.status.inspect}") id = RightAMQP::HABrokerClient.identity(host, port) @connect_request_stats.update("disconnect #{@client.alias_(id)}") connected = @client.connected result = e = nil if connected.include?(id) && connected.size == 1 result = "Not disconnecting from #{id} because it is the last connected broker for this agent" elsif @client.get(id) begin if remove @client.remove(host, port) do |id| unless update_configuration(:host => @client.hosts, :port => @client.ports) result = "Successfully disconnected from broker #{id} but failed to update config file" end end else @client.close_one(id) end rescue StandardError => e result = Log.format("Failed to disconnect from broker #{id}", e) end else result = "Cannot disconnect from broker #{id} because not configured for this agent" end ErrorTracker.log(self, result, e) if result result end
ruby
def disconnect(host, port, remove = false) and_remove = " and removing" if remove Log.info("Disconnecting#{and_remove} broker at host #{host.inspect} port #{port.inspect}") Log.info("Current broker configuration: #{@client.status.inspect}") id = RightAMQP::HABrokerClient.identity(host, port) @connect_request_stats.update("disconnect #{@client.alias_(id)}") connected = @client.connected result = e = nil if connected.include?(id) && connected.size == 1 result = "Not disconnecting from #{id} because it is the last connected broker for this agent" elsif @client.get(id) begin if remove @client.remove(host, port) do |id| unless update_configuration(:host => @client.hosts, :port => @client.ports) result = "Successfully disconnected from broker #{id} but failed to update config file" end end else @client.close_one(id) end rescue StandardError => e result = Log.format("Failed to disconnect from broker #{id}", e) end else result = "Cannot disconnect from broker #{id} because not configured for this agent" end ErrorTracker.log(self, result, e) if result result end
[ "def", "disconnect", "(", "host", ",", "port", ",", "remove", "=", "false", ")", "and_remove", "=", "\" and removing\"", "if", "remove", "Log", ".", "info", "(", "\"Disconnecting#{and_remove} broker at host #{host.inspect} port #{port.inspect}\"", ")", "Log", ".", "info", "(", "\"Current broker configuration: #{@client.status.inspect}\"", ")", "id", "=", "RightAMQP", "::", "HABrokerClient", ".", "identity", "(", "host", ",", "port", ")", "@connect_request_stats", ".", "update", "(", "\"disconnect #{@client.alias_(id)}\"", ")", "connected", "=", "@client", ".", "connected", "result", "=", "e", "=", "nil", "if", "connected", ".", "include?", "(", "id", ")", "&&", "connected", ".", "size", "==", "1", "result", "=", "\"Not disconnecting from #{id} because it is the last connected broker for this agent\"", "elsif", "@client", ".", "get", "(", "id", ")", "begin", "if", "remove", "@client", ".", "remove", "(", "host", ",", "port", ")", "do", "|", "id", "|", "unless", "update_configuration", "(", ":host", "=>", "@client", ".", "hosts", ",", ":port", "=>", "@client", ".", "ports", ")", "result", "=", "\"Successfully disconnected from broker #{id} but failed to update config file\"", "end", "end", "else", "@client", ".", "close_one", "(", "id", ")", "end", "rescue", "StandardError", "=>", "e", "result", "=", "Log", ".", "format", "(", "\"Failed to disconnect from broker #{id}\"", ",", "e", ")", "end", "else", "result", "=", "\"Cannot disconnect from broker #{id} because not configured for this agent\"", "end", "ErrorTracker", ".", "log", "(", "self", ",", "result", ",", "e", ")", "if", "result", "result", "end" ]
Disconnect from an AMQP broker and optionally remove it from the configuration Refuse to do so if it is the last connected broker === Parameters host(String):: Host name of broker port(Integer):: Port number of broker remove(Boolean):: Whether to remove broker from configuration rather than just closing it, defaults to false === Return (String|nil):: Error message if failed, otherwise nil
[ "Disconnect", "from", "an", "AMQP", "broker", "and", "optionally", "remove", "it", "from", "the", "configuration", "Refuse", "to", "do", "so", "if", "it", "is", "the", "last", "connected", "broker" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/agent.rb#L344-L373
train
rightscale/right_agent
lib/right_agent/agent.rb
RightScale.Agent.connect_failed
def connect_failed(ids) aliases = @client.aliases(ids).join(", ") @connect_request_stats.update("enroll failed #{aliases}") result = nil begin Log.info("Received indication that service initialization for this agent for brokers #{ids.inspect} has failed") connected = @client.connected ignored = connected & ids Log.info("Not marking brokers #{ignored.inspect} as unusable because currently connected") if ignored Log.info("Current broker configuration: #{@client.status.inspect}") @client.declare_unusable(ids - ignored) rescue StandardError => e ErrorTracker.log(self, msg = "Failed handling broker connection failure indication for #{ids.inspect}", e) result = Log.format(msg, e) end result end
ruby
def connect_failed(ids) aliases = @client.aliases(ids).join(", ") @connect_request_stats.update("enroll failed #{aliases}") result = nil begin Log.info("Received indication that service initialization for this agent for brokers #{ids.inspect} has failed") connected = @client.connected ignored = connected & ids Log.info("Not marking brokers #{ignored.inspect} as unusable because currently connected") if ignored Log.info("Current broker configuration: #{@client.status.inspect}") @client.declare_unusable(ids - ignored) rescue StandardError => e ErrorTracker.log(self, msg = "Failed handling broker connection failure indication for #{ids.inspect}", e) result = Log.format(msg, e) end result end
[ "def", "connect_failed", "(", "ids", ")", "aliases", "=", "@client", ".", "aliases", "(", "ids", ")", ".", "join", "(", "\", \"", ")", "@connect_request_stats", ".", "update", "(", "\"enroll failed #{aliases}\"", ")", "result", "=", "nil", "begin", "Log", ".", "info", "(", "\"Received indication that service initialization for this agent for brokers #{ids.inspect} has failed\"", ")", "connected", "=", "@client", ".", "connected", "ignored", "=", "connected", "&", "ids", "Log", ".", "info", "(", "\"Not marking brokers #{ignored.inspect} as unusable because currently connected\"", ")", "if", "ignored", "Log", ".", "info", "(", "\"Current broker configuration: #{@client.status.inspect}\"", ")", "@client", ".", "declare_unusable", "(", "ids", "-", "ignored", ")", "rescue", "StandardError", "=>", "e", "ErrorTracker", ".", "log", "(", "self", ",", "msg", "=", "\"Failed handling broker connection failure indication for #{ids.inspect}\"", ",", "e", ")", "result", "=", "Log", ".", "format", "(", "msg", ",", "e", ")", "end", "result", "end" ]
There were problems while setting up service for this agent on the given AMQP brokers, so mark these brokers as failed if not currently connected and later, during the periodic status check, attempt to reconnect === Parameters ids(Array):: Identity of brokers === Return (String|nil):: Error message if failed, otherwise nil
[ "There", "were", "problems", "while", "setting", "up", "service", "for", "this", "agent", "on", "the", "given", "AMQP", "brokers", "so", "mark", "these", "brokers", "as", "failed", "if", "not", "currently", "connected", "and", "later", "during", "the", "periodic", "status", "check", "attempt", "to", "reconnect" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/agent.rb#L384-L400
train
rightscale/right_agent
lib/right_agent/agent.rb
RightScale.Agent.terminate
def terminate(reason = nil, exception = nil) begin @history.update("stop") if @history ErrorTracker.log(self, "[stop] Terminating because #{reason}", exception) if reason if exception.is_a?(Exception) h = @history.analyze_service if h[:last_crashed] delay = [(Time.now.to_i - h[:last_crash_time]) * 2, MAX_ABNORMAL_TERMINATE_DELAY].min Log.info("[stop] Delaying termination for #{RightSupport::Stats.elapsed(delay)} to slow crash cycling") sleep(delay) end end if @terminating || @client.nil? @terminating = true @termination_timer.cancel if @termination_timer @termination_timer = nil Log.info("[stop] Terminating immediately") @terminate_callback.call @history.update("graceful exit") if @history && @client.nil? else @terminating = true @check_status_timer.cancel if @check_status_timer @check_status_timer = nil Log.info("[stop] Agent #{@identity} terminating") stop_gracefully(@options[:grace_timeout]) end rescue StandardError => e ErrorTracker.log(self, "Failed to terminate gracefully", e) begin @terminate_callback.call; rescue Exception; end end true end
ruby
def terminate(reason = nil, exception = nil) begin @history.update("stop") if @history ErrorTracker.log(self, "[stop] Terminating because #{reason}", exception) if reason if exception.is_a?(Exception) h = @history.analyze_service if h[:last_crashed] delay = [(Time.now.to_i - h[:last_crash_time]) * 2, MAX_ABNORMAL_TERMINATE_DELAY].min Log.info("[stop] Delaying termination for #{RightSupport::Stats.elapsed(delay)} to slow crash cycling") sleep(delay) end end if @terminating || @client.nil? @terminating = true @termination_timer.cancel if @termination_timer @termination_timer = nil Log.info("[stop] Terminating immediately") @terminate_callback.call @history.update("graceful exit") if @history && @client.nil? else @terminating = true @check_status_timer.cancel if @check_status_timer @check_status_timer = nil Log.info("[stop] Agent #{@identity} terminating") stop_gracefully(@options[:grace_timeout]) end rescue StandardError => e ErrorTracker.log(self, "Failed to terminate gracefully", e) begin @terminate_callback.call; rescue Exception; end end true end
[ "def", "terminate", "(", "reason", "=", "nil", ",", "exception", "=", "nil", ")", "begin", "@history", ".", "update", "(", "\"stop\"", ")", "if", "@history", "ErrorTracker", ".", "log", "(", "self", ",", "\"[stop] Terminating because #{reason}\"", ",", "exception", ")", "if", "reason", "if", "exception", ".", "is_a?", "(", "Exception", ")", "h", "=", "@history", ".", "analyze_service", "if", "h", "[", ":last_crashed", "]", "delay", "=", "[", "(", "Time", ".", "now", ".", "to_i", "-", "h", "[", ":last_crash_time", "]", ")", "*", "2", ",", "MAX_ABNORMAL_TERMINATE_DELAY", "]", ".", "min", "Log", ".", "info", "(", "\"[stop] Delaying termination for #{RightSupport::Stats.elapsed(delay)} to slow crash cycling\"", ")", "sleep", "(", "delay", ")", "end", "end", "if", "@terminating", "||", "@client", ".", "nil?", "@terminating", "=", "true", "@termination_timer", ".", "cancel", "if", "@termination_timer", "@termination_timer", "=", "nil", "Log", ".", "info", "(", "\"[stop] Terminating immediately\"", ")", "@terminate_callback", ".", "call", "@history", ".", "update", "(", "\"graceful exit\"", ")", "if", "@history", "&&", "@client", ".", "nil?", "else", "@terminating", "=", "true", "@check_status_timer", ".", "cancel", "if", "@check_status_timer", "@check_status_timer", "=", "nil", "Log", ".", "info", "(", "\"[stop] Agent #{@identity} terminating\"", ")", "stop_gracefully", "(", "@options", "[", ":grace_timeout", "]", ")", "end", "rescue", "StandardError", "=>", "e", "ErrorTracker", ".", "log", "(", "self", ",", "\"Failed to terminate gracefully\"", ",", "e", ")", "begin", "@terminate_callback", ".", "call", ";", "rescue", "Exception", ";", "end", "end", "true", "end" ]
Gracefully terminate execution by allowing unfinished tasks to complete Immediately terminate if called a second time Report reason for termination if it is abnormal === Parameters reason(String):: Reason for abnormal termination, if any exception(Exception|String):: Exception or other parenthetical error information, if any === Return true:: Always return true
[ "Gracefully", "terminate", "execution", "by", "allowing", "unfinished", "tasks", "to", "complete", "Immediately", "terminate", "if", "called", "a", "second", "time", "Report", "reason", "for", "termination", "if", "it", "is", "abnormal" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/agent.rb#L434-L465
train
rightscale/right_agent
lib/right_agent/agent.rb
RightScale.Agent.stats
def stats(options = {}) now = Time.now reset = options[:reset] stats = { "name" => @agent_name, "identity" => @identity, "hostname" => Socket.gethostname, "memory" => Platform.process.resident_set_size, "version" => AgentConfig.protocol_version, "agent stats" => agent_stats(reset), "receive stats" => dispatcher_stats(reset), "send stats" => @sender.stats(reset), "last reset time" => @last_stat_reset_time.to_i, "stat time" => now.to_i, "service uptime" => @history.analyze_service, "machine uptime" => Platform.shell.uptime } stats["revision"] = @revision if @revision if @mode == :http stats.merge!(@client.stats(reset)) else stats["brokers"] = @client.stats(reset) end result = OperationResult.success(stats) @last_stat_reset_time = now if reset result end
ruby
def stats(options = {}) now = Time.now reset = options[:reset] stats = { "name" => @agent_name, "identity" => @identity, "hostname" => Socket.gethostname, "memory" => Platform.process.resident_set_size, "version" => AgentConfig.protocol_version, "agent stats" => agent_stats(reset), "receive stats" => dispatcher_stats(reset), "send stats" => @sender.stats(reset), "last reset time" => @last_stat_reset_time.to_i, "stat time" => now.to_i, "service uptime" => @history.analyze_service, "machine uptime" => Platform.shell.uptime } stats["revision"] = @revision if @revision if @mode == :http stats.merge!(@client.stats(reset)) else stats["brokers"] = @client.stats(reset) end result = OperationResult.success(stats) @last_stat_reset_time = now if reset result end
[ "def", "stats", "(", "options", "=", "{", "}", ")", "now", "=", "Time", ".", "now", "reset", "=", "options", "[", ":reset", "]", "stats", "=", "{", "\"name\"", "=>", "@agent_name", ",", "\"identity\"", "=>", "@identity", ",", "\"hostname\"", "=>", "Socket", ".", "gethostname", ",", "\"memory\"", "=>", "Platform", ".", "process", ".", "resident_set_size", ",", "\"version\"", "=>", "AgentConfig", ".", "protocol_version", ",", "\"agent stats\"", "=>", "agent_stats", "(", "reset", ")", ",", "\"receive stats\"", "=>", "dispatcher_stats", "(", "reset", ")", ",", "\"send stats\"", "=>", "@sender", ".", "stats", "(", "reset", ")", ",", "\"last reset time\"", "=>", "@last_stat_reset_time", ".", "to_i", ",", "\"stat time\"", "=>", "now", ".", "to_i", ",", "\"service uptime\"", "=>", "@history", ".", "analyze_service", ",", "\"machine uptime\"", "=>", "Platform", ".", "shell", ".", "uptime", "}", "stats", "[", "\"revision\"", "]", "=", "@revision", "if", "@revision", "if", "@mode", "==", ":http", "stats", ".", "merge!", "(", "@client", ".", "stats", "(", "reset", ")", ")", "else", "stats", "[", "\"brokers\"", "]", "=", "@client", ".", "stats", "(", "reset", ")", "end", "result", "=", "OperationResult", ".", "success", "(", "stats", ")", "@last_stat_reset_time", "=", "now", "if", "reset", "result", "end" ]
Retrieve statistics about agent operation === Parameters: options(Hash):: Request options: :reset(Boolean):: Whether to reset the statistics after getting the current ones === Return result(OperationResult):: Always returns success
[ "Retrieve", "statistics", "about", "agent", "operation" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/agent.rb#L475-L501
train
rightscale/right_agent
lib/right_agent/agent.rb
RightScale.Agent.agent_stats
def agent_stats(reset = false) stats = { "request failures" => @request_failure_stats.all, "response failures" => @response_failure_stats.all }.merge(ErrorTracker.stats(reset)) if @mode != :http stats["connect requests"] = @connect_request_stats.all stats["non-deliveries"] = @non_delivery_stats.all end reset_agent_stats if reset stats end
ruby
def agent_stats(reset = false) stats = { "request failures" => @request_failure_stats.all, "response failures" => @response_failure_stats.all }.merge(ErrorTracker.stats(reset)) if @mode != :http stats["connect requests"] = @connect_request_stats.all stats["non-deliveries"] = @non_delivery_stats.all end reset_agent_stats if reset stats end
[ "def", "agent_stats", "(", "reset", "=", "false", ")", "stats", "=", "{", "\"request failures\"", "=>", "@request_failure_stats", ".", "all", ",", "\"response failures\"", "=>", "@response_failure_stats", ".", "all", "}", ".", "merge", "(", "ErrorTracker", ".", "stats", "(", "reset", ")", ")", "if", "@mode", "!=", ":http", "stats", "[", "\"connect requests\"", "]", "=", "@connect_request_stats", ".", "all", "stats", "[", "\"non-deliveries\"", "]", "=", "@non_delivery_stats", ".", "all", "end", "reset_agent_stats", "if", "reset", "stats", "end" ]
Get request statistics === Parameters reset(Boolean):: Whether to reset the statistics after getting the current ones === Return stats(Hash):: Current statistics: "connect requests"(Hash|nil):: Stats about requests to update AMQP broker connections with keys "total", "percent", and "last" with percentage breakdown by "connects: <alias>", "disconnects: <alias>", "enroll setup failed: <aliases>", or nil if none "exceptions"(Hash|nil):: Exceptions raised per category, or nil if none "total"(Integer):: Total exceptions for this category "recent"(Array):: Most recent as a hash of "count", "type", "message", "when", and "where" "non-deliveries"(Hash):: AMQP message non-delivery activity stats with keys "total", "percent", "last", and "rate" with percentage breakdown by request type, or nil if none "request failures"(Hash|nil):: Request dispatch failure activity stats with keys "total", "percent", "last", and "rate" with percentage breakdown per failure type, or nil if none "response failures"(Hash|nil):: Response delivery failure activity stats with keys "total", "percent", "last", and "rate" with percentage breakdown per failure type, or nil if none
[ "Get", "request", "statistics" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/agent.rb#L524-L535
train
rightscale/right_agent
lib/right_agent/agent.rb
RightScale.Agent.reset_agent_stats
def reset_agent_stats @connect_request_stats = RightSupport::Stats::Activity.new(measure_rate = false) @non_delivery_stats = RightSupport::Stats::Activity.new @request_failure_stats = RightSupport::Stats::Activity.new @response_failure_stats = RightSupport::Stats::Activity.new true end
ruby
def reset_agent_stats @connect_request_stats = RightSupport::Stats::Activity.new(measure_rate = false) @non_delivery_stats = RightSupport::Stats::Activity.new @request_failure_stats = RightSupport::Stats::Activity.new @response_failure_stats = RightSupport::Stats::Activity.new true end
[ "def", "reset_agent_stats", "@connect_request_stats", "=", "RightSupport", "::", "Stats", "::", "Activity", ".", "new", "(", "measure_rate", "=", "false", ")", "@non_delivery_stats", "=", "RightSupport", "::", "Stats", "::", "Activity", ".", "new", "@request_failure_stats", "=", "RightSupport", "::", "Stats", "::", "Activity", ".", "new", "@response_failure_stats", "=", "RightSupport", "::", "Stats", "::", "Activity", ".", "new", "true", "end" ]
Reset agent statistics === Return true:: Always return true
[ "Reset", "agent", "statistics" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/agent.rb#L541-L547
train
rightscale/right_agent
lib/right_agent/agent.rb
RightScale.Agent.set_configuration
def set_configuration(opts) @options = DEFAULT_OPTIONS.clone @options.update(opts) AgentConfig.root_dir = @options[:root_dir] AgentConfig.pid_dir = @options[:pid_dir] @options[:log_path] = false if @options[:daemonize] || @options[:log_dir] @options[:log_path] = (@options[:log_dir] || Platform.filesystem.log_dir) FileUtils.mkdir_p(@options[:log_path]) unless File.directory?(@options[:log_path]) end @options[:async_response] = true unless @options.has_key?(:async_response) @options[:non_blocking] = true if @options[:fiber_pool_size].to_i > 0 @identity = @options[:identity] parsed_identity = AgentIdentity.parse(@identity) @agent_type = parsed_identity.agent_type @agent_name = @options[:agent_name] @request_queue = "request" @request_queue << "-#{@options[:shard_id].to_i}" if @options[:shard_id].to_i != 0 @mode = @options[:mode].to_sym @stats_routing_key = "stats.#{@agent_type}.#{parsed_identity.base_id}" @terminate_callback = TERMINATE_BLOCK @revision = revision @queues = [@identity] @remaining_queue_setup = {} @history = History.new(@identity) end
ruby
def set_configuration(opts) @options = DEFAULT_OPTIONS.clone @options.update(opts) AgentConfig.root_dir = @options[:root_dir] AgentConfig.pid_dir = @options[:pid_dir] @options[:log_path] = false if @options[:daemonize] || @options[:log_dir] @options[:log_path] = (@options[:log_dir] || Platform.filesystem.log_dir) FileUtils.mkdir_p(@options[:log_path]) unless File.directory?(@options[:log_path]) end @options[:async_response] = true unless @options.has_key?(:async_response) @options[:non_blocking] = true if @options[:fiber_pool_size].to_i > 0 @identity = @options[:identity] parsed_identity = AgentIdentity.parse(@identity) @agent_type = parsed_identity.agent_type @agent_name = @options[:agent_name] @request_queue = "request" @request_queue << "-#{@options[:shard_id].to_i}" if @options[:shard_id].to_i != 0 @mode = @options[:mode].to_sym @stats_routing_key = "stats.#{@agent_type}.#{parsed_identity.base_id}" @terminate_callback = TERMINATE_BLOCK @revision = revision @queues = [@identity] @remaining_queue_setup = {} @history = History.new(@identity) end
[ "def", "set_configuration", "(", "opts", ")", "@options", "=", "DEFAULT_OPTIONS", ".", "clone", "@options", ".", "update", "(", "opts", ")", "AgentConfig", ".", "root_dir", "=", "@options", "[", ":root_dir", "]", "AgentConfig", ".", "pid_dir", "=", "@options", "[", ":pid_dir", "]", "@options", "[", ":log_path", "]", "=", "false", "if", "@options", "[", ":daemonize", "]", "||", "@options", "[", ":log_dir", "]", "@options", "[", ":log_path", "]", "=", "(", "@options", "[", ":log_dir", "]", "||", "Platform", ".", "filesystem", ".", "log_dir", ")", "FileUtils", ".", "mkdir_p", "(", "@options", "[", ":log_path", "]", ")", "unless", "File", ".", "directory?", "(", "@options", "[", ":log_path", "]", ")", "end", "@options", "[", ":async_response", "]", "=", "true", "unless", "@options", ".", "has_key?", "(", ":async_response", ")", "@options", "[", ":non_blocking", "]", "=", "true", "if", "@options", "[", ":fiber_pool_size", "]", ".", "to_i", ">", "0", "@identity", "=", "@options", "[", ":identity", "]", "parsed_identity", "=", "AgentIdentity", ".", "parse", "(", "@identity", ")", "@agent_type", "=", "parsed_identity", ".", "agent_type", "@agent_name", "=", "@options", "[", ":agent_name", "]", "@request_queue", "=", "\"request\"", "@request_queue", "<<", "\"-#{@options[:shard_id].to_i}\"", "if", "@options", "[", ":shard_id", "]", ".", "to_i", "!=", "0", "@mode", "=", "@options", "[", ":mode", "]", ".", "to_sym", "@stats_routing_key", "=", "\"stats.#{@agent_type}.#{parsed_identity.base_id}\"", "@terminate_callback", "=", "TERMINATE_BLOCK", "@revision", "=", "revision", "@queues", "=", "[", "@identity", "]", "@remaining_queue_setup", "=", "{", "}", "@history", "=", "History", ".", "new", "(", "@identity", ")", "end" ]
Set the agent's configuration using the supplied options === Parameters opts(Hash):: Configuration options === Return true:: Always return true
[ "Set", "the", "agent", "s", "configuration", "using", "the", "supplied", "options" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/agent.rb#L564-L593
train
rightscale/right_agent
lib/right_agent/agent.rb
RightScale.Agent.handle_event
def handle_event(event) if event.is_a?(Hash) if ["Push", "Request"].include?(event[:type]) # Use next_tick to ensure that on main reactor thread # so that any data access is thread safe EM_S.next_tick do begin if (result = @dispatcher.dispatch(event_to_packet(event))) && event[:type] == "Request" @client.notify(result_to_event(result), [result.to]) end rescue Dispatcher::DuplicateRequest rescue Exception => e ErrorTracker.log(self, "Failed sending response for <#{event[:uuid]}>", e) end end elsif event[:type] == "Result" if (data = event[:data]) && (result = data[:result]) && result.respond_to?(:non_delivery?) && result.non_delivery? Log.info("Non-delivery of event <#{data[:request_uuid]}>: #{result.content}") else ErrorTracker.log(self, "Unexpected Result event from #{event[:from]}: #{event.inspect}") end else ErrorTracker.log(self, "Unrecognized event type #{event[:type]} from #{event[:from]}") end else ErrorTracker.log(self, "Unrecognized event: #{event.class}") end nil end
ruby
def handle_event(event) if event.is_a?(Hash) if ["Push", "Request"].include?(event[:type]) # Use next_tick to ensure that on main reactor thread # so that any data access is thread safe EM_S.next_tick do begin if (result = @dispatcher.dispatch(event_to_packet(event))) && event[:type] == "Request" @client.notify(result_to_event(result), [result.to]) end rescue Dispatcher::DuplicateRequest rescue Exception => e ErrorTracker.log(self, "Failed sending response for <#{event[:uuid]}>", e) end end elsif event[:type] == "Result" if (data = event[:data]) && (result = data[:result]) && result.respond_to?(:non_delivery?) && result.non_delivery? Log.info("Non-delivery of event <#{data[:request_uuid]}>: #{result.content}") else ErrorTracker.log(self, "Unexpected Result event from #{event[:from]}: #{event.inspect}") end else ErrorTracker.log(self, "Unrecognized event type #{event[:type]} from #{event[:from]}") end else ErrorTracker.log(self, "Unrecognized event: #{event.class}") end nil end
[ "def", "handle_event", "(", "event", ")", "if", "event", ".", "is_a?", "(", "Hash", ")", "if", "[", "\"Push\"", ",", "\"Request\"", "]", ".", "include?", "(", "event", "[", ":type", "]", ")", "EM_S", ".", "next_tick", "do", "begin", "if", "(", "result", "=", "@dispatcher", ".", "dispatch", "(", "event_to_packet", "(", "event", ")", ")", ")", "&&", "event", "[", ":type", "]", "==", "\"Request\"", "@client", ".", "notify", "(", "result_to_event", "(", "result", ")", ",", "[", "result", ".", "to", "]", ")", "end", "rescue", "Dispatcher", "::", "DuplicateRequest", "rescue", "Exception", "=>", "e", "ErrorTracker", ".", "log", "(", "self", ",", "\"Failed sending response for <#{event[:uuid]}>\"", ",", "e", ")", "end", "end", "elsif", "event", "[", ":type", "]", "==", "\"Result\"", "if", "(", "data", "=", "event", "[", ":data", "]", ")", "&&", "(", "result", "=", "data", "[", ":result", "]", ")", "&&", "result", ".", "respond_to?", "(", ":non_delivery?", ")", "&&", "result", ".", "non_delivery?", "Log", ".", "info", "(", "\"Non-delivery of event <#{data[:request_uuid]}>: #{result.content}\"", ")", "else", "ErrorTracker", ".", "log", "(", "self", ",", "\"Unexpected Result event from #{event[:from]}: #{event.inspect}\"", ")", "end", "else", "ErrorTracker", ".", "log", "(", "self", ",", "\"Unrecognized event type #{event[:type]} from #{event[:from]}\"", ")", "end", "else", "ErrorTracker", ".", "log", "(", "self", ",", "\"Unrecognized event: #{event.class}\"", ")", "end", "nil", "end" ]
Handle events received by this agent === Parameters event(Hash):: Event received === Return nil:: Always return nil indicating no response since handled separately via notify
[ "Handle", "events", "received", "by", "this", "agent" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/agent.rb#L636-L664
train
rightscale/right_agent
lib/right_agent/agent.rb
RightScale.Agent.event_to_packet
def event_to_packet(event) packet = nil case event[:type] when "Push" packet = RightScale::Push.new(event[:path], event[:data], {:from => event[:from], :token => event[:uuid]}) packet.expires_at = event[:expires_at].to_i if event.has_key?(:expires_at) packet.skewed_by = event[:skewed_by].to_i if event.has_key?(:skewed_by) when "Request" options = {:from => event[:from], :token => event[:uuid], :reply_to => event[:reply_to], :tries => event[:tries]} packet = RightScale::Request.new(event[:path], event[:data], options) packet.expires_at = event[:expires_at].to_i if event.has_key?(:expires_at) packet.skewed_by = event[:skewed_by].to_i if event.has_key?(:skewed_by) end packet end
ruby
def event_to_packet(event) packet = nil case event[:type] when "Push" packet = RightScale::Push.new(event[:path], event[:data], {:from => event[:from], :token => event[:uuid]}) packet.expires_at = event[:expires_at].to_i if event.has_key?(:expires_at) packet.skewed_by = event[:skewed_by].to_i if event.has_key?(:skewed_by) when "Request" options = {:from => event[:from], :token => event[:uuid], :reply_to => event[:reply_to], :tries => event[:tries]} packet = RightScale::Request.new(event[:path], event[:data], options) packet.expires_at = event[:expires_at].to_i if event.has_key?(:expires_at) packet.skewed_by = event[:skewed_by].to_i if event.has_key?(:skewed_by) end packet end
[ "def", "event_to_packet", "(", "event", ")", "packet", "=", "nil", "case", "event", "[", ":type", "]", "when", "\"Push\"", "packet", "=", "RightScale", "::", "Push", ".", "new", "(", "event", "[", ":path", "]", ",", "event", "[", ":data", "]", ",", "{", ":from", "=>", "event", "[", ":from", "]", ",", ":token", "=>", "event", "[", ":uuid", "]", "}", ")", "packet", ".", "expires_at", "=", "event", "[", ":expires_at", "]", ".", "to_i", "if", "event", ".", "has_key?", "(", ":expires_at", ")", "packet", ".", "skewed_by", "=", "event", "[", ":skewed_by", "]", ".", "to_i", "if", "event", ".", "has_key?", "(", ":skewed_by", ")", "when", "\"Request\"", "options", "=", "{", ":from", "=>", "event", "[", ":from", "]", ",", ":token", "=>", "event", "[", ":uuid", "]", ",", ":reply_to", "=>", "event", "[", ":reply_to", "]", ",", ":tries", "=>", "event", "[", ":tries", "]", "}", "packet", "=", "RightScale", "::", "Request", ".", "new", "(", "event", "[", ":path", "]", ",", "event", "[", ":data", "]", ",", "options", ")", "packet", ".", "expires_at", "=", "event", "[", ":expires_at", "]", ".", "to_i", "if", "event", ".", "has_key?", "(", ":expires_at", ")", "packet", ".", "skewed_by", "=", "event", "[", ":skewed_by", "]", ".", "to_i", "if", "event", ".", "has_key?", "(", ":skewed_by", ")", "end", "packet", "end" ]
Convert event hash to packet === Parameters event(Hash):: Event to be converted === Return (Push|Request):: Packet
[ "Convert", "event", "hash", "to", "packet" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/agent.rb#L673-L687
train
rightscale/right_agent
lib/right_agent/agent.rb
RightScale.Agent.result_to_event
def result_to_event(result) { :type => "Result", :from => result.from, :data => { :result => result.results, :duration => result.duration, :request_uuid => result.token, :request_from => result.request_from } } end
ruby
def result_to_event(result) { :type => "Result", :from => result.from, :data => { :result => result.results, :duration => result.duration, :request_uuid => result.token, :request_from => result.request_from } } end
[ "def", "result_to_event", "(", "result", ")", "{", ":type", "=>", "\"Result\"", ",", ":from", "=>", "result", ".", "from", ",", ":data", "=>", "{", ":result", "=>", "result", ".", "results", ",", ":duration", "=>", "result", ".", "duration", ",", ":request_uuid", "=>", "result", ".", "token", ",", ":request_from", "=>", "result", ".", "request_from", "}", "}", "end" ]
Convert result packet to event === Parameters result(Result):: Event to be converted === Return (Hash):: Event
[ "Convert", "result", "packet", "to", "event" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/agent.rb#L696-L704
train
rightscale/right_agent
lib/right_agent/agent.rb
RightScale.Agent.create_dispatchers
def create_dispatchers cache = DispatchedCache.new(@identity) if @options[:dup_check] @dispatcher = Dispatcher.new(self, cache) @queues.inject({}) { |dispatchers, queue| dispatchers[queue] = @dispatcher; dispatchers } end
ruby
def create_dispatchers cache = DispatchedCache.new(@identity) if @options[:dup_check] @dispatcher = Dispatcher.new(self, cache) @queues.inject({}) { |dispatchers, queue| dispatchers[queue] = @dispatcher; dispatchers } end
[ "def", "create_dispatchers", "cache", "=", "DispatchedCache", ".", "new", "(", "@identity", ")", "if", "@options", "[", ":dup_check", "]", "@dispatcher", "=", "Dispatcher", ".", "new", "(", "self", ",", "cache", ")", "@queues", ".", "inject", "(", "{", "}", ")", "{", "|", "dispatchers", ",", "queue", "|", "dispatchers", "[", "queue", "]", "=", "@dispatcher", ";", "dispatchers", "}", "end" ]
Create dispatcher per queue for use in handling incoming requests === Return [Hash]:: Dispatchers with queue name as key
[ "Create", "dispatcher", "per", "queue", "for", "use", "in", "handling", "incoming", "requests" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/agent.rb#L710-L714
train
rightscale/right_agent
lib/right_agent/agent.rb
RightScale.Agent.load_actors
def load_actors # Load agent's configured actors actors = (@options[:actors] || []).clone Log.info("[setup] Agent #{@identity} with actors #{actors.inspect}") actors_dirs = AgentConfig.actors_dirs actors_dirs.each do |dir| Dir["#{dir}/*.rb"].each do |file| actor = File.basename(file, ".rb") next if actors && !actors.include?(actor) Log.info("[setup] Loading actor #{file}") require file actors.delete(actor) end end ErrorTracker.log(self, "Actors #{actors.inspect} not found in #{actors_dirs.inspect}") unless actors.empty? # Perform agent-specific initialization including actor creation and registration if (init_file = AgentConfig.init_file) Log.info("[setup] Initializing agent from #{init_file}") instance_eval(File.read(init_file), init_file) else ErrorTracker.log(self, "No agent init.rb file found in init directory of #{AgentConfig.root_dir.inspect}") end true end
ruby
def load_actors # Load agent's configured actors actors = (@options[:actors] || []).clone Log.info("[setup] Agent #{@identity} with actors #{actors.inspect}") actors_dirs = AgentConfig.actors_dirs actors_dirs.each do |dir| Dir["#{dir}/*.rb"].each do |file| actor = File.basename(file, ".rb") next if actors && !actors.include?(actor) Log.info("[setup] Loading actor #{file}") require file actors.delete(actor) end end ErrorTracker.log(self, "Actors #{actors.inspect} not found in #{actors_dirs.inspect}") unless actors.empty? # Perform agent-specific initialization including actor creation and registration if (init_file = AgentConfig.init_file) Log.info("[setup] Initializing agent from #{init_file}") instance_eval(File.read(init_file), init_file) else ErrorTracker.log(self, "No agent init.rb file found in init directory of #{AgentConfig.root_dir.inspect}") end true end
[ "def", "load_actors", "actors", "=", "(", "@options", "[", ":actors", "]", "||", "[", "]", ")", ".", "clone", "Log", ".", "info", "(", "\"[setup] Agent #{@identity} with actors #{actors.inspect}\"", ")", "actors_dirs", "=", "AgentConfig", ".", "actors_dirs", "actors_dirs", ".", "each", "do", "|", "dir", "|", "Dir", "[", "\"#{dir}/*.rb\"", "]", ".", "each", "do", "|", "file", "|", "actor", "=", "File", ".", "basename", "(", "file", ",", "\".rb\"", ")", "next", "if", "actors", "&&", "!", "actors", ".", "include?", "(", "actor", ")", "Log", ".", "info", "(", "\"[setup] Loading actor #{file}\"", ")", "require", "file", "actors", ".", "delete", "(", "actor", ")", "end", "end", "ErrorTracker", ".", "log", "(", "self", ",", "\"Actors #{actors.inspect} not found in #{actors_dirs.inspect}\"", ")", "unless", "actors", ".", "empty?", "if", "(", "init_file", "=", "AgentConfig", ".", "init_file", ")", "Log", ".", "info", "(", "\"[setup] Initializing agent from #{init_file}\"", ")", "instance_eval", "(", "File", ".", "read", "(", "init_file", ")", ",", "init_file", ")", "else", "ErrorTracker", ".", "log", "(", "self", ",", "\"No agent init.rb file found in init directory of #{AgentConfig.root_dir.inspect}\"", ")", "end", "true", "end" ]
Load the ruby code for the actors === Return true:: Always return true
[ "Load", "the", "ruby", "code", "for", "the", "actors" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/agent.rb#L728-L752
train
rightscale/right_agent
lib/right_agent/agent.rb
RightScale.Agent.setup_http
def setup_http(auth_client) @auth_client = auth_client if @mode == :http RightHttpClient.init(@auth_client, @options.merge(:retry_enabled => true)) @client = RightHttpClient.instance end true end
ruby
def setup_http(auth_client) @auth_client = auth_client if @mode == :http RightHttpClient.init(@auth_client, @options.merge(:retry_enabled => true)) @client = RightHttpClient.instance end true end
[ "def", "setup_http", "(", "auth_client", ")", "@auth_client", "=", "auth_client", "if", "@mode", "==", ":http", "RightHttpClient", ".", "init", "(", "@auth_client", ",", "@options", ".", "merge", "(", ":retry_enabled", "=>", "true", ")", ")", "@client", "=", "RightHttpClient", ".", "instance", "end", "true", "end" ]
Create client for HTTP-based RightNet communication The code loaded with the actors specific to this application is responsible for calling this function === Parameters auth_client(AuthClient):: Authorization client to be used by this agent === Return true:: Always return true
[ "Create", "client", "for", "HTTP", "-", "based", "RightNet", "communication", "The", "code", "loaded", "with", "the", "actors", "specific", "to", "this", "application", "is", "responsible", "for", "calling", "this", "function" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/agent.rb#L763-L770
train
rightscale/right_agent
lib/right_agent/agent.rb
RightScale.Agent.setup_status
def setup_status @status = {} if @client if @mode == :http @status = @client.status { |type, state| update_status(type, state) }.dup else @client.connection_status { |state| update_status(:broker, state) } @status[:broker] = :connected @status[:auth] = @auth_client.status { |type, state| update_status(type, state) } if @auth_client end end true end
ruby
def setup_status @status = {} if @client if @mode == :http @status = @client.status { |type, state| update_status(type, state) }.dup else @client.connection_status { |state| update_status(:broker, state) } @status[:broker] = :connected @status[:auth] = @auth_client.status { |type, state| update_status(type, state) } if @auth_client end end true end
[ "def", "setup_status", "@status", "=", "{", "}", "if", "@client", "if", "@mode", "==", ":http", "@status", "=", "@client", ".", "status", "{", "|", "type", ",", "state", "|", "update_status", "(", "type", ",", "state", ")", "}", ".", "dup", "else", "@client", ".", "connection_status", "{", "|", "state", "|", "update_status", "(", ":broker", ",", "state", ")", "}", "@status", "[", ":broker", "]", "=", ":connected", "@status", "[", ":auth", "]", "=", "@auth_client", ".", "status", "{", "|", "type", ",", "state", "|", "update_status", "(", "type", ",", "state", ")", "}", "if", "@auth_client", "end", "end", "true", "end" ]
Setup client status collection === Return true:: Always return true
[ "Setup", "client", "status", "collection" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/agent.rb#L798-L810
train
rightscale/right_agent
lib/right_agent/agent.rb
RightScale.Agent.setup_non_delivery
def setup_non_delivery @client.non_delivery do |reason, type, token, from, to| begin @non_delivery_stats.update(type) reason = case reason when "NO_ROUTE" then OperationResult::NO_ROUTE_TO_TARGET when "NO_CONSUMERS" then OperationResult::TARGET_NOT_CONNECTED else reason.to_s end result = Result.new(token, from, OperationResult.non_delivery(reason), to) @sender.handle_response(result) rescue Exception => e ErrorTracker.log(self, "Failed handling non-delivery for <#{token}>", e) end end end
ruby
def setup_non_delivery @client.non_delivery do |reason, type, token, from, to| begin @non_delivery_stats.update(type) reason = case reason when "NO_ROUTE" then OperationResult::NO_ROUTE_TO_TARGET when "NO_CONSUMERS" then OperationResult::TARGET_NOT_CONNECTED else reason.to_s end result = Result.new(token, from, OperationResult.non_delivery(reason), to) @sender.handle_response(result) rescue Exception => e ErrorTracker.log(self, "Failed handling non-delivery for <#{token}>", e) end end end
[ "def", "setup_non_delivery", "@client", ".", "non_delivery", "do", "|", "reason", ",", "type", ",", "token", ",", "from", ",", "to", "|", "begin", "@non_delivery_stats", ".", "update", "(", "type", ")", "reason", "=", "case", "reason", "when", "\"NO_ROUTE\"", "then", "OperationResult", "::", "NO_ROUTE_TO_TARGET", "when", "\"NO_CONSUMERS\"", "then", "OperationResult", "::", "TARGET_NOT_CONNECTED", "else", "reason", ".", "to_s", "end", "result", "=", "Result", ".", "new", "(", "token", ",", "from", ",", "OperationResult", ".", "non_delivery", "(", "reason", ")", ",", "to", ")", "@sender", ".", "handle_response", "(", "result", ")", "rescue", "Exception", "=>", "e", "ErrorTracker", ".", "log", "(", "self", ",", "\"Failed handling non-delivery for <#{token}>\"", ",", "e", ")", "end", "end", "end" ]
Setup non-delivery handler === Return true:: Always return true
[ "Setup", "non", "-", "delivery", "handler" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/agent.rb#L816-L831
train
rightscale/right_agent
lib/right_agent/agent.rb
RightScale.Agent.setup_queue
def setup_queue(name, ids = nil) queue = {:name => name, :options => {:durable => true, :no_declare => @options[:secure]}} filter = [:from, :tags, :tries, :persistent] options = {:ack => true, Push => filter, Request => filter, Result => [:from], :brokers => ids} @client.subscribe(queue, nil, options) { |_, packet, header| handle_packet(name, packet, header) } end
ruby
def setup_queue(name, ids = nil) queue = {:name => name, :options => {:durable => true, :no_declare => @options[:secure]}} filter = [:from, :tags, :tries, :persistent] options = {:ack => true, Push => filter, Request => filter, Result => [:from], :brokers => ids} @client.subscribe(queue, nil, options) { |_, packet, header| handle_packet(name, packet, header) } end
[ "def", "setup_queue", "(", "name", ",", "ids", "=", "nil", ")", "queue", "=", "{", ":name", "=>", "name", ",", ":options", "=>", "{", ":durable", "=>", "true", ",", ":no_declare", "=>", "@options", "[", ":secure", "]", "}", "}", "filter", "=", "[", ":from", ",", ":tags", ",", ":tries", ",", ":persistent", "]", "options", "=", "{", ":ack", "=>", "true", ",", "Push", "=>", "filter", ",", "Request", "=>", "filter", ",", "Result", "=>", "[", ":from", "]", ",", ":brokers", "=>", "ids", "}", "@client", ".", "subscribe", "(", "queue", ",", "nil", ",", "options", ")", "{", "|", "_", ",", "packet", ",", "header", "|", "handle_packet", "(", "name", ",", "packet", ",", "header", ")", "}", "end" ]
Setup queue for this agent === Parameters name(String):: Queue name ids(Array):: Identity of brokers for which to subscribe, defaults to all usable === Return (Array):: Identity of brokers to which subscribe submitted (although may still fail)
[ "Setup", "queue", "for", "this", "agent" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/agent.rb#L854-L859
train
rightscale/right_agent
lib/right_agent/agent.rb
RightScale.Agent.handle_packet
def handle_packet(queue, packet, header) begin # Continue to dispatch/ack requests even when terminating otherwise will block results # Ideally would reject requests when terminating but broker client does not yet support that case packet when Push, Request then dispatch_request(packet, queue) when Result then deliver_response(packet) end @sender.message_received rescue Exception => e ErrorTracker.log(self, "#{queue} queue processing error", e) ensure # Relying on fact that all dispatches/deliveries are synchronous and therefore # need to have completed or failed by now, thus allowing packet acknowledgement header.ack end true end
ruby
def handle_packet(queue, packet, header) begin # Continue to dispatch/ack requests even when terminating otherwise will block results # Ideally would reject requests when terminating but broker client does not yet support that case packet when Push, Request then dispatch_request(packet, queue) when Result then deliver_response(packet) end @sender.message_received rescue Exception => e ErrorTracker.log(self, "#{queue} queue processing error", e) ensure # Relying on fact that all dispatches/deliveries are synchronous and therefore # need to have completed or failed by now, thus allowing packet acknowledgement header.ack end true end
[ "def", "handle_packet", "(", "queue", ",", "packet", ",", "header", ")", "begin", "case", "packet", "when", "Push", ",", "Request", "then", "dispatch_request", "(", "packet", ",", "queue", ")", "when", "Result", "then", "deliver_response", "(", "packet", ")", "end", "@sender", ".", "message_received", "rescue", "Exception", "=>", "e", "ErrorTracker", ".", "log", "(", "self", ",", "\"#{queue} queue processing error\"", ",", "e", ")", "ensure", "header", ".", "ack", "end", "true", "end" ]
Handle packet from queue === Parameters queue(String):: Name of queue from which message was received packet(Packet):: Packet received header(AMQP::Frame::Header):: Packet header containing ack control === Return true:: Always return true
[ "Handle", "packet", "from", "queue" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/agent.rb#L870-L887
train
rightscale/right_agent
lib/right_agent/agent.rb
RightScale.Agent.dispatch_request
def dispatch_request(request, queue) begin if (dispatcher = @dispatchers[queue]) if (result = dispatcher.dispatch(request)) exchange = {:type => :queue, :name => request.reply_to, :options => {:durable => true, :no_declare => @options[:secure]}} @client.publish(exchange, result, :persistent => true, :mandatory => true, :log_filter => [:request_from, :tries, :persistent, :duration]) end else ErrorTracker.log(self, "Failed to dispatch request #{request.trace} from queue #{queue} because no dispatcher configured") @request_failure_stats.update("NoConfiguredDispatcher") end rescue Dispatcher::DuplicateRequest rescue RightAMQP::HABrokerClient::NoConnectedBrokers => e ErrorTracker.log(self, "Failed to publish result of dispatched request #{request.trace} from queue #{queue}", e) @request_failure_stats.update("NoConnectedBrokers") rescue StandardError => e ErrorTracker.log(self, "Failed to dispatch request #{request.trace} from queue #{queue}", e) @request_failure_stats.update(e.class.name) end true end
ruby
def dispatch_request(request, queue) begin if (dispatcher = @dispatchers[queue]) if (result = dispatcher.dispatch(request)) exchange = {:type => :queue, :name => request.reply_to, :options => {:durable => true, :no_declare => @options[:secure]}} @client.publish(exchange, result, :persistent => true, :mandatory => true, :log_filter => [:request_from, :tries, :persistent, :duration]) end else ErrorTracker.log(self, "Failed to dispatch request #{request.trace} from queue #{queue} because no dispatcher configured") @request_failure_stats.update("NoConfiguredDispatcher") end rescue Dispatcher::DuplicateRequest rescue RightAMQP::HABrokerClient::NoConnectedBrokers => e ErrorTracker.log(self, "Failed to publish result of dispatched request #{request.trace} from queue #{queue}", e) @request_failure_stats.update("NoConnectedBrokers") rescue StandardError => e ErrorTracker.log(self, "Failed to dispatch request #{request.trace} from queue #{queue}", e) @request_failure_stats.update(e.class.name) end true end
[ "def", "dispatch_request", "(", "request", ",", "queue", ")", "begin", "if", "(", "dispatcher", "=", "@dispatchers", "[", "queue", "]", ")", "if", "(", "result", "=", "dispatcher", ".", "dispatch", "(", "request", ")", ")", "exchange", "=", "{", ":type", "=>", ":queue", ",", ":name", "=>", "request", ".", "reply_to", ",", ":options", "=>", "{", ":durable", "=>", "true", ",", ":no_declare", "=>", "@options", "[", ":secure", "]", "}", "}", "@client", ".", "publish", "(", "exchange", ",", "result", ",", ":persistent", "=>", "true", ",", ":mandatory", "=>", "true", ",", ":log_filter", "=>", "[", ":request_from", ",", ":tries", ",", ":persistent", ",", ":duration", "]", ")", "end", "else", "ErrorTracker", ".", "log", "(", "self", ",", "\"Failed to dispatch request #{request.trace} from queue #{queue} because no dispatcher configured\"", ")", "@request_failure_stats", ".", "update", "(", "\"NoConfiguredDispatcher\"", ")", "end", "rescue", "Dispatcher", "::", "DuplicateRequest", "rescue", "RightAMQP", "::", "HABrokerClient", "::", "NoConnectedBrokers", "=>", "e", "ErrorTracker", ".", "log", "(", "self", ",", "\"Failed to publish result of dispatched request #{request.trace} from queue #{queue}\"", ",", "e", ")", "@request_failure_stats", ".", "update", "(", "\"NoConnectedBrokers\"", ")", "rescue", "StandardError", "=>", "e", "ErrorTracker", ".", "log", "(", "self", ",", "\"Failed to dispatch request #{request.trace} from queue #{queue}\"", ",", "e", ")", "@request_failure_stats", ".", "update", "(", "e", ".", "class", ".", "name", ")", "end", "true", "end" ]
Dispatch request and then send response if any === Parameters request(Push|Request):: Packet containing request queue(String):: Name of queue from which message was received === Return true:: Always return true
[ "Dispatch", "request", "and", "then", "send", "response", "if", "any" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/agent.rb#L897-L917
train
rightscale/right_agent
lib/right_agent/agent.rb
RightScale.Agent.deliver_response
def deliver_response(result) begin @sender.handle_response(result) rescue StandardError => e ErrorTracker.log(self, "Failed to deliver response #{result.trace}", e) @response_failure_stats.update(e.class.name) end true end
ruby
def deliver_response(result) begin @sender.handle_response(result) rescue StandardError => e ErrorTracker.log(self, "Failed to deliver response #{result.trace}", e) @response_failure_stats.update(e.class.name) end true end
[ "def", "deliver_response", "(", "result", ")", "begin", "@sender", ".", "handle_response", "(", "result", ")", "rescue", "StandardError", "=>", "e", "ErrorTracker", ".", "log", "(", "self", ",", "\"Failed to deliver response #{result.trace}\"", ",", "e", ")", "@response_failure_stats", ".", "update", "(", "e", ".", "class", ".", "name", ")", "end", "true", "end" ]
Deliver response to request sender === Parameters result(Result):: Packet containing response === Return true:: Always return true
[ "Deliver", "response", "to", "request", "sender" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/agent.rb#L926-L934
train
rightscale/right_agent
lib/right_agent/agent.rb
RightScale.Agent.finish_setup
def finish_setup @client.failed.each do |id| p = {:agent_identity => @identity} p[:host], p[:port], p[:id], p[:priority] = @client.identity_parts(id) @sender.send_push("/registrar/connect", p) end true end
ruby
def finish_setup @client.failed.each do |id| p = {:agent_identity => @identity} p[:host], p[:port], p[:id], p[:priority] = @client.identity_parts(id) @sender.send_push("/registrar/connect", p) end true end
[ "def", "finish_setup", "@client", ".", "failed", ".", "each", "do", "|", "id", "|", "p", "=", "{", ":agent_identity", "=>", "@identity", "}", "p", "[", ":host", "]", ",", "p", "[", ":port", "]", ",", "p", "[", ":id", "]", ",", "p", "[", ":priority", "]", "=", "@client", ".", "identity_parts", "(", "id", ")", "@sender", ".", "send_push", "(", "\"/registrar/connect\"", ",", "p", ")", "end", "true", "end" ]
Finish any remaining agent setup === Return true:: Always return true
[ "Finish", "any", "remaining", "agent", "setup" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/agent.rb#L940-L947
train
rightscale/right_agent
lib/right_agent/agent.rb
RightScale.Agent.publish_stats
def publish_stats s = stats({}).content if @mode == :http @client.notify({:type => "Stats", :from => @identity, :data => s}, nil) else exchange = {:type => :topic, :name => "stats", :options => {:no_declare => true}} @client.publish(exchange, Stats.new(s, @identity), :no_log => true, :routing_key => @stats_routing_key, :brokers => @check_status_brokers.rotate!) end true end
ruby
def publish_stats s = stats({}).content if @mode == :http @client.notify({:type => "Stats", :from => @identity, :data => s}, nil) else exchange = {:type => :topic, :name => "stats", :options => {:no_declare => true}} @client.publish(exchange, Stats.new(s, @identity), :no_log => true, :routing_key => @stats_routing_key, :brokers => @check_status_brokers.rotate!) end true end
[ "def", "publish_stats", "s", "=", "stats", "(", "{", "}", ")", ".", "content", "if", "@mode", "==", ":http", "@client", ".", "notify", "(", "{", ":type", "=>", "\"Stats\"", ",", ":from", "=>", "@identity", ",", ":data", "=>", "s", "}", ",", "nil", ")", "else", "exchange", "=", "{", ":type", "=>", ":topic", ",", ":name", "=>", "\"stats\"", ",", ":options", "=>", "{", ":no_declare", "=>", "true", "}", "}", "@client", ".", "publish", "(", "exchange", ",", "Stats", ".", "new", "(", "s", ",", "@identity", ")", ",", ":no_log", "=>", "true", ",", ":routing_key", "=>", "@stats_routing_key", ",", ":brokers", "=>", "@check_status_brokers", ".", "rotate!", ")", "end", "true", "end" ]
Publish current stats === Return true:: Always return true
[ "Publish", "current", "stats" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/agent.rb#L1035-L1045
train
rightscale/right_agent
lib/right_agent/agent.rb
RightScale.Agent.stop_gracefully
def stop_gracefully(timeout) if @mode == :http @client.close else @client.unusable.each { |id| @client.close_one(id, propagate = false) } end finish_terminating(timeout) end
ruby
def stop_gracefully(timeout) if @mode == :http @client.close else @client.unusable.each { |id| @client.close_one(id, propagate = false) } end finish_terminating(timeout) end
[ "def", "stop_gracefully", "(", "timeout", ")", "if", "@mode", "==", ":http", "@client", ".", "close", "else", "@client", ".", "unusable", ".", "each", "{", "|", "id", "|", "@client", ".", "close_one", "(", "id", ",", "propagate", "=", "false", ")", "}", "end", "finish_terminating", "(", "timeout", ")", "end" ]
Gracefully stop processing Close clients except for authorization === Parameters timeout(Integer):: Maximum number of seconds to wait after last request received before terminating regardless of whether there are still unfinished requests === Return true:: Always return true
[ "Gracefully", "stop", "processing", "Close", "clients", "except", "for", "authorization" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/agent.rb#L1079-L1086
train
rightscale/right_agent
lib/right_agent/agent.rb
RightScale.Agent.finish_terminating
def finish_terminating(timeout) if @sender request_count, request_age = @sender.terminate finish = lambda do request_count, request_age = @sender.terminate Log.info("[stop] The following #{request_count} requests initiated as recently as #{request_age} " + "seconds ago are being dropped:\n " + @sender.dump_requests.join("\n ")) if request_age if @mode == :http @terminate_callback.call else @client.close { @terminate_callback.call } end end if (wait_time = [timeout - (request_age || timeout), 0].max) > 0 Log.info("[stop] Termination waiting #{wait_time} seconds for completion of #{request_count} " + "requests initiated as recently as #{request_age} seconds ago") @termination_timer = EM::Timer.new(wait_time) do begin Log.info("[stop] Continuing with termination") finish.call rescue Exception => e ErrorTracker.log(self, "Failed while finishing termination", e) begin @terminate_callback.call; rescue Exception; end end end else finish.call end else @terminate_callback.call end @history.update("graceful exit") true end
ruby
def finish_terminating(timeout) if @sender request_count, request_age = @sender.terminate finish = lambda do request_count, request_age = @sender.terminate Log.info("[stop] The following #{request_count} requests initiated as recently as #{request_age} " + "seconds ago are being dropped:\n " + @sender.dump_requests.join("\n ")) if request_age if @mode == :http @terminate_callback.call else @client.close { @terminate_callback.call } end end if (wait_time = [timeout - (request_age || timeout), 0].max) > 0 Log.info("[stop] Termination waiting #{wait_time} seconds for completion of #{request_count} " + "requests initiated as recently as #{request_age} seconds ago") @termination_timer = EM::Timer.new(wait_time) do begin Log.info("[stop] Continuing with termination") finish.call rescue Exception => e ErrorTracker.log(self, "Failed while finishing termination", e) begin @terminate_callback.call; rescue Exception; end end end else finish.call end else @terminate_callback.call end @history.update("graceful exit") true end
[ "def", "finish_terminating", "(", "timeout", ")", "if", "@sender", "request_count", ",", "request_age", "=", "@sender", ".", "terminate", "finish", "=", "lambda", "do", "request_count", ",", "request_age", "=", "@sender", ".", "terminate", "Log", ".", "info", "(", "\"[stop] The following #{request_count} requests initiated as recently as #{request_age} \"", "+", "\"seconds ago are being dropped:\\n \"", "+", "@sender", ".", "dump_requests", ".", "join", "(", "\"\\n \"", ")", ")", "if", "request_age", "if", "@mode", "==", ":http", "@terminate_callback", ".", "call", "else", "@client", ".", "close", "{", "@terminate_callback", ".", "call", "}", "end", "end", "if", "(", "wait_time", "=", "[", "timeout", "-", "(", "request_age", "||", "timeout", ")", ",", "0", "]", ".", "max", ")", ">", "0", "Log", ".", "info", "(", "\"[stop] Termination waiting #{wait_time} seconds for completion of #{request_count} \"", "+", "\"requests initiated as recently as #{request_age} seconds ago\"", ")", "@termination_timer", "=", "EM", "::", "Timer", ".", "new", "(", "wait_time", ")", "do", "begin", "Log", ".", "info", "(", "\"[stop] Continuing with termination\"", ")", "finish", ".", "call", "rescue", "Exception", "=>", "e", "ErrorTracker", ".", "log", "(", "self", ",", "\"Failed while finishing termination\"", ",", "e", ")", "begin", "@terminate_callback", ".", "call", ";", "rescue", "Exception", ";", "end", "end", "end", "else", "finish", ".", "call", "end", "else", "@terminate_callback", ".", "call", "end", "@history", ".", "update", "(", "\"graceful exit\"", ")", "true", "end" ]
Finish termination after all requests have been processed === Parameters timeout(Integer):: Maximum number of seconds to wait after last request received before terminating regardless of whether there are still unfinished requests === Return true:: Always return true
[ "Finish", "termination", "after", "all", "requests", "have", "been", "processed" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/agent.rb#L1096-L1131
train
rightscale/right_agent
lib/right_agent/command/command_client.rb
RightScale.CommandClient.send_command
def send_command(options, verbose=false, timeout=20, &handler) return if @closing @last_timeout = timeout manage_em = !EM.reactor_running? response_handler = lambda do EM.stop if manage_em handler.call(@response) if handler && @response @pending -= 1 @close_handler.call if @close_handler && @pending == 0 end send_handler = lambda do @pending += 1 command = options.dup command[:verbose] = verbose command[:timeout] = timeout command[:cookie] = @cookie EM.next_tick { EM.connect('127.0.0.1', @socket_port, ConnectionHandler, command, self, response_handler) } EM.add_timer(timeout) { EM.stop; raise 'Timed out waiting for agent reply' } if manage_em end if manage_em EM.run { send_handler.call } else send_handler.call end true end
ruby
def send_command(options, verbose=false, timeout=20, &handler) return if @closing @last_timeout = timeout manage_em = !EM.reactor_running? response_handler = lambda do EM.stop if manage_em handler.call(@response) if handler && @response @pending -= 1 @close_handler.call if @close_handler && @pending == 0 end send_handler = lambda do @pending += 1 command = options.dup command[:verbose] = verbose command[:timeout] = timeout command[:cookie] = @cookie EM.next_tick { EM.connect('127.0.0.1', @socket_port, ConnectionHandler, command, self, response_handler) } EM.add_timer(timeout) { EM.stop; raise 'Timed out waiting for agent reply' } if manage_em end if manage_em EM.run { send_handler.call } else send_handler.call end true end
[ "def", "send_command", "(", "options", ",", "verbose", "=", "false", ",", "timeout", "=", "20", ",", "&", "handler", ")", "return", "if", "@closing", "@last_timeout", "=", "timeout", "manage_em", "=", "!", "EM", ".", "reactor_running?", "response_handler", "=", "lambda", "do", "EM", ".", "stop", "if", "manage_em", "handler", ".", "call", "(", "@response", ")", "if", "handler", "&&", "@response", "@pending", "-=", "1", "@close_handler", ".", "call", "if", "@close_handler", "&&", "@pending", "==", "0", "end", "send_handler", "=", "lambda", "do", "@pending", "+=", "1", "command", "=", "options", ".", "dup", "command", "[", ":verbose", "]", "=", "verbose", "command", "[", ":timeout", "]", "=", "timeout", "command", "[", ":cookie", "]", "=", "@cookie", "EM", ".", "next_tick", "{", "EM", ".", "connect", "(", "'127.0.0.1'", ",", "@socket_port", ",", "ConnectionHandler", ",", "command", ",", "self", ",", "response_handler", ")", "}", "EM", ".", "add_timer", "(", "timeout", ")", "{", "EM", ".", "stop", ";", "raise", "'Timed out waiting for agent reply'", "}", "if", "manage_em", "end", "if", "manage_em", "EM", ".", "run", "{", "send_handler", ".", "call", "}", "else", "send_handler", ".", "call", "end", "true", "end" ]
Send command to running agent === Parameters options(Hash):: Hash of options and command name options[:name]:: Command name options[:...]:: Other command specific options, passed through to agent verbose(Boolean):: Whether client should display debug info timeout(Integer):: Number of seconds we should wait for a reply from the agent === Block handler: Command results handler === Return true:: Always return true === Raise RuntimeError:: Timed out waiting for result, raised in EM thread
[ "Send", "command", "to", "running", "agent" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/command/command_client.rb#L71-L96
train
rightscale/right_agent
lib/right_agent/pid_file.rb
RightScale.PidFile.check
def check if pid = read_pid[:pid] if process_running?(pid) raise AlreadyRunning.new("#{@pid_file} already exists and process is running (pid: #{pid})") else Log.info("Removing stale pid file: #{@pid_file}") remove end end true end
ruby
def check if pid = read_pid[:pid] if process_running?(pid) raise AlreadyRunning.new("#{@pid_file} already exists and process is running (pid: #{pid})") else Log.info("Removing stale pid file: #{@pid_file}") remove end end true end
[ "def", "check", "if", "pid", "=", "read_pid", "[", ":pid", "]", "if", "process_running?", "(", "pid", ")", "raise", "AlreadyRunning", ".", "new", "(", "\"#{@pid_file} already exists and process is running (pid: #{pid})\"", ")", "else", "Log", ".", "info", "(", "\"Removing stale pid file: #{@pid_file}\"", ")", "remove", "end", "end", "true", "end" ]
Initialize pid file location from agent identity and pid directory Check whether pid file can be created Delete any existing pid file if process is not running anymore === Return true:: Always return true === Raise AlreadyRunning:: If pid file already exists and process is running
[ "Initialize", "pid", "file", "location", "from", "agent", "identity", "and", "pid", "directory", "Check", "whether", "pid", "file", "can", "be", "created", "Delete", "any", "existing", "pid", "file", "if", "process", "is", "not", "running", "anymore" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/pid_file.rb#L54-L64
train
rightscale/right_agent
lib/right_agent/pid_file.rb
RightScale.PidFile.write
def write begin FileUtils.mkdir_p(@pid_dir) open(@pid_file,'w') { |f| f.write(Process.pid) } File.chmod(0644, @pid_file) rescue StandardError => e ErrorTracker.log(self, "Failed to create PID file", e, nil, :caller) raise end true end
ruby
def write begin FileUtils.mkdir_p(@pid_dir) open(@pid_file,'w') { |f| f.write(Process.pid) } File.chmod(0644, @pid_file) rescue StandardError => e ErrorTracker.log(self, "Failed to create PID file", e, nil, :caller) raise end true end
[ "def", "write", "begin", "FileUtils", ".", "mkdir_p", "(", "@pid_dir", ")", "open", "(", "@pid_file", ",", "'w'", ")", "{", "|", "f", "|", "f", ".", "write", "(", "Process", ".", "pid", ")", "}", "File", ".", "chmod", "(", "0644", ",", "@pid_file", ")", "rescue", "StandardError", "=>", "e", "ErrorTracker", ".", "log", "(", "self", ",", "\"Failed to create PID file\"", ",", "e", ",", "nil", ",", ":caller", ")", "raise", "end", "true", "end" ]
Write pid to pid file === Return true:: Always return true
[ "Write", "pid", "to", "pid", "file" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/pid_file.rb#L70-L80
train
rightscale/right_agent
lib/right_agent/pid_file.rb
RightScale.PidFile.set_command_options
def set_command_options(options) content = { :listen_port => options[:listen_port], :cookie => options[:cookie] } # This is requried to preserve cookie value to be saved as string, # and not as escaped binary data content[:cookie].force_encoding('utf-8') open(@cookie_file,'w') { |f| f.write(YAML.dump(content)) } File.chmod(0600, @cookie_file) true end
ruby
def set_command_options(options) content = { :listen_port => options[:listen_port], :cookie => options[:cookie] } # This is requried to preserve cookie value to be saved as string, # and not as escaped binary data content[:cookie].force_encoding('utf-8') open(@cookie_file,'w') { |f| f.write(YAML.dump(content)) } File.chmod(0600, @cookie_file) true end
[ "def", "set_command_options", "(", "options", ")", "content", "=", "{", ":listen_port", "=>", "options", "[", ":listen_port", "]", ",", ":cookie", "=>", "options", "[", ":cookie", "]", "}", "content", "[", ":cookie", "]", ".", "force_encoding", "(", "'utf-8'", ")", "open", "(", "@cookie_file", ",", "'w'", ")", "{", "|", "f", "|", "f", ".", "write", "(", "YAML", ".", "dump", "(", "content", ")", ")", "}", "File", ".", "chmod", "(", "0600", ",", "@cookie_file", ")", "true", "end" ]
Update associated command protocol port === Parameters options[:listen_port](Integer):: Command protocol port to be used for this agent options[:cookie](String):: Cookie to be used together with command protocol === Return true:: Always return true
[ "Update", "associated", "command", "protocol", "port" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/pid_file.rb#L90-L98
train
rightscale/right_agent
lib/right_agent/pid_file.rb
RightScale.PidFile.read_pid
def read_pid content = {} if exists? open(@pid_file,'r') { |f| content[:pid] = f.read.to_i } open(@cookie_file,'r') do |f| command_options = (YAML.load(f.read) rescue {}) || {} content.merge!(command_options) end if File.readable?(@cookie_file) end content end
ruby
def read_pid content = {} if exists? open(@pid_file,'r') { |f| content[:pid] = f.read.to_i } open(@cookie_file,'r') do |f| command_options = (YAML.load(f.read) rescue {}) || {} content.merge!(command_options) end if File.readable?(@cookie_file) end content end
[ "def", "read_pid", "content", "=", "{", "}", "if", "exists?", "open", "(", "@pid_file", ",", "'r'", ")", "{", "|", "f", "|", "content", "[", ":pid", "]", "=", "f", ".", "read", ".", "to_i", "}", "open", "(", "@cookie_file", ",", "'r'", ")", "do", "|", "f", "|", "command_options", "=", "(", "YAML", ".", "load", "(", "f", ".", "read", ")", "rescue", "{", "}", ")", "||", "{", "}", "content", ".", "merge!", "(", "command_options", ")", "end", "if", "File", ".", "readable?", "(", "@cookie_file", ")", "end", "content", "end" ]
Read pid file content Empty hash if pid file does not exist or content cannot be loaded === Return content(Hash):: Hash containing 3 keys :pid, :cookie and :port
[ "Read", "pid", "file", "content", "Empty", "hash", "if", "pid", "file", "does", "not", "exist", "or", "content", "cannot", "be", "loaded" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/pid_file.rb#L115-L125
train
rightscale/right_agent
lib/right_agent/packets.rb
RightScale.Packet.to_msgpack
def to_msgpack(*a) msg = { 'msgpack_class' => self.class.name, 'data' => instance_variables.inject({}) do |m, ivar| name = ivar.to_s.sub(/@/, '') m[name] = instance_variable_get(ivar) unless NOT_SERIALIZED.include?(name) m end, 'size' => nil }.to_msgpack(*a) @size = msg.size # For msgpack 0.5.1 the to_msgpack result is a MessagePack::Packer so need to convert to string msg = msg.to_s.sub!(PACKET_SIZE_REGEXP) { |m| "size" + @size.to_msgpack } msg end
ruby
def to_msgpack(*a) msg = { 'msgpack_class' => self.class.name, 'data' => instance_variables.inject({}) do |m, ivar| name = ivar.to_s.sub(/@/, '') m[name] = instance_variable_get(ivar) unless NOT_SERIALIZED.include?(name) m end, 'size' => nil }.to_msgpack(*a) @size = msg.size # For msgpack 0.5.1 the to_msgpack result is a MessagePack::Packer so need to convert to string msg = msg.to_s.sub!(PACKET_SIZE_REGEXP) { |m| "size" + @size.to_msgpack } msg end
[ "def", "to_msgpack", "(", "*", "a", ")", "msg", "=", "{", "'msgpack_class'", "=>", "self", ".", "class", ".", "name", ",", "'data'", "=>", "instance_variables", ".", "inject", "(", "{", "}", ")", "do", "|", "m", ",", "ivar", "|", "name", "=", "ivar", ".", "to_s", ".", "sub", "(", "/", "/", ",", "''", ")", "m", "[", "name", "]", "=", "instance_variable_get", "(", "ivar", ")", "unless", "NOT_SERIALIZED", ".", "include?", "(", "name", ")", "m", "end", ",", "'size'", "=>", "nil", "}", ".", "to_msgpack", "(", "*", "a", ")", "@size", "=", "msg", ".", "size", "msg", "=", "msg", ".", "to_s", ".", "sub!", "(", "PACKET_SIZE_REGEXP", ")", "{", "|", "m", "|", "\"size\"", "+", "@size", ".", "to_msgpack", "}", "msg", "end" ]
Marshal packet into MessagePack format === Parameters a(Array):: Arguments === Return msg(String):: Marshalled packet
[ "Marshal", "packet", "into", "MessagePack", "format" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/packets.rb#L102-L116
train
rightscale/right_agent
lib/right_agent/packets.rb
RightScale.Packet.to_json
def to_json(*a) # Hack to override RightScale namespace with Nanite for downward compatibility class_name = self.class.name if class_name =~ /^RightScale::(.*)/ class_name = "Nanite::" + Regexp.last_match(1) end js = { 'json_class' => class_name, 'data' => instance_variables.inject({}) do |m, ivar| name = ivar.to_s.sub(/@/, '') m[name] = instance_variable_get(ivar) unless NOT_SERIALIZED.include?(name) m end }.to_json(*a) @size = js.size js = js.chop + ",\"size\":#{@size}}" end
ruby
def to_json(*a) # Hack to override RightScale namespace with Nanite for downward compatibility class_name = self.class.name if class_name =~ /^RightScale::(.*)/ class_name = "Nanite::" + Regexp.last_match(1) end js = { 'json_class' => class_name, 'data' => instance_variables.inject({}) do |m, ivar| name = ivar.to_s.sub(/@/, '') m[name] = instance_variable_get(ivar) unless NOT_SERIALIZED.include?(name) m end }.to_json(*a) @size = js.size js = js.chop + ",\"size\":#{@size}}" end
[ "def", "to_json", "(", "*", "a", ")", "class_name", "=", "self", ".", "class", ".", "name", "if", "class_name", "=~", "/", "/", "class_name", "=", "\"Nanite::\"", "+", "Regexp", ".", "last_match", "(", "1", ")", "end", "js", "=", "{", "'json_class'", "=>", "class_name", ",", "'data'", "=>", "instance_variables", ".", "inject", "(", "{", "}", ")", "do", "|", "m", ",", "ivar", "|", "name", "=", "ivar", ".", "to_s", ".", "sub", "(", "/", "/", ",", "''", ")", "m", "[", "name", "]", "=", "instance_variable_get", "(", "ivar", ")", "unless", "NOT_SERIALIZED", ".", "include?", "(", "name", ")", "m", "end", "}", ".", "to_json", "(", "*", "a", ")", "@size", "=", "js", ".", "size", "js", "=", "js", ".", "chop", "+", "\",\\\"size\\\":#{@size}}\"", "end" ]
Marshal packet into JSON format === Parameters a(Array):: Arguments === Return js(String):: Marshalled packet
[ "Marshal", "packet", "into", "JSON", "format" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/packets.rb#L125-L142
train
rightscale/right_agent
lib/right_agent/packets.rb
RightScale.Packet.enough_precision
def enough_precision(value) scale = [1.0, 10.0, 100.0, 1000.0, 10000.0, 100000.0] enough = lambda { |v| (v >= 10.0 ? 0 : (v >= 1.0 ? 1 : (v >= 0.1 ? 2 : (v >= 0.01 ? 3 : (v > 0.001 ? 4 : (v > 0.0 ? 5 : 0)))))) } digit_str = lambda { |p, v| sprintf("%.#{p}f", (v * scale[p]).round / scale[p])} digit_str.call(enough.call(value), value) end
ruby
def enough_precision(value) scale = [1.0, 10.0, 100.0, 1000.0, 10000.0, 100000.0] enough = lambda { |v| (v >= 10.0 ? 0 : (v >= 1.0 ? 1 : (v >= 0.1 ? 2 : (v >= 0.01 ? 3 : (v > 0.001 ? 4 : (v > 0.0 ? 5 : 0)))))) } digit_str = lambda { |p, v| sprintf("%.#{p}f", (v * scale[p]).round / scale[p])} digit_str.call(enough.call(value), value) end
[ "def", "enough_precision", "(", "value", ")", "scale", "=", "[", "1.0", ",", "10.0", ",", "100.0", ",", "1000.0", ",", "10000.0", ",", "100000.0", "]", "enough", "=", "lambda", "{", "|", "v", "|", "(", "v", ">=", "10.0", "?", "0", ":", "(", "v", ">=", "1.0", "?", "1", ":", "(", "v", ">=", "0.1", "?", "2", ":", "(", "v", ">=", "0.01", "?", "3", ":", "(", "v", ">", "0.001", "?", "4", ":", "(", "v", ">", "0.0", "?", "5", ":", "0", ")", ")", ")", ")", ")", ")", "}", "digit_str", "=", "lambda", "{", "|", "p", ",", "v", "|", "sprintf", "(", "\"%.#{p}f\"", ",", "(", "v", "*", "scale", "[", "p", "]", ")", ".", "round", "/", "scale", "[", "p", "]", ")", "}", "digit_str", ".", "call", "(", "enough", ".", "call", "(", "value", ")", ",", "value", ")", "end" ]
Determine enough precision for floating point value to give at least two significant digits and then convert the value to a decimal digit string of that precision === Parameters value(Float):: Value to be converted === Return (String):: Floating point digit string
[ "Determine", "enough", "precision", "for", "floating", "point", "value", "to", "give", "at", "least", "two", "significant", "digits", "and", "then", "convert", "the", "value", "to", "a", "decimal", "digit", "string", "of", "that", "precision" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/packets.rb#L181-L191
train
rightscale/right_agent
lib/right_agent/packets.rb
RightScale.Packet.ids_to_s
def ids_to_s(ids) if ids.is_a?(Array) s = ids.each { |i| id_to_s(i) }.join(', ') s.size > 1000 ? "[#{s[0, 1000]}...]" : "[#{s}]" else id_to_s(ids) end end
ruby
def ids_to_s(ids) if ids.is_a?(Array) s = ids.each { |i| id_to_s(i) }.join(', ') s.size > 1000 ? "[#{s[0, 1000]}...]" : "[#{s}]" else id_to_s(ids) end end
[ "def", "ids_to_s", "(", "ids", ")", "if", "ids", ".", "is_a?", "(", "Array", ")", "s", "=", "ids", ".", "each", "{", "|", "i", "|", "id_to_s", "(", "i", ")", "}", ".", "join", "(", "', '", ")", "s", ".", "size", ">", "1000", "?", "\"[#{s[0, 1000]}...]\"", ":", "\"[#{s}]\"", "else", "id_to_s", "(", "ids", ")", "end", "end" ]
Generate log friendly serialized identity for one or more ids Limit to 1000 bytes === Parameters ids(Array|String):: Serialized identity or array of serialized identities === Return (String):: Log friendly serialized identity
[ "Generate", "log", "friendly", "serialized", "identity", "for", "one", "or", "more", "ids", "Limit", "to", "1000", "bytes" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/packets.rb#L214-L221
train
rightscale/right_agent
lib/right_agent/packets.rb
RightScale.Packet.trace
def trace audit_id = self.respond_to?(:payload) && payload.is_a?(Hash) && (payload['audit_id'] || payload[:audit_id]) tok = self.respond_to?(:token) && token tr = "<#{audit_id || nil}> <#{tok}>" end
ruby
def trace audit_id = self.respond_to?(:payload) && payload.is_a?(Hash) && (payload['audit_id'] || payload[:audit_id]) tok = self.respond_to?(:token) && token tr = "<#{audit_id || nil}> <#{tok}>" end
[ "def", "trace", "audit_id", "=", "self", ".", "respond_to?", "(", ":payload", ")", "&&", "payload", ".", "is_a?", "(", "Hash", ")", "&&", "(", "payload", "[", "'audit_id'", "]", "||", "payload", "[", ":audit_id", "]", ")", "tok", "=", "self", ".", "respond_to?", "(", ":token", ")", "&&", "token", "tr", "=", "\"<#{audit_id || nil}> <#{tok}>\"", "end" ]
Generate token used to trace execution of operation across multiple packets === Return tr(String):: Trace token, may be empty
[ "Generate", "token", "used", "to", "trace", "execution", "of", "operation", "across", "multiple", "packets" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/packets.rb#L254-L258
train
rightscale/right_agent
lib/right_agent/clients/router_client.rb
RightScale.RouterClient.push
def push(type, payload, target, options = {}) params = { :type => type, :payload => payload, :target => target } make_request(:post, "/push", params, type.split("/")[2], options) end
ruby
def push(type, payload, target, options = {}) params = { :type => type, :payload => payload, :target => target } make_request(:post, "/push", params, type.split("/")[2], options) end
[ "def", "push", "(", "type", ",", "payload", ",", "target", ",", "options", "=", "{", "}", ")", "params", "=", "{", ":type", "=>", "type", ",", ":payload", "=>", "payload", ",", ":target", "=>", "target", "}", "make_request", "(", ":post", ",", "\"/push\"", ",", "params", ",", "type", ".", "split", "(", "\"/\"", ")", "[", "2", "]", ",", "options", ")", "end" ]
Create RightNet router client @param [AuthClient] auth_client providing authorization session for HTTP requests @option options [Numeric] :open_timeout maximum wait for connection; defaults to DEFAULT_OPEN_TIMEOUT @option options [Numeric] :request_timeout maximum wait for response; defaults to DEFAULT_REQUEST_TIMEOUT @option options [Numeric] :listen_timeout maximum wait for event; defaults to DEFAULT_LISTEN_TIMEOUT @option options [Boolean] :long_polling_only never attempt to create a WebSocket, always long-polling instead @option options [Numeric] :retry_timeout maximum before stop retrying; defaults to DEFAULT_RETRY_TIMEOUT @option options [Array] :retry_intervals between successive retries; defaults to DEFAULT_RETRY_INTERVALS @option options [Boolean] :retry_enabled for requests that fail to connect or that return a retry result @option options [Numeric] :reconnect_interval for reconnect attempts after lose connectivity @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 [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 @raise [ArgumentError] auth client does not support this client type 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 [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: [String] :agent_id serialized identity of specific target [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 [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
[ "Create", "RightNet", "router", "client" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/router_client.rb#L134-L140
train
rightscale/right_agent
lib/right_agent/clients/router_client.rb
RightScale.RouterClient.request
def request(type, payload, target, options = {}) params = { :type => type, :payload => payload, :target => target } make_request(:post, "/request", params, type.split("/")[2], options) end
ruby
def request(type, payload, target, options = {}) params = { :type => type, :payload => payload, :target => target } make_request(:post, "/request", params, type.split("/")[2], options) end
[ "def", "request", "(", "type", ",", "payload", ",", "target", ",", "options", "=", "{", "}", ")", "params", "=", "{", ":type", "=>", "type", ",", ":payload", "=>", "payload", ",", ":target", "=>", "target", "}", "make_request", "(", ":post", ",", "\"/request\"", ",", "params", ",", "type", ".", "split", "(", "\"/\"", ")", "[", "2", "]", ",", "options", ")", "end" ]
Route 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 30 sec 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 @param [String] type of request as path specifying actor and action @param [Hash, NilClass] payload for request @param [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: [String] :agent_id serialized identity of specific target [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 @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 [Result, NilClass] response from request @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", "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", "30", "sec", "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" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/router_client.rb#L173-L179
train
rightscale/right_agent
lib/right_agent/clients/router_client.rb
RightScale.RouterClient.notify
def notify(event, routing_keys) event[:uuid] ||= RightSupport::Data::UUID.generate event[:version] ||= AgentConfig.protocol_version params = {:event => event} params[:routing_keys] = routing_keys if routing_keys if @websocket path = event[:path] ? " #{event[:path]}" : "" to = routing_keys ? " to #{routing_keys.inspect}" : "" Log.info("Sending EVENT <#{event[:uuid]}> #{event[:type]}#{path}#{to}") @websocket.send(JSON.dump(params)) else make_request(:post, "/notify", params, "notify", :request_uuid => event[:uuid], :filter_params => ["event"]) end true end
ruby
def notify(event, routing_keys) event[:uuid] ||= RightSupport::Data::UUID.generate event[:version] ||= AgentConfig.protocol_version params = {:event => event} params[:routing_keys] = routing_keys if routing_keys if @websocket path = event[:path] ? " #{event[:path]}" : "" to = routing_keys ? " to #{routing_keys.inspect}" : "" Log.info("Sending EVENT <#{event[:uuid]}> #{event[:type]}#{path}#{to}") @websocket.send(JSON.dump(params)) else make_request(:post, "/notify", params, "notify", :request_uuid => event[:uuid], :filter_params => ["event"]) end true end
[ "def", "notify", "(", "event", ",", "routing_keys", ")", "event", "[", ":uuid", "]", "||=", "RightSupport", "::", "Data", "::", "UUID", ".", "generate", "event", "[", ":version", "]", "||=", "AgentConfig", ".", "protocol_version", "params", "=", "{", ":event", "=>", "event", "}", "params", "[", ":routing_keys", "]", "=", "routing_keys", "if", "routing_keys", "if", "@websocket", "path", "=", "event", "[", ":path", "]", "?", "\" #{event[:path]}\"", ":", "\"\"", "to", "=", "routing_keys", "?", "\" to #{routing_keys.inspect}\"", ":", "\"\"", "Log", ".", "info", "(", "\"Sending EVENT <#{event[:uuid]}> #{event[:type]}#{path}#{to}\"", ")", "@websocket", ".", "send", "(", "JSON", ".", "dump", "(", "params", ")", ")", "else", "make_request", "(", ":post", ",", "\"/notify\"", ",", "params", ",", "\"notify\"", ",", ":request_uuid", "=>", "event", "[", ":uuid", "]", ",", ":filter_params", "=>", "[", "\"event\"", "]", ")", "end", "true", "end" ]
Route event Use WebSocket if possible Do not block this request even if in the process of closing since used for request responses @param [Hash] event to send @param [Array, NilClass] routing_keys as strings to assist router in delivering event to interested parties @return [TrueClass] always true @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", "event", "Use", "WebSocket", "if", "possible", "Do", "not", "block", "this", "request", "even", "if", "in", "the", "process", "of", "closing", "since", "used", "for", "request", "responses" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/router_client.rb#L197-L211
train
rightscale/right_agent
lib/right_agent/clients/router_client.rb
RightScale.RouterClient.listen
def listen(routing_keys, &handler) raise ArgumentError, "Block missing" unless block_given? @event_uuids = nil @listen_interval = 0 @listen_state = :choose @listen_failures = 0 @connect_interval = CONNECT_INTERVAL @reconnect_interval = RECONNECT_INTERVAL listen_loop(routing_keys, &handler) true end
ruby
def listen(routing_keys, &handler) raise ArgumentError, "Block missing" unless block_given? @event_uuids = nil @listen_interval = 0 @listen_state = :choose @listen_failures = 0 @connect_interval = CONNECT_INTERVAL @reconnect_interval = RECONNECT_INTERVAL listen_loop(routing_keys, &handler) true end
[ "def", "listen", "(", "routing_keys", ",", "&", "handler", ")", "raise", "ArgumentError", ",", "\"Block missing\"", "unless", "block_given?", "@event_uuids", "=", "nil", "@listen_interval", "=", "0", "@listen_state", "=", ":choose", "@listen_failures", "=", "0", "@connect_interval", "=", "CONNECT_INTERVAL", "@reconnect_interval", "=", "RECONNECT_INTERVAL", "listen_loop", "(", "routing_keys", ",", "&", "handler", ")", "true", "end" ]
Receive events via an HTTP WebSocket if available, otherwise via an HTTP long-polling @param [Array, NilClass] routing_keys for event sources of interest with nil meaning all @yield [event] required block called each time event received @yieldparam [Hash] event received @return [TrueClass] always true, although only returns when closing @raise [ArgumentError] block missing @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
[ "Receive", "events", "via", "an", "HTTP", "WebSocket", "if", "available", "otherwise", "via", "an", "HTTP", "long", "-", "polling" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/router_client.rb#L229-L241
train
rightscale/right_agent
lib/right_agent/clients/router_client.rb
RightScale.RouterClient.listen_loop
def listen_loop(routing_keys, &handler) @listen_timer = nil begin # Perform listen action based on current state case @listen_state when :choose # Choose listen method or continue as is if already listening # or want to delay choosing choose_listen_method when :check # Check whether really got connected, given the possibility of an # asynchronous WebSocket handshake failure that resulted in a close # Continue to use WebSockets if still connected or if connect failed # due to unresponsive server if @websocket.nil? if router_not_responding? update_listen_state(:connect, backoff_reconnect_interval) else backoff_connect_interval update_listen_state(:long_poll) end elsif (@listen_checks += 1) > CHECK_INTERVAL @reconnect_interval = RECONNECT_INTERVAL update_listen_state(:choose, @connect_interval = CONNECT_INTERVAL) end when :connect # Use of WebSockets is enabled and it is again time to try to connect @stats["reconnects"].update("websocket") if @attempted_connect_at try_connect(routing_keys, &handler) when :long_poll # Resorting to long-polling # Need to long-poll on separate thread if cannot use non-blocking HTTP i/o # Will still periodically retry WebSockets if not restricted to just long-polling if @options[:non_blocking] @event_uuids = process_long_poll(try_long_poll(routing_keys, @event_uuids, &handler)) else update_listen_state(:wait, 1) try_deferred_long_poll(routing_keys, @event_uuids, &handler) end when :wait # Deferred long-polling is expected to break out of this state eventually when :cancel return false end @listen_failures = 0 rescue Exception => e ErrorTracker.log(self, "Failed to listen", e) @listen_failures += 1 if @listen_failures > MAX_LISTEN_FAILURES ErrorTracker.log(self, "Exceeded maximum repeated listen failures (#{MAX_LISTEN_FAILURES}), stopping listening") @listen_state = :cancel self.state = :failed return false end @listen_state = :choose @listen_interval = CHECK_INTERVAL end listen_loop_wait(Time.now, @listen_interval, routing_keys, &handler) end
ruby
def listen_loop(routing_keys, &handler) @listen_timer = nil begin # Perform listen action based on current state case @listen_state when :choose # Choose listen method or continue as is if already listening # or want to delay choosing choose_listen_method when :check # Check whether really got connected, given the possibility of an # asynchronous WebSocket handshake failure that resulted in a close # Continue to use WebSockets if still connected or if connect failed # due to unresponsive server if @websocket.nil? if router_not_responding? update_listen_state(:connect, backoff_reconnect_interval) else backoff_connect_interval update_listen_state(:long_poll) end elsif (@listen_checks += 1) > CHECK_INTERVAL @reconnect_interval = RECONNECT_INTERVAL update_listen_state(:choose, @connect_interval = CONNECT_INTERVAL) end when :connect # Use of WebSockets is enabled and it is again time to try to connect @stats["reconnects"].update("websocket") if @attempted_connect_at try_connect(routing_keys, &handler) when :long_poll # Resorting to long-polling # Need to long-poll on separate thread if cannot use non-blocking HTTP i/o # Will still periodically retry WebSockets if not restricted to just long-polling if @options[:non_blocking] @event_uuids = process_long_poll(try_long_poll(routing_keys, @event_uuids, &handler)) else update_listen_state(:wait, 1) try_deferred_long_poll(routing_keys, @event_uuids, &handler) end when :wait # Deferred long-polling is expected to break out of this state eventually when :cancel return false end @listen_failures = 0 rescue Exception => e ErrorTracker.log(self, "Failed to listen", e) @listen_failures += 1 if @listen_failures > MAX_LISTEN_FAILURES ErrorTracker.log(self, "Exceeded maximum repeated listen failures (#{MAX_LISTEN_FAILURES}), stopping listening") @listen_state = :cancel self.state = :failed return false end @listen_state = :choose @listen_interval = CHECK_INTERVAL end listen_loop_wait(Time.now, @listen_interval, routing_keys, &handler) end
[ "def", "listen_loop", "(", "routing_keys", ",", "&", "handler", ")", "@listen_timer", "=", "nil", "begin", "case", "@listen_state", "when", ":choose", "choose_listen_method", "when", ":check", "if", "@websocket", ".", "nil?", "if", "router_not_responding?", "update_listen_state", "(", ":connect", ",", "backoff_reconnect_interval", ")", "else", "backoff_connect_interval", "update_listen_state", "(", ":long_poll", ")", "end", "elsif", "(", "@listen_checks", "+=", "1", ")", ">", "CHECK_INTERVAL", "@reconnect_interval", "=", "RECONNECT_INTERVAL", "update_listen_state", "(", ":choose", ",", "@connect_interval", "=", "CONNECT_INTERVAL", ")", "end", "when", ":connect", "@stats", "[", "\"reconnects\"", "]", ".", "update", "(", "\"websocket\"", ")", "if", "@attempted_connect_at", "try_connect", "(", "routing_keys", ",", "&", "handler", ")", "when", ":long_poll", "if", "@options", "[", ":non_blocking", "]", "@event_uuids", "=", "process_long_poll", "(", "try_long_poll", "(", "routing_keys", ",", "@event_uuids", ",", "&", "handler", ")", ")", "else", "update_listen_state", "(", ":wait", ",", "1", ")", "try_deferred_long_poll", "(", "routing_keys", ",", "@event_uuids", ",", "&", "handler", ")", "end", "when", ":wait", "when", ":cancel", "return", "false", "end", "@listen_failures", "=", "0", "rescue", "Exception", "=>", "e", "ErrorTracker", ".", "log", "(", "self", ",", "\"Failed to listen\"", ",", "e", ")", "@listen_failures", "+=", "1", "if", "@listen_failures", ">", "MAX_LISTEN_FAILURES", "ErrorTracker", ".", "log", "(", "self", ",", "\"Exceeded maximum repeated listen failures (#{MAX_LISTEN_FAILURES}), stopping listening\"", ")", "@listen_state", "=", ":cancel", "self", ".", "state", "=", ":failed", "return", "false", "end", "@listen_state", "=", ":choose", "@listen_interval", "=", "CHECK_INTERVAL", "end", "listen_loop_wait", "(", "Time", ".", "now", ",", "@listen_interval", ",", "routing_keys", ",", "&", "handler", ")", "end" ]
Perform listen action, then wait prescribed time for next action A periodic timer is not effective here because it does not wa @param [Array, NilClass] routing_keys for event sources of interest with nil meaning all @yield [event] required block called each time event received @yieldparam [Hash] event received @return [Boolean] false if failed or terminating, otherwise true
[ "Perform", "listen", "action", "then", "wait", "prescribed", "time", "for", "next", "action", "A", "periodic", "timer", "is", "not", "effective", "here", "because", "it", "does", "not", "wa" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/router_client.rb#L292-L352
train
rightscale/right_agent
lib/right_agent/clients/router_client.rb
RightScale.RouterClient.listen_loop_wait
def listen_loop_wait(started_at, interval, routing_keys, &handler) if @listen_interval == 0 EM_S.next_tick { listen_loop(routing_keys, &handler) } else @listen_timer = EM_S::Timer.new(interval) do remaining = @listen_interval - (Time.now - started_at) if remaining > 0 listen_loop_wait(started_at, remaining, routing_keys, &handler) else listen_loop(routing_keys, &handler) end end end true end
ruby
def listen_loop_wait(started_at, interval, routing_keys, &handler) if @listen_interval == 0 EM_S.next_tick { listen_loop(routing_keys, &handler) } else @listen_timer = EM_S::Timer.new(interval) do remaining = @listen_interval - (Time.now - started_at) if remaining > 0 listen_loop_wait(started_at, remaining, routing_keys, &handler) else listen_loop(routing_keys, &handler) end end end true end
[ "def", "listen_loop_wait", "(", "started_at", ",", "interval", ",", "routing_keys", ",", "&", "handler", ")", "if", "@listen_interval", "==", "0", "EM_S", ".", "next_tick", "{", "listen_loop", "(", "routing_keys", ",", "&", "handler", ")", "}", "else", "@listen_timer", "=", "EM_S", "::", "Timer", ".", "new", "(", "interval", ")", "do", "remaining", "=", "@listen_interval", "-", "(", "Time", ".", "now", "-", "started_at", ")", "if", "remaining", ">", "0", "listen_loop_wait", "(", "started_at", ",", "remaining", ",", "routing_keys", ",", "&", "handler", ")", "else", "listen_loop", "(", "routing_keys", ",", "&", "handler", ")", "end", "end", "end", "true", "end" ]
Wait specified interval before next listen loop Continue waiting if interval changes while waiting @param [Time] started_at time when first started waiting @param [Numeric] interval to wait @param [Array, NilClass] routing_keys for event sources of interest with nil meaning all @yield [event] required block called each time event received @yieldparam [Hash] event received @return [TrueClass] always true
[ "Wait", "specified", "interval", "before", "next", "listen", "loop", "Continue", "waiting", "if", "interval", "changes", "while", "waiting" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/router_client.rb#L365-L379
train
rightscale/right_agent
lib/right_agent/clients/router_client.rb
RightScale.RouterClient.update_listen_state
def update_listen_state(state, interval = 0) if state == :cancel @listen_timer.cancel if @listen_timer @listen_timer = nil @listen_state = state elsif [:choose, :check, :connect, :long_poll, :wait].include?(state) @listen_checks = 0 if state == :check && @listen_state != :check @listen_state = state @listen_interval = interval else raise ArgumentError, "Invalid listen state: #{state.inspect}" end true end
ruby
def update_listen_state(state, interval = 0) if state == :cancel @listen_timer.cancel if @listen_timer @listen_timer = nil @listen_state = state elsif [:choose, :check, :connect, :long_poll, :wait].include?(state) @listen_checks = 0 if state == :check && @listen_state != :check @listen_state = state @listen_interval = interval else raise ArgumentError, "Invalid listen state: #{state.inspect}" end true end
[ "def", "update_listen_state", "(", "state", ",", "interval", "=", "0", ")", "if", "state", "==", ":cancel", "@listen_timer", ".", "cancel", "if", "@listen_timer", "@listen_timer", "=", "nil", "@listen_state", "=", "state", "elsif", "[", ":choose", ",", ":check", ",", ":connect", ",", ":long_poll", ",", ":wait", "]", ".", "include?", "(", "state", ")", "@listen_checks", "=", "0", "if", "state", "==", ":check", "&&", "@listen_state", "!=", ":check", "@listen_state", "=", "state", "@listen_interval", "=", "interval", "else", "raise", "ArgumentError", ",", "\"Invalid listen state: #{state.inspect}\"", "end", "true", "end" ]
Update listen state @param [Symbol] state next @param [Integer] interval before next listen action @return [TrueClass] always true @raise [ArgumentError] invalid state
[ "Update", "listen", "state" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/router_client.rb#L389-L402
train
rightscale/right_agent
lib/right_agent/clients/router_client.rb
RightScale.RouterClient.try_connect
def try_connect(routing_keys, &handler) connect(routing_keys, &handler) update_listen_state(:check, 1) rescue Exception => e ErrorTracker.log(self, "Failed creating WebSocket", e, nil, :caller) backoff_connect_interval update_listen_state(:long_poll) end
ruby
def try_connect(routing_keys, &handler) connect(routing_keys, &handler) update_listen_state(:check, 1) rescue Exception => e ErrorTracker.log(self, "Failed creating WebSocket", e, nil, :caller) backoff_connect_interval update_listen_state(:long_poll) end
[ "def", "try_connect", "(", "routing_keys", ",", "&", "handler", ")", "connect", "(", "routing_keys", ",", "&", "handler", ")", "update_listen_state", "(", ":check", ",", "1", ")", "rescue", "Exception", "=>", "e", "ErrorTracker", ".", "log", "(", "self", ",", "\"Failed creating WebSocket\"", ",", "e", ",", "nil", ",", ":caller", ")", "backoff_connect_interval", "update_listen_state", "(", ":long_poll", ")", "end" ]
Try to create WebSocket connection @param [Array, NilClass] routing_keys for event sources of interest with nil meaning all @yield [event] required block called each time event received @yieldparam [Hash] event received @return [TrueClass] always true
[ "Try", "to", "create", "WebSocket", "connection" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/router_client.rb#L437-L444
train
rightscale/right_agent
lib/right_agent/clients/router_client.rb
RightScale.RouterClient.connect
def connect(routing_keys, &handler) raise ArgumentError, "Block missing" unless block_given? @attempted_connect_at = Time.now @close_code = @close_reason = nil # Initialize use of proxy if defined if (v = BalancedHttpClient::PROXY_ENVIRONMENT_VARIABLES.detect { |v| ENV.has_key?(v) }) proxy_uri = ENV[v].match(/^[[:alpha:]]+:\/\//) ? URI.parse(ENV[v]) : URI.parse("http://" + ENV[v]) @proxy = { :origin => proxy_uri.to_s } end options = { # Limit to .auth_header here (rather than .headers) to keep WebSockets happy :headers => {"X-API-Version" => API_VERSION}.merge(@auth_client.auth_header), :ping => @options[:listen_timeout] } options[:proxy] = @proxy if @proxy url = URI.parse(@auth_client.router_url) url.scheme = url.scheme == "https" ? "wss" : "ws" url.path = url.path + "/connect" url.query = routing_keys.map { |k| "routing_keys[]=#{CGI.escape(k)}" }.join("&") if routing_keys && routing_keys.any? Log.info("Creating WebSocket connection to #{url.to_s}") @websocket = Faye::WebSocket::Client.new(url.to_s, protocols = nil, options) @websocket.onerror = lambda do |event| error = if event.respond_to?(:data) # faye-websocket 0.7.0 event.data elsif event.respond_to?(:message) # faye-websocket 0.7.4 event.message else event.to_s end ErrorTracker.log(self, "WebSocket error (#{error})") if error end @websocket.onclose = lambda do |event| begin @close_code = event.code.to_i @close_reason = event.reason msg = "WebSocket closed (#{event.code}" msg << ((event.reason.nil? || event.reason.empty?) ? ")" : ": #{event.reason})") Log.info(msg) rescue Exception => e ErrorTracker.log(self, "Failed closing WebSocket", e) end @websocket = nil end @websocket.onmessage = lambda do |event| begin # Receive event event = SerializationHelper.symbolize_keys(JSON.parser.new(event.data, JSON.load_default_options).parse) Log.info("Received EVENT <#{event[:uuid]}> #{event[:type]} #{event[:path]} from #{event[:from]}") @stats["events"].update("#{event[:type]} #{event[:path]}") # Acknowledge event @websocket.send(JSON.dump({:ack => event[:uuid]})) # Handle event handler.call(event) @communicated_callbacks.each { |callback| callback.call } if @communicated_callbacks rescue Exception => e ErrorTracker.log(self, "Failed handling WebSocket event", e) end end @websocket end
ruby
def connect(routing_keys, &handler) raise ArgumentError, "Block missing" unless block_given? @attempted_connect_at = Time.now @close_code = @close_reason = nil # Initialize use of proxy if defined if (v = BalancedHttpClient::PROXY_ENVIRONMENT_VARIABLES.detect { |v| ENV.has_key?(v) }) proxy_uri = ENV[v].match(/^[[:alpha:]]+:\/\//) ? URI.parse(ENV[v]) : URI.parse("http://" + ENV[v]) @proxy = { :origin => proxy_uri.to_s } end options = { # Limit to .auth_header here (rather than .headers) to keep WebSockets happy :headers => {"X-API-Version" => API_VERSION}.merge(@auth_client.auth_header), :ping => @options[:listen_timeout] } options[:proxy] = @proxy if @proxy url = URI.parse(@auth_client.router_url) url.scheme = url.scheme == "https" ? "wss" : "ws" url.path = url.path + "/connect" url.query = routing_keys.map { |k| "routing_keys[]=#{CGI.escape(k)}" }.join("&") if routing_keys && routing_keys.any? Log.info("Creating WebSocket connection to #{url.to_s}") @websocket = Faye::WebSocket::Client.new(url.to_s, protocols = nil, options) @websocket.onerror = lambda do |event| error = if event.respond_to?(:data) # faye-websocket 0.7.0 event.data elsif event.respond_to?(:message) # faye-websocket 0.7.4 event.message else event.to_s end ErrorTracker.log(self, "WebSocket error (#{error})") if error end @websocket.onclose = lambda do |event| begin @close_code = event.code.to_i @close_reason = event.reason msg = "WebSocket closed (#{event.code}" msg << ((event.reason.nil? || event.reason.empty?) ? ")" : ": #{event.reason})") Log.info(msg) rescue Exception => e ErrorTracker.log(self, "Failed closing WebSocket", e) end @websocket = nil end @websocket.onmessage = lambda do |event| begin # Receive event event = SerializationHelper.symbolize_keys(JSON.parser.new(event.data, JSON.load_default_options).parse) Log.info("Received EVENT <#{event[:uuid]}> #{event[:type]} #{event[:path]} from #{event[:from]}") @stats["events"].update("#{event[:type]} #{event[:path]}") # Acknowledge event @websocket.send(JSON.dump({:ack => event[:uuid]})) # Handle event handler.call(event) @communicated_callbacks.each { |callback| callback.call } if @communicated_callbacks rescue Exception => e ErrorTracker.log(self, "Failed handling WebSocket event", e) end end @websocket end
[ "def", "connect", "(", "routing_keys", ",", "&", "handler", ")", "raise", "ArgumentError", ",", "\"Block missing\"", "unless", "block_given?", "@attempted_connect_at", "=", "Time", ".", "now", "@close_code", "=", "@close_reason", "=", "nil", "if", "(", "v", "=", "BalancedHttpClient", "::", "PROXY_ENVIRONMENT_VARIABLES", ".", "detect", "{", "|", "v", "|", "ENV", ".", "has_key?", "(", "v", ")", "}", ")", "proxy_uri", "=", "ENV", "[", "v", "]", ".", "match", "(", "/", "\\/", "\\/", "/", ")", "?", "URI", ".", "parse", "(", "ENV", "[", "v", "]", ")", ":", "URI", ".", "parse", "(", "\"http://\"", "+", "ENV", "[", "v", "]", ")", "@proxy", "=", "{", ":origin", "=>", "proxy_uri", ".", "to_s", "}", "end", "options", "=", "{", ":headers", "=>", "{", "\"X-API-Version\"", "=>", "API_VERSION", "}", ".", "merge", "(", "@auth_client", ".", "auth_header", ")", ",", ":ping", "=>", "@options", "[", ":listen_timeout", "]", "}", "options", "[", ":proxy", "]", "=", "@proxy", "if", "@proxy", "url", "=", "URI", ".", "parse", "(", "@auth_client", ".", "router_url", ")", "url", ".", "scheme", "=", "url", ".", "scheme", "==", "\"https\"", "?", "\"wss\"", ":", "\"ws\"", "url", ".", "path", "=", "url", ".", "path", "+", "\"/connect\"", "url", ".", "query", "=", "routing_keys", ".", "map", "{", "|", "k", "|", "\"routing_keys[]=#{CGI.escape(k)}\"", "}", ".", "join", "(", "\"&\"", ")", "if", "routing_keys", "&&", "routing_keys", ".", "any?", "Log", ".", "info", "(", "\"Creating WebSocket connection to #{url.to_s}\"", ")", "@websocket", "=", "Faye", "::", "WebSocket", "::", "Client", ".", "new", "(", "url", ".", "to_s", ",", "protocols", "=", "nil", ",", "options", ")", "@websocket", ".", "onerror", "=", "lambda", "do", "|", "event", "|", "error", "=", "if", "event", ".", "respond_to?", "(", ":data", ")", "event", ".", "data", "elsif", "event", ".", "respond_to?", "(", ":message", ")", "event", ".", "message", "else", "event", ".", "to_s", "end", "ErrorTracker", ".", "log", "(", "self", ",", "\"WebSocket error (#{error})\"", ")", "if", "error", "end", "@websocket", ".", "onclose", "=", "lambda", "do", "|", "event", "|", "begin", "@close_code", "=", "event", ".", "code", ".", "to_i", "@close_reason", "=", "event", ".", "reason", "msg", "=", "\"WebSocket closed (#{event.code}\"", "msg", "<<", "(", "(", "event", ".", "reason", ".", "nil?", "||", "event", ".", "reason", ".", "empty?", ")", "?", "\")\"", ":", "\": #{event.reason})\"", ")", "Log", ".", "info", "(", "msg", ")", "rescue", "Exception", "=>", "e", "ErrorTracker", ".", "log", "(", "self", ",", "\"Failed closing WebSocket\"", ",", "e", ")", "end", "@websocket", "=", "nil", "end", "@websocket", ".", "onmessage", "=", "lambda", "do", "|", "event", "|", "begin", "event", "=", "SerializationHelper", ".", "symbolize_keys", "(", "JSON", ".", "parser", ".", "new", "(", "event", ".", "data", ",", "JSON", ".", "load_default_options", ")", ".", "parse", ")", "Log", ".", "info", "(", "\"Received EVENT <#{event[:uuid]}> #{event[:type]} #{event[:path]} from #{event[:from]}\"", ")", "@stats", "[", "\"events\"", "]", ".", "update", "(", "\"#{event[:type]} #{event[:path]}\"", ")", "@websocket", ".", "send", "(", "JSON", ".", "dump", "(", "{", ":ack", "=>", "event", "[", ":uuid", "]", "}", ")", ")", "handler", ".", "call", "(", "event", ")", "@communicated_callbacks", ".", "each", "{", "|", "callback", "|", "callback", ".", "call", "}", "if", "@communicated_callbacks", "rescue", "Exception", "=>", "e", "ErrorTracker", ".", "log", "(", "self", ",", "\"Failed handling WebSocket event\"", ",", "e", ")", "end", "end", "@websocket", "end" ]
Connect to RightNet router using WebSocket for receiving events @param [Array, NilClass] routing_keys as strings to assist router in delivering event to interested parties @yield [event] required block called when event received @yieldparam [Object] event received @yieldreturn [Hash, NilClass] event this is response to event received, or nil meaning no response @return [Faye::WebSocket] WebSocket created @raise [ArgumentError] block missing
[ "Connect", "to", "RightNet", "router", "using", "WebSocket", "for", "receiving", "events" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/router_client.rb#L459-L530
train
rightscale/right_agent
lib/right_agent/clients/router_client.rb
RightScale.RouterClient.try_long_poll
def try_long_poll(routing_keys, event_uuids, &handler) begin long_poll(routing_keys, event_uuids, &handler) rescue Exception => e e end end
ruby
def try_long_poll(routing_keys, event_uuids, &handler) begin long_poll(routing_keys, event_uuids, &handler) rescue Exception => e e end end
[ "def", "try_long_poll", "(", "routing_keys", ",", "event_uuids", ",", "&", "handler", ")", "begin", "long_poll", "(", "routing_keys", ",", "event_uuids", ",", "&", "handler", ")", "rescue", "Exception", "=>", "e", "e", "end", "end" ]
Try to make long-polling request to receive events @param [Array, NilClass] routing_keys for event sources of interest with nil meaning all @param [Array, NilClass] event_uuids from previous poll @yield [event] required block called each time event received @yieldparam [Hash] event received @return [Array, NilClass, Exception] UUIDs of events received, or nil if none, or Exception if failed
[ "Try", "to", "make", "long", "-", "polling", "request", "to", "receive", "events" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/router_client.rb#L541-L547
train
rightscale/right_agent
lib/right_agent/clients/router_client.rb
RightScale.RouterClient.try_deferred_long_poll
def try_deferred_long_poll(routing_keys, event_uuids, &handler) # Proc for running long-poll in EM defer thread since this is a blocking call @defer_operation_proc = Proc.new { try_long_poll(routing_keys, event_uuids, &handler) } # Proc that runs in main EM reactor thread to handle result from above operation proc @defer_callback_proc = Proc.new { |result| @event_uuids = process_long_poll(result) } # Use EM defer thread since the long-poll will block EM.defer(@defer_operation_proc, @defer_callback_proc) true end
ruby
def try_deferred_long_poll(routing_keys, event_uuids, &handler) # Proc for running long-poll in EM defer thread since this is a blocking call @defer_operation_proc = Proc.new { try_long_poll(routing_keys, event_uuids, &handler) } # Proc that runs in main EM reactor thread to handle result from above operation proc @defer_callback_proc = Proc.new { |result| @event_uuids = process_long_poll(result) } # Use EM defer thread since the long-poll will block EM.defer(@defer_operation_proc, @defer_callback_proc) true end
[ "def", "try_deferred_long_poll", "(", "routing_keys", ",", "event_uuids", ",", "&", "handler", ")", "@defer_operation_proc", "=", "Proc", ".", "new", "{", "try_long_poll", "(", "routing_keys", ",", "event_uuids", ",", "&", "handler", ")", "}", "@defer_callback_proc", "=", "Proc", ".", "new", "{", "|", "result", "|", "@event_uuids", "=", "process_long_poll", "(", "result", ")", "}", "EM", ".", "defer", "(", "@defer_operation_proc", ",", "@defer_callback_proc", ")", "true", "end" ]
Try to make long-polling request to receive events using EM defer thread Repeat long-polling until there is an error or the stop time has been reached @param [Array, NilClass] routing_keys for event sources of interest with nil meaning all @param [Array, NilClass] event_uuids from previous poll @yield [event] required block called each time event received @yieldparam [Hash] event received @return [Array, NilClass] UUIDs of events received, or nil if none
[ "Try", "to", "make", "long", "-", "polling", "request", "to", "receive", "events", "using", "EM", "defer", "thread", "Repeat", "long", "-", "polling", "until", "there", "is", "an", "error", "or", "the", "stop", "time", "has", "been", "reached" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/router_client.rb#L559-L569
train