id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
700
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
701
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", "# 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" ]
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
702
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
703
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
704
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
705
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
706
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
707
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
708
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
709
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
710
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", "]", ")", "# 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" ]
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
711
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
712
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
713
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
714
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", "# 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" ]
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
715
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
716
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
717
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
718
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
719
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", "# 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" ]
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
720
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
721
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
722
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
723
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
724
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
725
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
726
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
727
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
728
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
729
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", "]", "}", "# 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" ]
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
730
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
731
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", "# 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" ]
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
732
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", ")", "# Hack to override RightScale namespace with Nanite for downward compatibility", "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
733
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
734
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
735
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
736
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
737
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
738
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
739
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
740
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", "# 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" ]
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
741
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
742
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
743
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
744
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", "# Initialize use of proxy if defined", "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", "=", "{", "# 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" ]
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
745
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
746
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", ")", "# 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" ]
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
747
rightscale/right_agent
lib/right_agent/clients/router_client.rb
RightScale.RouterClient.long_poll
def long_poll(routing_keys, ack, &handler) raise ArgumentError, "Block missing" unless block_given? params = { :wait_time => @options[:listen_timeout] - 5, :timestamp => Time.now.to_f } params[:routing_keys] = routing_keys if routing_keys params[:ack] = ack if ack && ack.any? options = { :request_timeout => @connect_interval, :poll_timeout => @options[:listen_timeout] } event_uuids = [] events = make_request(:poll, "/listen", params, "listen", options) if events events.each do |event| event = SerializationHelper.symbolize_keys(event) Log.info("Received EVENT <#{event[:uuid]}> #{event[:type]} #{event[:path]} from #{event[:from]}") @stats["events"].update("#{event[:type]} #{event[:path]}") event_uuids << event[:uuid] handler.call(event) end end event_uuids if event_uuids.any? end
ruby
def long_poll(routing_keys, ack, &handler) raise ArgumentError, "Block missing" unless block_given? params = { :wait_time => @options[:listen_timeout] - 5, :timestamp => Time.now.to_f } params[:routing_keys] = routing_keys if routing_keys params[:ack] = ack if ack && ack.any? options = { :request_timeout => @connect_interval, :poll_timeout => @options[:listen_timeout] } event_uuids = [] events = make_request(:poll, "/listen", params, "listen", options) if events events.each do |event| event = SerializationHelper.symbolize_keys(event) Log.info("Received EVENT <#{event[:uuid]}> #{event[:type]} #{event[:path]} from #{event[:from]}") @stats["events"].update("#{event[:type]} #{event[:path]}") event_uuids << event[:uuid] handler.call(event) end end event_uuids if event_uuids.any? end
[ "def", "long_poll", "(", "routing_keys", ",", "ack", ",", "&", "handler", ")", "raise", "ArgumentError", ",", "\"Block missing\"", "unless", "block_given?", "params", "=", "{", ":wait_time", "=>", "@options", "[", ":listen_timeout", "]", "-", "5", ",", ":timestamp", "=>", "Time", ".", "now", ".", "to_f", "}", "params", "[", ":routing_keys", "]", "=", "routing_keys", "if", "routing_keys", "params", "[", ":ack", "]", "=", "ack", "if", "ack", "&&", "ack", ".", "any?", "options", "=", "{", ":request_timeout", "=>", "@connect_interval", ",", ":poll_timeout", "=>", "@options", "[", ":listen_timeout", "]", "}", "event_uuids", "=", "[", "]", "events", "=", "make_request", "(", ":poll", ",", "\"/listen\"", ",", "params", ",", "\"listen\"", ",", "options", ")", "if", "events", "events", ".", "each", "do", "|", "event", "|", "event", "=", "SerializationHelper", ".", "symbolize_keys", "(", "event", ")", "Log", ".", "info", "(", "\"Received EVENT <#{event[:uuid]}> #{event[:type]} #{event[:path]} from #{event[:from]}\"", ")", "@stats", "[", "\"events\"", "]", ".", "update", "(", "\"#{event[:type]} #{event[:path]}\"", ")", "event_uuids", "<<", "event", "[", ":uuid", "]", "handler", ".", "call", "(", "event", ")", "end", "end", "event_uuids", "if", "event_uuids", ".", "any?", "end" ]
Make long-polling request to receive one or more events Do not return until an event is received or the polling times out or fails @param [Array, NilClass] routing_keys as strings to assist router in delivering event to interested parties @param [Array, NilClass] ack UUIDs for events received on previous poll @yield [event] required block called for each event received @yieldparam [Object] event received @return [Array, NilClass] UUIDs of events received, or nil if none @raise [ArgumentError] block missing
[ "Make", "long", "-", "polling", "request", "to", "receive", "one", "or", "more", "events", "Do", "not", "return", "until", "an", "event", "is", "received", "or", "the", "polling", "times", "out", "or", "fails" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/router_client.rb#L584-L609
748
rightscale/right_agent
lib/right_agent/clients/router_client.rb
RightScale.RouterClient.process_long_poll
def process_long_poll(result) case result when Exceptions::Unauthorized, Exceptions::ConnectivityFailure, Exceptions::RetryableError, Exceptions::InternalServerError # Reset connect_interval otherwise long-poll and WebSocket connect attempts will continue to backoff @connect_interval = CONNECT_INTERVAL update_listen_state(:choose, backoff_reconnect_interval) result = nil when Exception ErrorTracker.track(self, result) update_listen_state(:choose, backoff_reconnect_interval) result = nil else @reconnect_interval = RECONNECT_INTERVAL @communicated_callbacks.each { |callback| callback.call } if @communicated_callbacks update_listen_state(:choose) end result end
ruby
def process_long_poll(result) case result when Exceptions::Unauthorized, Exceptions::ConnectivityFailure, Exceptions::RetryableError, Exceptions::InternalServerError # Reset connect_interval otherwise long-poll and WebSocket connect attempts will continue to backoff @connect_interval = CONNECT_INTERVAL update_listen_state(:choose, backoff_reconnect_interval) result = nil when Exception ErrorTracker.track(self, result) update_listen_state(:choose, backoff_reconnect_interval) result = nil else @reconnect_interval = RECONNECT_INTERVAL @communicated_callbacks.each { |callback| callback.call } if @communicated_callbacks update_listen_state(:choose) end result end
[ "def", "process_long_poll", "(", "result", ")", "case", "result", "when", "Exceptions", "::", "Unauthorized", ",", "Exceptions", "::", "ConnectivityFailure", ",", "Exceptions", "::", "RetryableError", ",", "Exceptions", "::", "InternalServerError", "# Reset connect_interval otherwise long-poll and WebSocket connect attempts will continue to backoff", "@connect_interval", "=", "CONNECT_INTERVAL", "update_listen_state", "(", ":choose", ",", "backoff_reconnect_interval", ")", "result", "=", "nil", "when", "Exception", "ErrorTracker", ".", "track", "(", "self", ",", "result", ")", "update_listen_state", "(", ":choose", ",", "backoff_reconnect_interval", ")", "result", "=", "nil", "else", "@reconnect_interval", "=", "RECONNECT_INTERVAL", "@communicated_callbacks", ".", "each", "{", "|", "callback", "|", "callback", ".", "call", "}", "if", "@communicated_callbacks", "update_listen_state", "(", ":choose", ")", "end", "result", "end" ]
Process result from long-polling attempt Not necessary to log failure since should already have been done by underlying HTTP client @param [Array, NilClass] result from long-polling attempt @return [Array, NilClass] result for long-polling attempt
[ "Process", "result", "from", "long", "-", "polling", "attempt", "Not", "necessary", "to", "log", "failure", "since", "should", "already", "have", "been", "done", "by", "underlying", "HTTP", "client" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/router_client.rb#L617-L634
749
rightscale/right_agent
lib/right_agent/clients/base_retry_client.rb
RightScale.BaseRetryClient.init
def init(type, auth_client, options) raise ArgumentError, "Auth client does not support server type #{type.inspect}" unless auth_client.respond_to?(type.to_s + "_url") raise ArgumentError, ":api_version option missing" unless options[:api_version] @type = type @auth_client = auth_client @http_client = nil @status_callbacks = [] @options = options.dup @options[:server_name] ||= type.to_s @options[:open_timeout] ||= DEFAULT_OPEN_TIMEOUT @options[:request_timeout] ||= DEFAULT_REQUEST_TIMEOUT @options[:retry_timeout] ||= DEFAULT_RETRY_TIMEOUT @options[:retry_intervals] ||= DEFAULT_RETRY_INTERVALS @options[:reconnect_interval] ||= DEFAULT_RECONNECT_INTERVAL reset_stats @state = :pending create_http_client enable_use if check_health == :connected state == :connected end
ruby
def init(type, auth_client, options) raise ArgumentError, "Auth client does not support server type #{type.inspect}" unless auth_client.respond_to?(type.to_s + "_url") raise ArgumentError, ":api_version option missing" unless options[:api_version] @type = type @auth_client = auth_client @http_client = nil @status_callbacks = [] @options = options.dup @options[:server_name] ||= type.to_s @options[:open_timeout] ||= DEFAULT_OPEN_TIMEOUT @options[:request_timeout] ||= DEFAULT_REQUEST_TIMEOUT @options[:retry_timeout] ||= DEFAULT_RETRY_TIMEOUT @options[:retry_intervals] ||= DEFAULT_RETRY_INTERVALS @options[:reconnect_interval] ||= DEFAULT_RECONNECT_INTERVAL reset_stats @state = :pending create_http_client enable_use if check_health == :connected state == :connected end
[ "def", "init", "(", "type", ",", "auth_client", ",", "options", ")", "raise", "ArgumentError", ",", "\"Auth client does not support server type #{type.inspect}\"", "unless", "auth_client", ".", "respond_to?", "(", "type", ".", "to_s", "+", "\"_url\"", ")", "raise", "ArgumentError", ",", "\":api_version option missing\"", "unless", "options", "[", ":api_version", "]", "@type", "=", "type", "@auth_client", "=", "auth_client", "@http_client", "=", "nil", "@status_callbacks", "=", "[", "]", "@options", "=", "options", ".", "dup", "@options", "[", ":server_name", "]", "||=", "type", ".", "to_s", "@options", "[", ":open_timeout", "]", "||=", "DEFAULT_OPEN_TIMEOUT", "@options", "[", ":request_timeout", "]", "||=", "DEFAULT_REQUEST_TIMEOUT", "@options", "[", ":retry_timeout", "]", "||=", "DEFAULT_RETRY_TIMEOUT", "@options", "[", ":retry_intervals", "]", "||=", "DEFAULT_RETRY_INTERVALS", "@options", "[", ":reconnect_interval", "]", "||=", "DEFAULT_RECONNECT_INTERVAL", "reset_stats", "@state", "=", ":pending", "create_http_client", "enable_use", "if", "check_health", "==", ":connected", "state", "==", ":connected", "end" ]
Set configuration of this client and initialize HTTP access @param [Symbol] type of server for use in obtaining URL from auth_client, e.g., :router @param [AuthClient] auth_client providing authorization session for HTTP requests @option options [String] :server_name for use in reporting errors, e.g., RightNet @option options [String] :api_version of server for use in X-API-Version header @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] :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; can be augmented on individual requests @return [Boolean] whether currently connected @raise [ArgumentError] auth client does not support this client type @raise [ArgumentError] :api_version missing
[ "Set", "configuration", "of", "this", "client", "and", "initialize", "HTTP", "access" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/base_retry_client.rb#L86-L105
750
rightscale/right_agent
lib/right_agent/clients/base_retry_client.rb
RightScale.BaseRetryClient.create_http_client
def create_http_client close_http_client("reconnecting") url = @auth_client.send(@type.to_s + "_url") Log.info("Connecting to #{@options[:server_name]} via #{url.inspect}") options = {:server_name => @options[:server_name]} options[:api_version] = @options[:api_version] if @options[:api_version] options[:non_blocking] = @options[:non_blocking] if @options[:non_blocking] options[:filter_params] = @options[:filter_params] if @options[:filter_params] @http_client = RightScale::BalancedHttpClient.new(url, options) end
ruby
def create_http_client close_http_client("reconnecting") url = @auth_client.send(@type.to_s + "_url") Log.info("Connecting to #{@options[:server_name]} via #{url.inspect}") options = {:server_name => @options[:server_name]} options[:api_version] = @options[:api_version] if @options[:api_version] options[:non_blocking] = @options[:non_blocking] if @options[:non_blocking] options[:filter_params] = @options[:filter_params] if @options[:filter_params] @http_client = RightScale::BalancedHttpClient.new(url, options) end
[ "def", "create_http_client", "close_http_client", "(", "\"reconnecting\"", ")", "url", "=", "@auth_client", ".", "send", "(", "@type", ".", "to_s", "+", "\"_url\"", ")", "Log", ".", "info", "(", "\"Connecting to #{@options[:server_name]} via #{url.inspect}\"", ")", "options", "=", "{", ":server_name", "=>", "@options", "[", ":server_name", "]", "}", "options", "[", ":api_version", "]", "=", "@options", "[", ":api_version", "]", "if", "@options", "[", ":api_version", "]", "options", "[", ":non_blocking", "]", "=", "@options", "[", ":non_blocking", "]", "if", "@options", "[", ":non_blocking", "]", "options", "[", ":filter_params", "]", "=", "@options", "[", ":filter_params", "]", "if", "@options", "[", ":filter_params", "]", "@http_client", "=", "RightScale", "::", "BalancedHttpClient", ".", "new", "(", "url", ",", "options", ")", "end" ]
Create HTTP client If there is an existing client, close it first @return [TrueClass] always true @return [BalancedHttpClient] client
[ "Create", "HTTP", "client", "If", "there", "is", "an", "existing", "client", "close", "it", "first" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/base_retry_client.rb#L227-L236
751
rightscale/right_agent
lib/right_agent/clients/base_retry_client.rb
RightScale.BaseRetryClient.close_http_client
def close_http_client(reason) @http_client.close(reason) if @http_client true rescue StandardError => e ErrorTracker.log(self, "Failed closing connection", e) false end
ruby
def close_http_client(reason) @http_client.close(reason) if @http_client true rescue StandardError => e ErrorTracker.log(self, "Failed closing connection", e) false end
[ "def", "close_http_client", "(", "reason", ")", "@http_client", ".", "close", "(", "reason", ")", "if", "@http_client", "true", "rescue", "StandardError", "=>", "e", "ErrorTracker", ".", "log", "(", "self", ",", "\"Failed closing connection\"", ",", "e", ")", "false", "end" ]
Close HTTP client persistent connections @param [String] reason for closing @return [Boolean] false if failed, otherwise true
[ "Close", "HTTP", "client", "persistent", "connections" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/base_retry_client.rb#L243-L249
752
rightscale/right_agent
lib/right_agent/clients/base_retry_client.rb
RightScale.BaseRetryClient.check_health
def check_health begin @http_client.check_health self.state = :connected rescue BalancedHttpClient::NotResponding => e ErrorTracker.log(self, "Failed #{@options[:server_name]} health check", e.nested_exception) self.state = :disconnected rescue StandardError => e ErrorTracker.log(self, "Failed #{@options[:server_name]} health check", e, nil, :caller) self.state = :disconnected end end
ruby
def check_health begin @http_client.check_health self.state = :connected rescue BalancedHttpClient::NotResponding => e ErrorTracker.log(self, "Failed #{@options[:server_name]} health check", e.nested_exception) self.state = :disconnected rescue StandardError => e ErrorTracker.log(self, "Failed #{@options[:server_name]} health check", e, nil, :caller) self.state = :disconnected end end
[ "def", "check_health", "begin", "@http_client", ".", "check_health", "self", ".", "state", "=", ":connected", "rescue", "BalancedHttpClient", "::", "NotResponding", "=>", "e", "ErrorTracker", ".", "log", "(", "self", ",", "\"Failed #{@options[:server_name]} health check\"", ",", "e", ".", "nested_exception", ")", "self", ".", "state", "=", ":disconnected", "rescue", "StandardError", "=>", "e", "ErrorTracker", ".", "log", "(", "self", ",", "\"Failed #{@options[:server_name]} health check\"", ",", "e", ",", "nil", ",", ":caller", ")", "self", ".", "state", "=", ":disconnected", "end", "end" ]
Check health of RightApi directly without applying RequestBalancer Do not check whether HTTP client exists @return [Symbol] RightApi client state
[ "Check", "health", "of", "RightApi", "directly", "without", "applying", "RequestBalancer", "Do", "not", "check", "whether", "HTTP", "client", "exists" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/base_retry_client.rb#L263-L274
753
rightscale/right_agent
lib/right_agent/clients/base_retry_client.rb
RightScale.BaseRetryClient.reconnect
def reconnect unless @reconnecting @reconnecting = true if EM.reactor_running? @stats["reconnects"].update("initiate") @reconnect_timer = EM_S::PeriodicTimer.new(rand(@options[:reconnect_interval])) do begin reconnect_once rescue Exception => e ErrorTracker.log(self, "Failed #{@options[:server_name]} reconnect", e, nil, :caller) @stats["reconnects"].update("failure") self.state = :disconnected end @reconnect_timer.interval = @options[:reconnect_interval] if @reconnect_timer end else reconnect_once end end true end
ruby
def reconnect unless @reconnecting @reconnecting = true if EM.reactor_running? @stats["reconnects"].update("initiate") @reconnect_timer = EM_S::PeriodicTimer.new(rand(@options[:reconnect_interval])) do begin reconnect_once rescue Exception => e ErrorTracker.log(self, "Failed #{@options[:server_name]} reconnect", e, nil, :caller) @stats["reconnects"].update("failure") self.state = :disconnected end @reconnect_timer.interval = @options[:reconnect_interval] if @reconnect_timer end else reconnect_once end end true end
[ "def", "reconnect", "unless", "@reconnecting", "@reconnecting", "=", "true", "if", "EM", ".", "reactor_running?", "@stats", "[", "\"reconnects\"", "]", ".", "update", "(", "\"initiate\"", ")", "@reconnect_timer", "=", "EM_S", "::", "PeriodicTimer", ".", "new", "(", "rand", "(", "@options", "[", ":reconnect_interval", "]", ")", ")", "do", "begin", "reconnect_once", "rescue", "Exception", "=>", "e", "ErrorTracker", ".", "log", "(", "self", ",", "\"Failed #{@options[:server_name]} reconnect\"", ",", "e", ",", "nil", ",", ":caller", ")", "@stats", "[", "\"reconnects\"", "]", ".", "update", "(", "\"failure\"", ")", "self", ".", "state", "=", ":disconnected", "end", "@reconnect_timer", ".", "interval", "=", "@options", "[", ":reconnect_interval", "]", "if", "@reconnect_timer", "end", "else", "reconnect_once", "end", "end", "true", "end" ]
If EventMachine reactor is running, begin attempting to periodically reconnect with server by checking health. Randomize initial attempt to reduce server spiking. If EventMachine reactor is NOT running, attempt to reconnect once and raise any exception that is encountered. @return [TrueClass] always true
[ "If", "EventMachine", "reactor", "is", "running", "begin", "attempting", "to", "periodically", "reconnect", "with", "server", "by", "checking", "health", ".", "Randomize", "initial", "attempt", "to", "reduce", "server", "spiking", "." ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/base_retry_client.rb#L284-L306
754
rightscale/right_agent
lib/right_agent/clients/base_retry_client.rb
RightScale.BaseRetryClient.make_request
def make_request(verb, path, params = {}, type = nil, options = {}) raise Exceptions::Terminating if state == :closed started_at = Time.now time_to_live = (options[:time_to_live] && options[:time_to_live] > 0) ? options[:time_to_live] : nil expires_at = started_at + [time_to_live || @options[:retry_timeout], @options[:retry_timeout]].min headers = time_to_live ? @auth_client.headers.merge("X-Expires-At" => started_at + time_to_live) : @auth_client.headers request_uuid = options[:request_uuid] || RightSupport::Data::UUID.generate attempts = 0 result = nil @stats["requests sent"].measure(type || path, request_uuid) do begin attempts += 1 http_options = { :open_timeout => @options[:open_timeout], :request_timeout => @options[:request_timeout], :request_uuid => request_uuid, :headers => headers } reconnect_once if (:disconnected == state) && !EM.reactor_running? raise Exceptions::ConnectivityFailure, "#{@type} client not connected" unless [:connected, :closing].include?(state) result = @http_client.send(verb, path, params, http_options.merge(options)) rescue StandardError => e request_uuid = handle_exception(e, type || path, request_uuid, expires_at, attempts) request_uuid ? retry : raise end end @communicated_callbacks.each { |callback| callback.call } if @communicated_callbacks result end
ruby
def make_request(verb, path, params = {}, type = nil, options = {}) raise Exceptions::Terminating if state == :closed started_at = Time.now time_to_live = (options[:time_to_live] && options[:time_to_live] > 0) ? options[:time_to_live] : nil expires_at = started_at + [time_to_live || @options[:retry_timeout], @options[:retry_timeout]].min headers = time_to_live ? @auth_client.headers.merge("X-Expires-At" => started_at + time_to_live) : @auth_client.headers request_uuid = options[:request_uuid] || RightSupport::Data::UUID.generate attempts = 0 result = nil @stats["requests sent"].measure(type || path, request_uuid) do begin attempts += 1 http_options = { :open_timeout => @options[:open_timeout], :request_timeout => @options[:request_timeout], :request_uuid => request_uuid, :headers => headers } reconnect_once if (:disconnected == state) && !EM.reactor_running? raise Exceptions::ConnectivityFailure, "#{@type} client not connected" unless [:connected, :closing].include?(state) result = @http_client.send(verb, path, params, http_options.merge(options)) rescue StandardError => e request_uuid = handle_exception(e, type || path, request_uuid, expires_at, attempts) request_uuid ? retry : raise end end @communicated_callbacks.each { |callback| callback.call } if @communicated_callbacks result end
[ "def", "make_request", "(", "verb", ",", "path", ",", "params", "=", "{", "}", ",", "type", "=", "nil", ",", "options", "=", "{", "}", ")", "raise", "Exceptions", "::", "Terminating", "if", "state", "==", ":closed", "started_at", "=", "Time", ".", "now", "time_to_live", "=", "(", "options", "[", ":time_to_live", "]", "&&", "options", "[", ":time_to_live", "]", ">", "0", ")", "?", "options", "[", ":time_to_live", "]", ":", "nil", "expires_at", "=", "started_at", "+", "[", "time_to_live", "||", "@options", "[", ":retry_timeout", "]", ",", "@options", "[", ":retry_timeout", "]", "]", ".", "min", "headers", "=", "time_to_live", "?", "@auth_client", ".", "headers", ".", "merge", "(", "\"X-Expires-At\"", "=>", "started_at", "+", "time_to_live", ")", ":", "@auth_client", ".", "headers", "request_uuid", "=", "options", "[", ":request_uuid", "]", "||", "RightSupport", "::", "Data", "::", "UUID", ".", "generate", "attempts", "=", "0", "result", "=", "nil", "@stats", "[", "\"requests sent\"", "]", ".", "measure", "(", "type", "||", "path", ",", "request_uuid", ")", "do", "begin", "attempts", "+=", "1", "http_options", "=", "{", ":open_timeout", "=>", "@options", "[", ":open_timeout", "]", ",", ":request_timeout", "=>", "@options", "[", ":request_timeout", "]", ",", ":request_uuid", "=>", "request_uuid", ",", ":headers", "=>", "headers", "}", "reconnect_once", "if", "(", ":disconnected", "==", "state", ")", "&&", "!", "EM", ".", "reactor_running?", "raise", "Exceptions", "::", "ConnectivityFailure", ",", "\"#{@type} client not connected\"", "unless", "[", ":connected", ",", ":closing", "]", ".", "include?", "(", "state", ")", "result", "=", "@http_client", ".", "send", "(", "verb", ",", "path", ",", "params", ",", "http_options", ".", "merge", "(", "options", ")", ")", "rescue", "StandardError", "=>", "e", "request_uuid", "=", "handle_exception", "(", "e", ",", "type", "||", "path", ",", "request_uuid", ",", "expires_at", ",", "attempts", ")", "request_uuid", "?", "retry", ":", "raise", "end", "end", "@communicated_callbacks", ".", "each", "{", "|", "callback", "|", "callback", ".", "call", "}", "if", "@communicated_callbacks", "result", "end" ]
Make request via HTTP. Attempt to reconnect first if disconnected and EM reactor is not running. Rely on underlying HTTP client to log request and response. Retry request if response indicates to or if there are connectivity failures. There are also several timeouts involved: - Underlying BalancedHttpClient connection open timeout (:open_timeout) - Underlying BalancedHttpClient request timeout (:request_timeout) - Retry timeout for this method and its handlers (:retry_timeout) - Seconds before request expires and is to be ignored (:time_to_live) and if the target server is a RightNet router: - Router response timeout (ideally > :retry_timeout and < :request_timeout) - Router retry timeout (ideally = :retry_timeout) There are several possible levels of retry involved, starting with the outermost: - This method will retry if the targeted server is not responding or if it receives a retry response, but the total elapsed time is not allowed to exceed :request_timeout - RequestBalancer in BalancedHttpClient will retry using other endpoints if it gets an error that it considers retryable, and even if a front-end balancer is in use there will likely be at least two such endpoints for redundancy and if the target server is a RightNet router: - The router when sending a request via AMQP will retry if it receives no response, but not exceeding its configured :retry_timeout; if the router's timeouts for retry are consistent with the ones prescribed above, there will be no retry by the RequestBalancer after router retries @param [Symbol] verb for HTTP REST request @param [String] path in URI for desired resource @param [Hash] params for HTTP request @param [String] type of request for use in logging; defaults to path @param [String, NilClass] request_uuid uniquely identifying this request; defaults to randomly generated UUID @param [Numeric, NilClass] time_to_live seconds before request expires and is to be ignored; non-positive value or nil means never expire; defaults to nil @param [Hash] options augmenting or overriding default options for HTTP request @return [Object, NilClass] result of request with nil meaning no result @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
[ "Make", "request", "via", "HTTP", ".", "Attempt", "to", "reconnect", "first", "if", "disconnected", "and", "EM", "reactor", "is", "not", "running", ".", "Rely", "on", "underlying", "HTTP", "client", "to", "log", "request", "and", "response", ".", "Retry", "request", "if", "response", "indicates", "to", "or", "if", "there", "are", "connectivity", "failures", "." ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/base_retry_client.rb#L367-L394
755
rightscale/right_agent
lib/right_agent/clients/base_retry_client.rb
RightScale.BaseRetryClient.handle_exception
def handle_exception(exception, type, request_uuid, expires_at, attempts) result = request_uuid if exception.respond_to?(:http_code) case exception.http_code when 301, 302 # MovedPermanently, Found handle_redirect(exception, type, request_uuid) when 401 # Unauthorized raise Exceptions::Unauthorized.new(exception.http_body, exception) when 403 # Forbidden @auth_client.expired raise Exceptions::RetryableError.new("Authorization expired", exception) when 449 # RetryWith result = handle_retry_with(exception, type, request_uuid, expires_at, attempts) when 500 # InternalServerError raise Exceptions::InternalServerError.new(exception.http_body, @options[:server_name]) else @stats["request failures"].update("#{type} - #{exception.http_code}") result = nil end elsif exception.is_a?(BalancedHttpClient::NotResponding) handle_not_responding(exception, type, request_uuid, expires_at, attempts) else @stats["request failures"].update("#{type} - #{exception.class.name}") result = nil end result end
ruby
def handle_exception(exception, type, request_uuid, expires_at, attempts) result = request_uuid if exception.respond_to?(:http_code) case exception.http_code when 301, 302 # MovedPermanently, Found handle_redirect(exception, type, request_uuid) when 401 # Unauthorized raise Exceptions::Unauthorized.new(exception.http_body, exception) when 403 # Forbidden @auth_client.expired raise Exceptions::RetryableError.new("Authorization expired", exception) when 449 # RetryWith result = handle_retry_with(exception, type, request_uuid, expires_at, attempts) when 500 # InternalServerError raise Exceptions::InternalServerError.new(exception.http_body, @options[:server_name]) else @stats["request failures"].update("#{type} - #{exception.http_code}") result = nil end elsif exception.is_a?(BalancedHttpClient::NotResponding) handle_not_responding(exception, type, request_uuid, expires_at, attempts) else @stats["request failures"].update("#{type} - #{exception.class.name}") result = nil end result end
[ "def", "handle_exception", "(", "exception", ",", "type", ",", "request_uuid", ",", "expires_at", ",", "attempts", ")", "result", "=", "request_uuid", "if", "exception", ".", "respond_to?", "(", ":http_code", ")", "case", "exception", ".", "http_code", "when", "301", ",", "302", "# MovedPermanently, Found", "handle_redirect", "(", "exception", ",", "type", ",", "request_uuid", ")", "when", "401", "# Unauthorized", "raise", "Exceptions", "::", "Unauthorized", ".", "new", "(", "exception", ".", "http_body", ",", "exception", ")", "when", "403", "# Forbidden", "@auth_client", ".", "expired", "raise", "Exceptions", "::", "RetryableError", ".", "new", "(", "\"Authorization expired\"", ",", "exception", ")", "when", "449", "# RetryWith", "result", "=", "handle_retry_with", "(", "exception", ",", "type", ",", "request_uuid", ",", "expires_at", ",", "attempts", ")", "when", "500", "# InternalServerError", "raise", "Exceptions", "::", "InternalServerError", ".", "new", "(", "exception", ".", "http_body", ",", "@options", "[", ":server_name", "]", ")", "else", "@stats", "[", "\"request failures\"", "]", ".", "update", "(", "\"#{type} - #{exception.http_code}\"", ")", "result", "=", "nil", "end", "elsif", "exception", ".", "is_a?", "(", "BalancedHttpClient", "::", "NotResponding", ")", "handle_not_responding", "(", "exception", ",", "type", ",", "request_uuid", ",", "expires_at", ",", "attempts", ")", "else", "@stats", "[", "\"request failures\"", "]", ".", "update", "(", "\"#{type} - #{exception.class.name}\"", ")", "result", "=", "nil", "end", "result", "end" ]
Examine exception to determine whether to setup retry, raise new exception, or re-raise @param [StandardError] exception raised @param [String] action from request type @param [String] type of request for use in logging @param [String] request_uuid originally created for this request @param [Time] expires_at time for request @param [Integer] attempts to make request @return [String, NilClass] request UUID to be used on retry or nil if to raise instead @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::InternalServerError] internal error in server being accessed
[ "Examine", "exception", "to", "determine", "whether", "to", "setup", "retry", "raise", "new", "exception", "or", "re", "-", "raise" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/base_retry_client.rb#L412-L438
756
rightscale/right_agent
lib/right_agent/clients/base_retry_client.rb
RightScale.BaseRetryClient.handle_redirect
def handle_redirect(redirect, type, request_uuid) Log.info("Received REDIRECT #{redirect} for #{type} request <#{request_uuid}>") if redirect.respond_to?(:response) && (location = redirect.response.headers[:location]) && !location.empty? Log.info("Requesting auth client to handle redirect to #{location.inspect}") @stats["reconnects"].update("redirect") @auth_client.redirect(location) raise Exceptions::RetryableError.new(redirect.http_body, redirect) else raise Exceptions::InternalServerError.new("No redirect location provided", @options[:server_name]) end true end
ruby
def handle_redirect(redirect, type, request_uuid) Log.info("Received REDIRECT #{redirect} for #{type} request <#{request_uuid}>") if redirect.respond_to?(:response) && (location = redirect.response.headers[:location]) && !location.empty? Log.info("Requesting auth client to handle redirect to #{location.inspect}") @stats["reconnects"].update("redirect") @auth_client.redirect(location) raise Exceptions::RetryableError.new(redirect.http_body, redirect) else raise Exceptions::InternalServerError.new("No redirect location provided", @options[:server_name]) end true end
[ "def", "handle_redirect", "(", "redirect", ",", "type", ",", "request_uuid", ")", "Log", ".", "info", "(", "\"Received REDIRECT #{redirect} for #{type} request <#{request_uuid}>\"", ")", "if", "redirect", ".", "respond_to?", "(", ":response", ")", "&&", "(", "location", "=", "redirect", ".", "response", ".", "headers", "[", ":location", "]", ")", "&&", "!", "location", ".", "empty?", "Log", ".", "info", "(", "\"Requesting auth client to handle redirect to #{location.inspect}\"", ")", "@stats", "[", "\"reconnects\"", "]", ".", "update", "(", "\"redirect\"", ")", "@auth_client", ".", "redirect", "(", "location", ")", "raise", "Exceptions", "::", "RetryableError", ".", "new", "(", "redirect", ".", "http_body", ",", "redirect", ")", "else", "raise", "Exceptions", "::", "InternalServerError", ".", "new", "(", "\"No redirect location provided\"", ",", "@options", "[", ":server_name", "]", ")", "end", "true", "end" ]
Treat redirect response as indication that no longer accessing the correct shard Handle it by informing auth client so that it can re-authorize Do not retry, but tell client to with the expectation that re-auth will correct the situation @param [RestClient::MovedPermanently, RestClient::Found] redirect exception raised @param [String] type of request for use in logging @param [String] request_uuid originally created for this request @return [TrueClass] never returns @raise [Exceptions::RetryableError] request redirected but if retried may succeed @raise [Exceptions::InternalServerError] no redirect location provided
[ "Treat", "redirect", "response", "as", "indication", "that", "no", "longer", "accessing", "the", "correct", "shard", "Handle", "it", "by", "informing", "auth", "client", "so", "that", "it", "can", "re", "-", "authorize", "Do", "not", "retry", "but", "tell", "client", "to", "with", "the", "expectation", "that", "re", "-", "auth", "will", "correct", "the", "situation" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/base_retry_client.rb#L452-L463
757
rightscale/right_agent
lib/right_agent/clients/base_retry_client.rb
RightScale.BaseRetryClient.handle_retry_with
def handle_retry_with(retry_result, type, request_uuid, expires_at, attempts) case (interval = retry_interval(expires_at, attempts, 1)) when nil @stats["request failures"].update("#{type} - retry") raise Exceptions::RetryableError.new(retry_result.http_body, retry_result) when 0 @stats["request failures"].update("#{type} - retry") raise Exceptions::RetryableError.new(retry_result.http_body, retry_result) else ErrorTracker.log(self, "Retrying #{type} request <#{request_uuid}> in #{interval} seconds " + "in response to retryable error (#{retry_result.http_body})") wait(interval) end # Change request_uuid so that retried request not rejected as duplicate "#{request_uuid}:retry" end
ruby
def handle_retry_with(retry_result, type, request_uuid, expires_at, attempts) case (interval = retry_interval(expires_at, attempts, 1)) when nil @stats["request failures"].update("#{type} - retry") raise Exceptions::RetryableError.new(retry_result.http_body, retry_result) when 0 @stats["request failures"].update("#{type} - retry") raise Exceptions::RetryableError.new(retry_result.http_body, retry_result) else ErrorTracker.log(self, "Retrying #{type} request <#{request_uuid}> in #{interval} seconds " + "in response to retryable error (#{retry_result.http_body})") wait(interval) end # Change request_uuid so that retried request not rejected as duplicate "#{request_uuid}:retry" end
[ "def", "handle_retry_with", "(", "retry_result", ",", "type", ",", "request_uuid", ",", "expires_at", ",", "attempts", ")", "case", "(", "interval", "=", "retry_interval", "(", "expires_at", ",", "attempts", ",", "1", ")", ")", "when", "nil", "@stats", "[", "\"request failures\"", "]", ".", "update", "(", "\"#{type} - retry\"", ")", "raise", "Exceptions", "::", "RetryableError", ".", "new", "(", "retry_result", ".", "http_body", ",", "retry_result", ")", "when", "0", "@stats", "[", "\"request failures\"", "]", ".", "update", "(", "\"#{type} - retry\"", ")", "raise", "Exceptions", "::", "RetryableError", ".", "new", "(", "retry_result", ".", "http_body", ",", "retry_result", ")", "else", "ErrorTracker", ".", "log", "(", "self", ",", "\"Retrying #{type} request <#{request_uuid}> in #{interval} seconds \"", "+", "\"in response to retryable error (#{retry_result.http_body})\"", ")", "wait", "(", "interval", ")", "end", "# Change request_uuid so that retried request not rejected as duplicate", "\"#{request_uuid}:retry\"", "end" ]
Handle retry response by retrying it only once This indicates the request was received but a retryable error prevented it from being processed; the retry responsibility may be passed on If retrying, this function does not return until it is time to retry @param [RestClient::RetryWith] retry_result exception raised @param [String] type of request for use in logging @param [String] request_uuid originally created for this request @param [Time] expires_at time for request @param [Integer] attempts to make request @return [String] request UUID to be used on retry @raise [Exceptions::RetryableError] request failed but if retried may succeed
[ "Handle", "retry", "response", "by", "retrying", "it", "only", "once", "This", "indicates", "the", "request", "was", "received", "but", "a", "retryable", "error", "prevented", "it", "from", "being", "processed", ";", "the", "retry", "responsibility", "may", "be", "passed", "on", "If", "retrying", "this", "function", "does", "not", "return", "until", "it", "is", "time", "to", "retry" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/base_retry_client.rb#L479-L494
758
rightscale/right_agent
lib/right_agent/clients/base_retry_client.rb
RightScale.BaseRetryClient.handle_not_responding
def handle_not_responding(not_responding, type, request_uuid, expires_at, attempts) case (interval = retry_interval(expires_at, attempts)) when nil @stats["request failures"].update("#{type} - no result") self.state = :disconnected raise Exceptions::ConnectivityFailure.new(not_responding.message) when 0 @stats["request failures"].update("#{type} - no result") self.state = :disconnected raise Exceptions::ConnectivityFailure.new(not_responding.message + " after #{attempts} attempts") else ErrorTracker.log(self, "Retrying #{type} request <#{request_uuid}> in #{interval} seconds " + "in response to routing failure (#{BalancedHttpClient.exception_text(not_responding)})") wait(interval) end true end
ruby
def handle_not_responding(not_responding, type, request_uuid, expires_at, attempts) case (interval = retry_interval(expires_at, attempts)) when nil @stats["request failures"].update("#{type} - no result") self.state = :disconnected raise Exceptions::ConnectivityFailure.new(not_responding.message) when 0 @stats["request failures"].update("#{type} - no result") self.state = :disconnected raise Exceptions::ConnectivityFailure.new(not_responding.message + " after #{attempts} attempts") else ErrorTracker.log(self, "Retrying #{type} request <#{request_uuid}> in #{interval} seconds " + "in response to routing failure (#{BalancedHttpClient.exception_text(not_responding)})") wait(interval) end true end
[ "def", "handle_not_responding", "(", "not_responding", ",", "type", ",", "request_uuid", ",", "expires_at", ",", "attempts", ")", "case", "(", "interval", "=", "retry_interval", "(", "expires_at", ",", "attempts", ")", ")", "when", "nil", "@stats", "[", "\"request failures\"", "]", ".", "update", "(", "\"#{type} - no result\"", ")", "self", ".", "state", "=", ":disconnected", "raise", "Exceptions", "::", "ConnectivityFailure", ".", "new", "(", "not_responding", ".", "message", ")", "when", "0", "@stats", "[", "\"request failures\"", "]", ".", "update", "(", "\"#{type} - no result\"", ")", "self", ".", "state", "=", ":disconnected", "raise", "Exceptions", "::", "ConnectivityFailure", ".", "new", "(", "not_responding", ".", "message", "+", "\" after #{attempts} attempts\"", ")", "else", "ErrorTracker", ".", "log", "(", "self", ",", "\"Retrying #{type} request <#{request_uuid}> in #{interval} seconds \"", "+", "\"in response to routing failure (#{BalancedHttpClient.exception_text(not_responding)})\"", ")", "wait", "(", "interval", ")", "end", "true", "end" ]
Handle not responding response by determining whether okay to retry If request is being retried, this function does not return until it is time to retry @param [BalancedHttpClient::NotResponding] not_responding exception indicating targeted server is too busy or out of service @param [String] type of request for use in logging @param [String] request_uuid originally created for this request @param [Time] expires_at time for request @param [Integer] attempts to make request @return [TrueClass] always true @raise [Exceptions::ConnectivityFailure] cannot connect to server, lost connection to it, or it is out of service or too busy to respond
[ "Handle", "not", "responding", "response", "by", "determining", "whether", "okay", "to", "retry", "If", "request", "is", "being", "retried", "this", "function", "does", "not", "return", "until", "it", "is", "time", "to", "retry" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/base_retry_client.rb#L510-L526
759
rightscale/right_agent
lib/right_agent/clients/base_retry_client.rb
RightScale.BaseRetryClient.retry_interval
def retry_interval(expires_at, attempts, max_retries = nil) if @options[:retry_enabled] if max_retries.nil? || attempts <= max_retries interval = @options[:retry_intervals][attempts - 1] || @options[:retry_intervals][-1] ((Time.now + interval) < expires_at) ? interval : 0 else 0 end end end
ruby
def retry_interval(expires_at, attempts, max_retries = nil) if @options[:retry_enabled] if max_retries.nil? || attempts <= max_retries interval = @options[:retry_intervals][attempts - 1] || @options[:retry_intervals][-1] ((Time.now + interval) < expires_at) ? interval : 0 else 0 end end end
[ "def", "retry_interval", "(", "expires_at", ",", "attempts", ",", "max_retries", "=", "nil", ")", "if", "@options", "[", ":retry_enabled", "]", "if", "max_retries", ".", "nil?", "||", "attempts", "<=", "max_retries", "interval", "=", "@options", "[", ":retry_intervals", "]", "[", "attempts", "-", "1", "]", "||", "@options", "[", ":retry_intervals", "]", "[", "-", "1", "]", "(", "(", "Time", ".", "now", "+", "interval", ")", "<", "expires_at", ")", "?", "interval", ":", "0", "else", "0", "end", "end", "end" ]
Determine time interval before next retry @param [Time] expires_at time for request @param [Integer] attempts so far @param [Integer] max_retries @return [Integer, NilClass] retry interval with 0 meaning no try and nil meaning retry disabled
[ "Determine", "time", "interval", "before", "next", "retry" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/base_retry_client.rb#L535-L544
760
rightscale/right_agent
lib/right_agent/clients/base_retry_client.rb
RightScale.BaseRetryClient.wait
def wait(interval) if @options[:non_blocking] fiber = Fiber.current EM.add_timer(interval) { fiber.resume } Fiber.yield else sleep(interval) end true end
ruby
def wait(interval) if @options[:non_blocking] fiber = Fiber.current EM.add_timer(interval) { fiber.resume } Fiber.yield else sleep(interval) end true end
[ "def", "wait", "(", "interval", ")", "if", "@options", "[", ":non_blocking", "]", "fiber", "=", "Fiber", ".", "current", "EM", ".", "add_timer", "(", "interval", ")", "{", "fiber", ".", "resume", "}", "Fiber", ".", "yield", "else", "sleep", "(", "interval", ")", "end", "true", "end" ]
Wait the specified interval in non-blocking fashion if possible @param [Numeric] interval to wait @return [TrueClass] always true
[ "Wait", "the", "specified", "interval", "in", "non", "-", "blocking", "fashion", "if", "possible" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/base_retry_client.rb#L551-L560
761
rightscale/right_agent
lib/right_agent/retryable_request.rb
RightScale.RetryableRequest.handle_response
def handle_response(r) return true if @done @raw_response = r res = result_from(r) if res.success? if @cancel_timer @cancel_timer.cancel @cancel_timer = nil end @done = true succeed(res.content) else reason = res.content if res.non_delivery? Log.info("Request non-delivery (#{reason}) for #{@operation}") elsif res.retry? reason = (reason && !reason.empty?) ? reason : "RightScale not ready" Log.info("Request #{@operation} failed (#{reason}) and should be retried") elsif res.cancel? reason = (reason && !reason.empty?) ? reason : "RightScale cannot execute request" Log.info("Request #{@operation} canceled (#{reason})") else Log.info("Request #{@operation} failed (#{reason})") end if (res.non_delivery? || res.retry? || @retry_on_error) && !res.cancel? Log.info("Retrying in #{@retry_delay} seconds...") if @retry_delay > 0 this_delay = @retry_delay if (@retries += 1) >= @retry_delay_count @retry_delay = [@retry_delay * RETRY_BACKOFF_FACTOR, @max_retry_delay].min @retry_delay_count = [@retry_delay_count / RETRY_BACKOFF_FACTOR, 1].max @retries = 0 end EM.add_timer(this_delay) { run } else EM.next_tick { run } end else cancel(res.content) end end true end
ruby
def handle_response(r) return true if @done @raw_response = r res = result_from(r) if res.success? if @cancel_timer @cancel_timer.cancel @cancel_timer = nil end @done = true succeed(res.content) else reason = res.content if res.non_delivery? Log.info("Request non-delivery (#{reason}) for #{@operation}") elsif res.retry? reason = (reason && !reason.empty?) ? reason : "RightScale not ready" Log.info("Request #{@operation} failed (#{reason}) and should be retried") elsif res.cancel? reason = (reason && !reason.empty?) ? reason : "RightScale cannot execute request" Log.info("Request #{@operation} canceled (#{reason})") else Log.info("Request #{@operation} failed (#{reason})") end if (res.non_delivery? || res.retry? || @retry_on_error) && !res.cancel? Log.info("Retrying in #{@retry_delay} seconds...") if @retry_delay > 0 this_delay = @retry_delay if (@retries += 1) >= @retry_delay_count @retry_delay = [@retry_delay * RETRY_BACKOFF_FACTOR, @max_retry_delay].min @retry_delay_count = [@retry_delay_count / RETRY_BACKOFF_FACTOR, 1].max @retries = 0 end EM.add_timer(this_delay) { run } else EM.next_tick { run } end else cancel(res.content) end end true end
[ "def", "handle_response", "(", "r", ")", "return", "true", "if", "@done", "@raw_response", "=", "r", "res", "=", "result_from", "(", "r", ")", "if", "res", ".", "success?", "if", "@cancel_timer", "@cancel_timer", ".", "cancel", "@cancel_timer", "=", "nil", "end", "@done", "=", "true", "succeed", "(", "res", ".", "content", ")", "else", "reason", "=", "res", ".", "content", "if", "res", ".", "non_delivery?", "Log", ".", "info", "(", "\"Request non-delivery (#{reason}) for #{@operation}\"", ")", "elsif", "res", ".", "retry?", "reason", "=", "(", "reason", "&&", "!", "reason", ".", "empty?", ")", "?", "reason", ":", "\"RightScale not ready\"", "Log", ".", "info", "(", "\"Request #{@operation} failed (#{reason}) and should be retried\"", ")", "elsif", "res", ".", "cancel?", "reason", "=", "(", "reason", "&&", "!", "reason", ".", "empty?", ")", "?", "reason", ":", "\"RightScale cannot execute request\"", "Log", ".", "info", "(", "\"Request #{@operation} canceled (#{reason})\"", ")", "else", "Log", ".", "info", "(", "\"Request #{@operation} failed (#{reason})\"", ")", "end", "if", "(", "res", ".", "non_delivery?", "||", "res", ".", "retry?", "||", "@retry_on_error", ")", "&&", "!", "res", ".", "cancel?", "Log", ".", "info", "(", "\"Retrying in #{@retry_delay} seconds...\"", ")", "if", "@retry_delay", ">", "0", "this_delay", "=", "@retry_delay", "if", "(", "@retries", "+=", "1", ")", ">=", "@retry_delay_count", "@retry_delay", "=", "[", "@retry_delay", "*", "RETRY_BACKOFF_FACTOR", ",", "@max_retry_delay", "]", ".", "min", "@retry_delay_count", "=", "[", "@retry_delay_count", "/", "RETRY_BACKOFF_FACTOR", ",", "1", "]", ".", "max", "@retries", "=", "0", "end", "EM", ".", "add_timer", "(", "this_delay", ")", "{", "run", "}", "else", "EM", ".", "next_tick", "{", "run", "}", "end", "else", "cancel", "(", "res", ".", "content", ")", "end", "end", "true", "end" ]
Process request response and retry if needed === Parameters r(Result):: Request result === Return true:: Always return true
[ "Process", "request", "response", "and", "retry", "if", "needed" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/retryable_request.rb#L151-L193
762
rightscale/right_agent
lib/right_agent/serialize/secure_serializer.rb
RightScale.SecureSerializer.dump
def dump(obj, encrypt = nil) must_encrypt = encrypt || @encrypt serialize_format = if obj.respond_to?(:send_version) && can_handle_msgpack_result?(obj.send_version) @serializer.format else :json end encode_format = serialize_format == :json ? :pem : :der msg = @serializer.dump(obj, serialize_format) if must_encrypt certs = @store.get_target(obj) if certs msg = EncryptedDocument.new(msg, certs).encrypted_data(encode_format) else target = obj.target_for_encryption if obj.respond_to?(:target_for_encryption) ErrorTracker.log(self, "No certs available for object #{obj.class} being sent to #{target.inspect}") if target end end sig = Signature.new(msg, @cert, @key).data(encode_format) @serializer.dump({'id' => @identity, 'data' => msg, 'signature' => sig, 'encrypted' => !certs.nil?}, serialize_format) end
ruby
def dump(obj, encrypt = nil) must_encrypt = encrypt || @encrypt serialize_format = if obj.respond_to?(:send_version) && can_handle_msgpack_result?(obj.send_version) @serializer.format else :json end encode_format = serialize_format == :json ? :pem : :der msg = @serializer.dump(obj, serialize_format) if must_encrypt certs = @store.get_target(obj) if certs msg = EncryptedDocument.new(msg, certs).encrypted_data(encode_format) else target = obj.target_for_encryption if obj.respond_to?(:target_for_encryption) ErrorTracker.log(self, "No certs available for object #{obj.class} being sent to #{target.inspect}") if target end end sig = Signature.new(msg, @cert, @key).data(encode_format) @serializer.dump({'id' => @identity, 'data' => msg, 'signature' => sig, 'encrypted' => !certs.nil?}, serialize_format) end
[ "def", "dump", "(", "obj", ",", "encrypt", "=", "nil", ")", "must_encrypt", "=", "encrypt", "||", "@encrypt", "serialize_format", "=", "if", "obj", ".", "respond_to?", "(", ":send_version", ")", "&&", "can_handle_msgpack_result?", "(", "obj", ".", "send_version", ")", "@serializer", ".", "format", "else", ":json", "end", "encode_format", "=", "serialize_format", "==", ":json", "?", ":pem", ":", ":der", "msg", "=", "@serializer", ".", "dump", "(", "obj", ",", "serialize_format", ")", "if", "must_encrypt", "certs", "=", "@store", ".", "get_target", "(", "obj", ")", "if", "certs", "msg", "=", "EncryptedDocument", ".", "new", "(", "msg", ",", "certs", ")", ".", "encrypted_data", "(", "encode_format", ")", "else", "target", "=", "obj", ".", "target_for_encryption", "if", "obj", ".", "respond_to?", "(", ":target_for_encryption", ")", "ErrorTracker", ".", "log", "(", "self", ",", "\"No certs available for object #{obj.class} being sent to #{target.inspect}\"", ")", "if", "target", "end", "end", "sig", "=", "Signature", ".", "new", "(", "msg", ",", "@cert", ",", "@key", ")", ".", "data", "(", "encode_format", ")", "@serializer", ".", "dump", "(", "{", "'id'", "=>", "@identity", ",", "'data'", "=>", "msg", ",", "'signature'", "=>", "sig", ",", "'encrypted'", "=>", "!", "certs", ".", "nil?", "}", ",", "serialize_format", ")", "end" ]
Initialize serializer, must be called prior to using it === Parameters serializer(Serializer):: Object serializer identity(String):: Serialized identity associated with serialized messages store(Object):: Credentials store exposing certificates used for encryption (:get_target), signature validation (:get_signer), and certificate(s)/key(s) used for decryption (:get_receiver) encrypt(Boolean):: true if data should be signed and encrypted, otherwise just signed, true by default Serialize, sign, and encrypt message Sign and encrypt using X.509 certificate === Parameters obj(Object):: Object to be serialized and encrypted encrypt(Boolean|nil):: true if object should be signed and encrypted, false if just signed, nil means use class setting === Return (String):: MessagePack serialized and optionally encrypted object
[ "Initialize", "serializer", "must", "be", "called", "prior", "to", "using", "it" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/serialize/secure_serializer.rb#L90-L110
763
rightscale/right_agent
lib/right_agent/serialize/secure_serializer.rb
RightScale.SecureSerializer.load
def load(msg, id = nil) msg = @serializer.load(msg) sig = Signature.from_data(msg['signature']) certs = @store.get_signer(msg['id']) raise MissingCertificate.new("Could not find a certificate for signer #{msg['id']}") unless certs certs = [ certs ] unless certs.respond_to?(:any?) raise InvalidSignature.new("Failed signature check for signer #{msg['id']}") unless certs.any? { |c| sig.match?(c) } data = msg['data'] if data && msg['encrypted'] cert, key = @store.get_receiver(id) raise MissingCertificate.new("Could not find a certificate for #{id.inspect}") unless cert raise MissingPrivateKey.new("Could not find a private key for #{id.inspect}") unless key data = EncryptedDocument.from_data(data).decrypted_data(key, cert) end @serializer.load(data) if data end
ruby
def load(msg, id = nil) msg = @serializer.load(msg) sig = Signature.from_data(msg['signature']) certs = @store.get_signer(msg['id']) raise MissingCertificate.new("Could not find a certificate for signer #{msg['id']}") unless certs certs = [ certs ] unless certs.respond_to?(:any?) raise InvalidSignature.new("Failed signature check for signer #{msg['id']}") unless certs.any? { |c| sig.match?(c) } data = msg['data'] if data && msg['encrypted'] cert, key = @store.get_receiver(id) raise MissingCertificate.new("Could not find a certificate for #{id.inspect}") unless cert raise MissingPrivateKey.new("Could not find a private key for #{id.inspect}") unless key data = EncryptedDocument.from_data(data).decrypted_data(key, cert) end @serializer.load(data) if data end
[ "def", "load", "(", "msg", ",", "id", "=", "nil", ")", "msg", "=", "@serializer", ".", "load", "(", "msg", ")", "sig", "=", "Signature", ".", "from_data", "(", "msg", "[", "'signature'", "]", ")", "certs", "=", "@store", ".", "get_signer", "(", "msg", "[", "'id'", "]", ")", "raise", "MissingCertificate", ".", "new", "(", "\"Could not find a certificate for signer #{msg['id']}\"", ")", "unless", "certs", "certs", "=", "[", "certs", "]", "unless", "certs", ".", "respond_to?", "(", ":any?", ")", "raise", "InvalidSignature", ".", "new", "(", "\"Failed signature check for signer #{msg['id']}\"", ")", "unless", "certs", ".", "any?", "{", "|", "c", "|", "sig", ".", "match?", "(", "c", ")", "}", "data", "=", "msg", "[", "'data'", "]", "if", "data", "&&", "msg", "[", "'encrypted'", "]", "cert", ",", "key", "=", "@store", ".", "get_receiver", "(", "id", ")", "raise", "MissingCertificate", ".", "new", "(", "\"Could not find a certificate for #{id.inspect}\"", ")", "unless", "cert", "raise", "MissingPrivateKey", ".", "new", "(", "\"Could not find a private key for #{id.inspect}\"", ")", "unless", "key", "data", "=", "EncryptedDocument", ".", "from_data", "(", "data", ")", ".", "decrypted_data", "(", "key", ",", "cert", ")", "end", "@serializer", ".", "load", "(", "data", ")", "if", "data", "end" ]
Decrypt, authorize signature, and unserialize message Use x.509 certificate store for decrypting and validating signature === Parameters msg(String):: Serialized and optionally encrypted object using MessagePack or JSON id(String|nil):: Optional identifier of source of data for use in determining who is the receiver === Return (Object):: Unserialized object === Raise MissingCertificate:: If could not find certificate for message signer or receiver MissingPrivateKey:: If could not find private key for message receiver InvalidSignature:: If message signature check failed for message
[ "Decrypt", "authorize", "signature", "and", "unserialize", "message", "Use", "x", ".", "509", "certificate", "store", "for", "decrypting", "and", "validating", "signature" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/serialize/secure_serializer.rb#L127-L144
764
rightscale/right_agent
lib/right_agent/core_payload_types/right_script_attachment.rb
RightScale.RightScriptAttachment.fill_out
def fill_out(session) session['scope'] = "attachments" if @digest session['resource'] = @digest else session['resource'] = to_hash session['url'] = @url session['etag'] = @etag end @token = session.to_s end
ruby
def fill_out(session) session['scope'] = "attachments" if @digest session['resource'] = @digest else session['resource'] = to_hash session['url'] = @url session['etag'] = @etag end @token = session.to_s end
[ "def", "fill_out", "(", "session", ")", "session", "[", "'scope'", "]", "=", "\"attachments\"", "if", "@digest", "session", "[", "'resource'", "]", "=", "@digest", "else", "session", "[", "'resource'", "]", "=", "to_hash", "session", "[", "'url'", "]", "=", "@url", "session", "[", "'etag'", "]", "=", "@etag", "end", "@token", "=", "session", ".", "to_s", "end" ]
Fill out the session cookie appropriately for this attachment.
[ "Fill", "out", "the", "session", "cookie", "appropriately", "for", "this", "attachment", "." ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/core_payload_types/right_script_attachment.rb#L68-L78
765
rightscale/right_agent
lib/right_agent/command/command_parser.rb
RightScale.CommandParser.parse_chunk
def parse_chunk(chunk) @buildup << chunk chunks = @buildup.split(CommandSerializer::SEPARATOR, -1) if (do_call = chunks.size > 1) commands = [] (0..chunks.size - 2).each do |i| begin commands << CommandSerializer.load(chunks[i]) rescue StandardError => e # log any exceptions caused by serializing individual chunks instead # of halting EM. each command is discrete so we need to keep trying # so long as there are more commands to process (although subsequent # commands may lack context if previous commands failed). Log.error("Failed parsing command chunk", e, :trace) end end commands.each do |cmd| EM.next_tick do begin @callback.call(cmd) rescue Exception => e # log any exceptions raised by callback instead of halting EM. Log.error("Failed executing parsed command", e, :trace) end end end @buildup = chunks.last end do_call rescue StandardError => e # log any other exceptions instead of halting EM. Log.error("Failed parsing command chunk", e, :trace) end
ruby
def parse_chunk(chunk) @buildup << chunk chunks = @buildup.split(CommandSerializer::SEPARATOR, -1) if (do_call = chunks.size > 1) commands = [] (0..chunks.size - 2).each do |i| begin commands << CommandSerializer.load(chunks[i]) rescue StandardError => e # log any exceptions caused by serializing individual chunks instead # of halting EM. each command is discrete so we need to keep trying # so long as there are more commands to process (although subsequent # commands may lack context if previous commands failed). Log.error("Failed parsing command chunk", e, :trace) end end commands.each do |cmd| EM.next_tick do begin @callback.call(cmd) rescue Exception => e # log any exceptions raised by callback instead of halting EM. Log.error("Failed executing parsed command", e, :trace) end end end @buildup = chunks.last end do_call rescue StandardError => e # log any other exceptions instead of halting EM. Log.error("Failed parsing command chunk", e, :trace) end
[ "def", "parse_chunk", "(", "chunk", ")", "@buildup", "<<", "chunk", "chunks", "=", "@buildup", ".", "split", "(", "CommandSerializer", "::", "SEPARATOR", ",", "-", "1", ")", "if", "(", "do_call", "=", "chunks", ".", "size", ">", "1", ")", "commands", "=", "[", "]", "(", "0", "..", "chunks", ".", "size", "-", "2", ")", ".", "each", "do", "|", "i", "|", "begin", "commands", "<<", "CommandSerializer", ".", "load", "(", "chunks", "[", "i", "]", ")", "rescue", "StandardError", "=>", "e", "# log any exceptions caused by serializing individual chunks instead", "# of halting EM. each command is discrete so we need to keep trying", "# so long as there are more commands to process (although subsequent", "# commands may lack context if previous commands failed).", "Log", ".", "error", "(", "\"Failed parsing command chunk\"", ",", "e", ",", ":trace", ")", "end", "end", "commands", ".", "each", "do", "|", "cmd", "|", "EM", ".", "next_tick", "do", "begin", "@callback", ".", "call", "(", "cmd", ")", "rescue", "Exception", "=>", "e", "# log any exceptions raised by callback instead of halting EM.", "Log", ".", "error", "(", "\"Failed executing parsed command\"", ",", "e", ",", ":trace", ")", "end", "end", "end", "@buildup", "=", "chunks", ".", "last", "end", "do_call", "rescue", "StandardError", "=>", "e", "# log any other exceptions instead of halting EM.", "Log", ".", "error", "(", "\"Failed parsing command chunk\"", ",", "e", ",", ":trace", ")", "end" ]
Register callback block === Block Block that will get called back whenever a command is successfully parsed === Raise (ArgumentError): If block is missing Parse given input May cause multiple callbacks if multiple commands are successfully parsed Callback happens in next EM tick === Parameters chunk(String):: Chunck of serialized command(s) to be parsed === Return true:: If callback was called at least once false:: Otherwise
[ "Register", "callback", "block" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/command/command_parser.rb#L51-L83
766
rightscale/right_agent
spec/spec_helper.rb
RightScale.SpecHelper.issue_cert
def issue_cert test_dn = { 'C' => 'US', 'ST' => 'California', 'L' => 'Santa Barbara', 'O' => 'Agent', 'OU' => 'Certification Services', 'CN' => 'Agent test' } dn = DistinguishedName.new(test_dn) key = RsaKeyPair.new [ Certificate.new(key, dn, dn), key ] end
ruby
def issue_cert test_dn = { 'C' => 'US', 'ST' => 'California', 'L' => 'Santa Barbara', 'O' => 'Agent', 'OU' => 'Certification Services', 'CN' => 'Agent test' } dn = DistinguishedName.new(test_dn) key = RsaKeyPair.new [ Certificate.new(key, dn, dn), key ] end
[ "def", "issue_cert", "test_dn", "=", "{", "'C'", "=>", "'US'", ",", "'ST'", "=>", "'California'", ",", "'L'", "=>", "'Santa Barbara'", ",", "'O'", "=>", "'Agent'", ",", "'OU'", "=>", "'Certification Services'", ",", "'CN'", "=>", "'Agent test'", "}", "dn", "=", "DistinguishedName", ".", "new", "(", "test_dn", ")", "key", "=", "RsaKeyPair", ".", "new", "[", "Certificate", ".", "new", "(", "key", ",", "dn", ",", "dn", ")", ",", "key", "]", "end" ]
Create test certificate
[ "Create", "test", "certificate" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/spec/spec_helper.rb#L57-L67
767
rightscale/right_agent
lib/right_agent/dispatcher.rb
RightScale.Dispatcher.dispatch
def dispatch(request) token = request.token actor, method, idempotent = route(request) received_at = @request_stats.update(method, (token if request.is_a?(Request))) if (dup = duplicate?(request, method, idempotent)) raise DuplicateRequest, dup end unless (result = expired?(request, method)) result = perform(request, actor, method, idempotent) end if request.is_a?(Request) duration = @request_stats.finish(received_at, token) Result.new(token, request.reply_to, result, @identity, request.from, request.tries, request.persistent, duration) end end
ruby
def dispatch(request) token = request.token actor, method, idempotent = route(request) received_at = @request_stats.update(method, (token if request.is_a?(Request))) if (dup = duplicate?(request, method, idempotent)) raise DuplicateRequest, dup end unless (result = expired?(request, method)) result = perform(request, actor, method, idempotent) end if request.is_a?(Request) duration = @request_stats.finish(received_at, token) Result.new(token, request.reply_to, result, @identity, request.from, request.tries, request.persistent, duration) end end
[ "def", "dispatch", "(", "request", ")", "token", "=", "request", ".", "token", "actor", ",", "method", ",", "idempotent", "=", "route", "(", "request", ")", "received_at", "=", "@request_stats", ".", "update", "(", "method", ",", "(", "token", "if", "request", ".", "is_a?", "(", "Request", ")", ")", ")", "if", "(", "dup", "=", "duplicate?", "(", "request", ",", "method", ",", "idempotent", ")", ")", "raise", "DuplicateRequest", ",", "dup", "end", "unless", "(", "result", "=", "expired?", "(", "request", ",", "method", ")", ")", "result", "=", "perform", "(", "request", ",", "actor", ",", "method", ",", "idempotent", ")", "end", "if", "request", ".", "is_a?", "(", "Request", ")", "duration", "=", "@request_stats", ".", "finish", "(", "received_at", ",", "token", ")", "Result", ".", "new", "(", "token", ",", "request", ".", "reply_to", ",", "result", ",", "@identity", ",", "request", ".", "from", ",", "request", ".", "tries", ",", "request", ".", "persistent", ",", "duration", ")", "end", "end" ]
Route request to appropriate actor for servicing Reject requests whose TTL has expired or that are duplicates of work already dispatched === Parameters request(Request|Push):: Packet containing request header(AMQP::Frame::Header|nil):: Request header containing ack control === Return (Result|nil):: Result of request, or nil if there is no result because request is a Push === Raise InvalidRequestType:: If the request cannot be routed to an actor DuplicateRequest:: If request rejected because it has already been processed
[ "Route", "request", "to", "appropriate", "actor", "for", "servicing", "Reject", "requests", "whose", "TTL", "has", "expired", "or", "that", "are", "duplicates", "of", "work", "already", "dispatched" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/dispatcher.rb#L86-L100
768
rightscale/right_agent
lib/right_agent/dispatcher.rb
RightScale.Dispatcher.stats
def stats(reset = false) stats = { "dispatched cache" => (@dispatched_cache.stats if @dispatched_cache), "dispatch failures" => @dispatch_failure_stats.all, "rejects" => @reject_stats.all, "requests" => @request_stats.all } reset_stats if reset stats end
ruby
def stats(reset = false) stats = { "dispatched cache" => (@dispatched_cache.stats if @dispatched_cache), "dispatch failures" => @dispatch_failure_stats.all, "rejects" => @reject_stats.all, "requests" => @request_stats.all } reset_stats if reset stats end
[ "def", "stats", "(", "reset", "=", "false", ")", "stats", "=", "{", "\"dispatched cache\"", "=>", "(", "@dispatched_cache", ".", "stats", "if", "@dispatched_cache", ")", ",", "\"dispatch failures\"", "=>", "@dispatch_failure_stats", ".", "all", ",", "\"rejects\"", "=>", "@reject_stats", ".", "all", ",", "\"requests\"", "=>", "@request_stats", ".", "all", "}", "reset_stats", "if", "reset", "stats", "end" ]
Get dispatcher statistics === Parameters reset(Boolean):: Whether to reset the statistics after getting the current ones === Return stats(Hash):: Current statistics: "dispatched cache"(Hash|nil):: Number of dispatched requests cached and age of youngest and oldest, or nil if empty "dispatch failures"(Hash|nil):: Dispatch failure activity stats with keys "total", "percent", "last", and "rate" with percentage breakdown per failure type, or nil if none "rejects"(Hash|nil):: Request reject activity stats with keys "total", "percent", "last", and "rate" with percentage breakdown per reason ("duplicate (<method>)", "retry duplicate (<method>)", or "stale (<method>)"), 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
[ "Get", "dispatcher", "statistics" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/dispatcher.rb#L118-L127
769
rightscale/right_agent
lib/right_agent/dispatcher.rb
RightScale.Dispatcher.expired?
def expired?(request, method) if (expires_at = request.expires_at) && expires_at > 0 && (now = Time.now.to_i) >= expires_at @reject_stats.update("expired (#{method})") Log.info("REJECT EXPIRED <#{request.token}> from #{request.from} TTL #{RightSupport::Stats.elapsed(now - expires_at)} ago") # For agents that do not know about non-delivery, use error result if can_handle_non_delivery_result?(request.recv_version) OperationResult.non_delivery(OperationResult::TTL_EXPIRATION) else OperationResult.error("Could not deliver request (#{OperationResult::TTL_EXPIRATION})") end end end
ruby
def expired?(request, method) if (expires_at = request.expires_at) && expires_at > 0 && (now = Time.now.to_i) >= expires_at @reject_stats.update("expired (#{method})") Log.info("REJECT EXPIRED <#{request.token}> from #{request.from} TTL #{RightSupport::Stats.elapsed(now - expires_at)} ago") # For agents that do not know about non-delivery, use error result if can_handle_non_delivery_result?(request.recv_version) OperationResult.non_delivery(OperationResult::TTL_EXPIRATION) else OperationResult.error("Could not deliver request (#{OperationResult::TTL_EXPIRATION})") end end end
[ "def", "expired?", "(", "request", ",", "method", ")", "if", "(", "expires_at", "=", "request", ".", "expires_at", ")", "&&", "expires_at", ">", "0", "&&", "(", "now", "=", "Time", ".", "now", ".", "to_i", ")", ">=", "expires_at", "@reject_stats", ".", "update", "(", "\"expired (#{method})\"", ")", "Log", ".", "info", "(", "\"REJECT EXPIRED <#{request.token}> from #{request.from} TTL #{RightSupport::Stats.elapsed(now - expires_at)} ago\"", ")", "# For agents that do not know about non-delivery, use error result", "if", "can_handle_non_delivery_result?", "(", "request", ".", "recv_version", ")", "OperationResult", ".", "non_delivery", "(", "OperationResult", "::", "TTL_EXPIRATION", ")", "else", "OperationResult", ".", "error", "(", "\"Could not deliver request (#{OperationResult::TTL_EXPIRATION})\"", ")", "end", "end", "end" ]
Determine if request TTL has expired === Parameters request(Push|Request):: Request to be checked method(String):: Actor method requested to be performed === Return (OperationResult|nil):: Error result if expired, otherwise nil
[ "Determine", "if", "request", "TTL", "has", "expired" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/dispatcher.rb#L150-L161
770
rightscale/right_agent
lib/right_agent/dispatcher.rb
RightScale.Dispatcher.duplicate?
def duplicate?(request, method, idempotent) if !idempotent && @dispatched_cache if (serviced_by = @dispatched_cache.serviced_by(request.token)) from_retry = "" else from_retry = "retry " request.tries.each { |t| break if (serviced_by = @dispatched_cache.serviced_by(t)) } end if serviced_by @reject_stats.update("#{from_retry}duplicate (#{method})") msg = "<#{request.token}> already serviced by #{serviced_by == @identity ? 'self' : serviced_by}" Log.info("REJECT #{from_retry.upcase}DUP #{msg}") msg end end end
ruby
def duplicate?(request, method, idempotent) if !idempotent && @dispatched_cache if (serviced_by = @dispatched_cache.serviced_by(request.token)) from_retry = "" else from_retry = "retry " request.tries.each { |t| break if (serviced_by = @dispatched_cache.serviced_by(t)) } end if serviced_by @reject_stats.update("#{from_retry}duplicate (#{method})") msg = "<#{request.token}> already serviced by #{serviced_by == @identity ? 'self' : serviced_by}" Log.info("REJECT #{from_retry.upcase}DUP #{msg}") msg end end end
[ "def", "duplicate?", "(", "request", ",", "method", ",", "idempotent", ")", "if", "!", "idempotent", "&&", "@dispatched_cache", "if", "(", "serviced_by", "=", "@dispatched_cache", ".", "serviced_by", "(", "request", ".", "token", ")", ")", "from_retry", "=", "\"\"", "else", "from_retry", "=", "\"retry \"", "request", ".", "tries", ".", "each", "{", "|", "t", "|", "break", "if", "(", "serviced_by", "=", "@dispatched_cache", ".", "serviced_by", "(", "t", ")", ")", "}", "end", "if", "serviced_by", "@reject_stats", ".", "update", "(", "\"#{from_retry}duplicate (#{method})\"", ")", "msg", "=", "\"<#{request.token}> already serviced by #{serviced_by == @identity ? 'self' : serviced_by}\"", "Log", ".", "info", "(", "\"REJECT #{from_retry.upcase}DUP #{msg}\"", ")", "msg", "end", "end", "end" ]
Determine whether this request is a duplicate === Parameters request(Request|Push):: Packet containing request method(String):: Actor method requested to be performed idempotent(Boolean):: Whether this method is idempotent === Return (String|nil):: Messaging describing who already serviced request if it is a duplicate, otherwise nil
[ "Determine", "whether", "this", "request", "is", "a", "duplicate" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/dispatcher.rb#L172-L187
771
rightscale/right_agent
lib/right_agent/dispatcher.rb
RightScale.Dispatcher.route
def route(request) prefix, method = request.type.split('/')[1..-1] method ||= :index method = method.to_sym actor = @registry.actor_for(prefix) if actor.nil? || !actor.respond_to?(method) raise InvalidRequestType, "Unknown actor or method for dispatching request <#{request.token}> of type #{request.type}" end [actor, method, actor.class.idempotent?(method)] end
ruby
def route(request) prefix, method = request.type.split('/')[1..-1] method ||= :index method = method.to_sym actor = @registry.actor_for(prefix) if actor.nil? || !actor.respond_to?(method) raise InvalidRequestType, "Unknown actor or method for dispatching request <#{request.token}> of type #{request.type}" end [actor, method, actor.class.idempotent?(method)] end
[ "def", "route", "(", "request", ")", "prefix", ",", "method", "=", "request", ".", "type", ".", "split", "(", "'/'", ")", "[", "1", "..", "-", "1", "]", "method", "||=", ":index", "method", "=", "method", ".", "to_sym", "actor", "=", "@registry", ".", "actor_for", "(", "prefix", ")", "if", "actor", ".", "nil?", "||", "!", "actor", ".", "respond_to?", "(", "method", ")", "raise", "InvalidRequestType", ",", "\"Unknown actor or method for dispatching request <#{request.token}> of type #{request.type}\"", "end", "[", "actor", ",", "method", ",", "actor", ".", "class", ".", "idempotent?", "(", "method", ")", "]", "end" ]
Use request type to route request to actor and an associated method === Parameters request(Push|Request):: Packet containing request === Return (Array):: Actor name, method name, and whether method is idempotent === Raise InvalidRequestType:: If the request cannot be routed to an actor
[ "Use", "request", "type", "to", "route", "request", "to", "actor", "and", "an", "associated", "method" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/dispatcher.rb#L199-L208
772
rightscale/right_agent
lib/right_agent/dispatcher.rb
RightScale.Dispatcher.perform
def perform(request, actor, method, idempotent) @dispatched_cache.store(request.token) if @dispatched_cache && !idempotent if actor.method(method).arity.abs == 1 actor.send(method, request.payload) else actor.send(method, request.payload, request) end rescue StandardError => e ErrorTracker.log(self, "Failed dispatching #{request.trace}", e, request) @dispatch_failure_stats.update("#{request.type}->#{e.class.name}") OperationResult.error("Could not handle #{request.type} request", e) end
ruby
def perform(request, actor, method, idempotent) @dispatched_cache.store(request.token) if @dispatched_cache && !idempotent if actor.method(method).arity.abs == 1 actor.send(method, request.payload) else actor.send(method, request.payload, request) end rescue StandardError => e ErrorTracker.log(self, "Failed dispatching #{request.trace}", e, request) @dispatch_failure_stats.update("#{request.type}->#{e.class.name}") OperationResult.error("Could not handle #{request.type} request", e) end
[ "def", "perform", "(", "request", ",", "actor", ",", "method", ",", "idempotent", ")", "@dispatched_cache", ".", "store", "(", "request", ".", "token", ")", "if", "@dispatched_cache", "&&", "!", "idempotent", "if", "actor", ".", "method", "(", "method", ")", ".", "arity", ".", "abs", "==", "1", "actor", ".", "send", "(", "method", ",", "request", ".", "payload", ")", "else", "actor", ".", "send", "(", "method", ",", "request", ".", "payload", ",", "request", ")", "end", "rescue", "StandardError", "=>", "e", "ErrorTracker", ".", "log", "(", "self", ",", "\"Failed dispatching #{request.trace}\"", ",", "e", ",", "request", ")", "@dispatch_failure_stats", ".", "update", "(", "\"#{request.type}->#{e.class.name}\"", ")", "OperationResult", ".", "error", "(", "\"Could not handle #{request.type} request\"", ",", "e", ")", "end" ]
Perform requested action === Parameters request(Push|Request):: Packet containing request token(String):: Unique identity token for request method(String):: Actor method requested to be performed idempotent(Boolean):: Whether this method is idempotent === Return (OperationResult):: Result from performing a request
[ "Perform", "requested", "action" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/dispatcher.rb#L220-L231
773
rightscale/right_agent
lib/right_agent/security/certificate.rb
RightScale.Certificate.save
def save(file) File.open(file, "w") do |f| f.write(@raw_cert.to_pem) end true end
ruby
def save(file) File.open(file, "w") do |f| f.write(@raw_cert.to_pem) end true end
[ "def", "save", "(", "file", ")", "File", ".", "open", "(", "file", ",", "\"w\"", ")", "do", "|", "f", "|", "f", ".", "write", "(", "@raw_cert", ".", "to_pem", ")", "end", "true", "end" ]
Save certificate to file in PEM format === Parameters file(String):: File path name === Return true:: Always return true
[ "Save", "certificate", "to", "file", "in", "PEM", "format" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/security/certificate.rb#L84-L89
774
rightscale/right_agent
lib/right_agent/history.rb
RightScale.History.load
def load events = [] File.open(@history, "r") { |f| events = f.readlines.map { |l| JSON.legacy_load(l) } } if File.readable?(@history) events end
ruby
def load events = [] File.open(@history, "r") { |f| events = f.readlines.map { |l| JSON.legacy_load(l) } } if File.readable?(@history) events end
[ "def", "load", "events", "=", "[", "]", "File", ".", "open", "(", "@history", ",", "\"r\"", ")", "{", "|", "f", "|", "events", "=", "f", ".", "readlines", ".", "map", "{", "|", "l", "|", "JSON", ".", "legacy_load", "(", "l", ")", "}", "}", "if", "File", ".", "readable?", "(", "@history", ")", "events", "end" ]
Load events from history file === Return events(Array):: List of historical events with each being a hash of :time(Integer):: Time in seconds in Unix-epoch when event occurred :pid(Integer):: Process id of agent recording the event :event(Object):: Event object in the form String or {String => Object}, where String is the event name and Object is any associated JSON-encodable data
[ "Load", "events", "from", "history", "file" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/history.rb#L63-L67
775
rightscale/right_agent
lib/right_agent/clients/api_client.rb
RightScale.ApiClient.map_request
def map_request(type, payload, options) verb, path = API_MAP[type] raise ArgumentError, "Unsupported request type: #{type}" if path.nil? actor, action = type.split("/")[1..-1] path, params, request_options = parameterize(actor, action, payload, path) if action == "query_tags" map_query_tags(verb, params, action, options.merge(request_options)) else map_response(make_request(verb, path, params, action, options.merge(request_options)), path) end end
ruby
def map_request(type, payload, options) verb, path = API_MAP[type] raise ArgumentError, "Unsupported request type: #{type}" if path.nil? actor, action = type.split("/")[1..-1] path, params, request_options = parameterize(actor, action, payload, path) if action == "query_tags" map_query_tags(verb, params, action, options.merge(request_options)) else map_response(make_request(verb, path, params, action, options.merge(request_options)), path) end end
[ "def", "map_request", "(", "type", ",", "payload", ",", "options", ")", "verb", ",", "path", "=", "API_MAP", "[", "type", "]", "raise", "ArgumentError", ",", "\"Unsupported request type: #{type}\"", "if", "path", ".", "nil?", "actor", ",", "action", "=", "type", ".", "split", "(", "\"/\"", ")", "[", "1", "..", "-", "1", "]", "path", ",", "params", ",", "request_options", "=", "parameterize", "(", "actor", ",", "action", ",", "payload", ",", "path", ")", "if", "action", "==", "\"query_tags\"", "map_query_tags", "(", "verb", ",", "params", ",", "action", ",", "options", ".", "merge", "(", "request_options", ")", ")", "else", "map_response", "(", "make_request", "(", "verb", ",", "path", ",", "params", ",", "action", ",", "options", ".", "merge", "(", "request_options", ")", ")", ",", "path", ")", "end", "end" ]
Convert request to RightApi form and then make request via HTTP @param [String] type of request as path specifying actor and action @param [Hash, NilClass] payload for request @option options [String] :request_uuid uniquely identifying this request @option options [Numeric] :time_to_live seconds before request expires and is to be ignored @return [Object, NilClass] response from request @raise [Exceptions::Unauthorized] authorization failed @raise [Exceptions::ConnectivityFailure] cannot connect to server, lost connection to it, or it is 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
[ "Convert", "request", "to", "RightApi", "form", "and", "then", "make", "request", "via", "HTTP" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/api_client.rb#L192-L202
776
rightscale/right_agent
lib/right_agent/clients/api_client.rb
RightScale.ApiClient.map_response
def map_response(response, path) case path when "/audit_entries" # Convert returned audit entry href to audit ID response.sub!(/^.*\/api\/audit_entries\//, "") if response.is_a?(String) when "/tags/by_resource", "/tags/by_tag" # Extract tags for each instance resource from response array with members of form # {"actions" => [], "links" => [{"rel" => "resource", "href" => <href>}, ...]}, "tags" => [{"name" => <tag>}, ...] tags = {} if response response.each do |hash| r = {} hash["links"].each { |l| r[l["href"]] = {"tags" => []} if l["href"] =~ /instances/ } hash["tags"].each { |t| r.each_key { |k| r[k]["tags"] << t["name"] } } if r.any? tags.merge!(r) end end response = tags end response end
ruby
def map_response(response, path) case path when "/audit_entries" # Convert returned audit entry href to audit ID response.sub!(/^.*\/api\/audit_entries\//, "") if response.is_a?(String) when "/tags/by_resource", "/tags/by_tag" # Extract tags for each instance resource from response array with members of form # {"actions" => [], "links" => [{"rel" => "resource", "href" => <href>}, ...]}, "tags" => [{"name" => <tag>}, ...] tags = {} if response response.each do |hash| r = {} hash["links"].each { |l| r[l["href"]] = {"tags" => []} if l["href"] =~ /instances/ } hash["tags"].each { |t| r.each_key { |k| r[k]["tags"] << t["name"] } } if r.any? tags.merge!(r) end end response = tags end response end
[ "def", "map_response", "(", "response", ",", "path", ")", "case", "path", "when", "\"/audit_entries\"", "# Convert returned audit entry href to audit ID", "response", ".", "sub!", "(", "/", "\\/", "\\/", "\\/", "/", ",", "\"\"", ")", "if", "response", ".", "is_a?", "(", "String", ")", "when", "\"/tags/by_resource\"", ",", "\"/tags/by_tag\"", "# Extract tags for each instance resource from response array with members of form", "# {\"actions\" => [], \"links\" => [{\"rel\" => \"resource\", \"href\" => <href>}, ...]}, \"tags\" => [{\"name\" => <tag>}, ...]", "tags", "=", "{", "}", "if", "response", "response", ".", "each", "do", "|", "hash", "|", "r", "=", "{", "}", "hash", "[", "\"links\"", "]", ".", "each", "{", "|", "l", "|", "r", "[", "l", "[", "\"href\"", "]", "]", "=", "{", "\"tags\"", "=>", "[", "]", "}", "if", "l", "[", "\"href\"", "]", "=~", "/", "/", "}", "hash", "[", "\"tags\"", "]", ".", "each", "{", "|", "t", "|", "r", ".", "each_key", "{", "|", "k", "|", "r", "[", "k", "]", "[", "\"tags\"", "]", "<<", "t", "[", "\"name\"", "]", "}", "}", "if", "r", ".", "any?", "tags", ".", "merge!", "(", "r", ")", "end", "end", "response", "=", "tags", "end", "response", "end" ]
Convert response from request into required form where necessary @param [Object] response received @param [String] path in URI for desired resource @return [Object] converted response
[ "Convert", "response", "from", "request", "into", "required", "form", "where", "necessary" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/api_client.rb#L210-L230
777
rightscale/right_agent
lib/right_agent/clients/api_client.rb
RightScale.ApiClient.map_query_tags
def map_query_tags(verb, params, action, options) response = {} hrefs = params[:resource_hrefs] || [] hrefs.concat(query_by_tag(verb, params[:tags], action, options)) if params[:tags] response = query_by_resource(verb, hrefs, action, options) if hrefs.any? response end
ruby
def map_query_tags(verb, params, action, options) response = {} hrefs = params[:resource_hrefs] || [] hrefs.concat(query_by_tag(verb, params[:tags], action, options)) if params[:tags] response = query_by_resource(verb, hrefs, action, options) if hrefs.any? response end
[ "def", "map_query_tags", "(", "verb", ",", "params", ",", "action", ",", "options", ")", "response", "=", "{", "}", "hrefs", "=", "params", "[", ":resource_hrefs", "]", "||", "[", "]", "hrefs", ".", "concat", "(", "query_by_tag", "(", "verb", ",", "params", "[", ":tags", "]", ",", "action", ",", "options", ")", ")", "if", "params", "[", ":tags", "]", "response", "=", "query_by_resource", "(", "verb", ",", "hrefs", ",", "action", ",", "options", ")", "if", "hrefs", ".", "any?", "response", "end" ]
Convert tag query request into one or more API requests and then convert responses Currently only retrieving "instances" resources @param [Symbol] verb for HTTP REST request @param [Hash] params for HTTP request @param [String] action from request type @param [Hash] options augmenting or overriding default options for HTTP request @return [Hash] tags retrieved with resource href as key and tags array as value
[ "Convert", "tag", "query", "request", "into", "one", "or", "more", "API", "requests", "and", "then", "convert", "responses", "Currently", "only", "retrieving", "instances", "resources" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/api_client.rb#L241-L247
778
rightscale/right_agent
lib/right_agent/clients/api_client.rb
RightScale.ApiClient.query_by_tag
def query_by_tag(verb, tags, action, options) path = "/tags/by_tag" params = {:tags => tags, :match_all => false, :resource_type => "instances"} map_response(make_request(verb, path, params, action, options), path).keys end
ruby
def query_by_tag(verb, tags, action, options) path = "/tags/by_tag" params = {:tags => tags, :match_all => false, :resource_type => "instances"} map_response(make_request(verb, path, params, action, options), path).keys end
[ "def", "query_by_tag", "(", "verb", ",", "tags", ",", "action", ",", "options", ")", "path", "=", "\"/tags/by_tag\"", "params", "=", "{", ":tags", "=>", "tags", ",", ":match_all", "=>", "false", ",", ":resource_type", "=>", "\"instances\"", "}", "map_response", "(", "make_request", "(", "verb", ",", "path", ",", "params", ",", "action", ",", "options", ")", ",", "path", ")", ".", "keys", "end" ]
Query API for resources with specified tags @param [Symbol] verb for HTTP REST request @param [Array] tags that all resources retrieved must have @param [String] action from request type @param [Hash] options augmenting or overriding default options for HTTP request @return [Array] resource hrefs
[ "Query", "API", "for", "resources", "with", "specified", "tags" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/api_client.rb#L257-L261
779
rightscale/right_agent
lib/right_agent/clients/api_client.rb
RightScale.ApiClient.query_by_resource
def query_by_resource(verb, hrefs, action, options) path = "/tags/by_resource" params = {:resource_hrefs => hrefs} map_response(make_request(verb, path, params, action, options), path) end
ruby
def query_by_resource(verb, hrefs, action, options) path = "/tags/by_resource" params = {:resource_hrefs => hrefs} map_response(make_request(verb, path, params, action, options), path) end
[ "def", "query_by_resource", "(", "verb", ",", "hrefs", ",", "action", ",", "options", ")", "path", "=", "\"/tags/by_resource\"", "params", "=", "{", ":resource_hrefs", "=>", "hrefs", "}", "map_response", "(", "make_request", "(", "verb", ",", "path", ",", "params", ",", "action", ",", "options", ")", ",", "path", ")", "end" ]
Query API for tags associated with a set of resources @param [Symbol] verb for HTTP REST request @param [Array] hrefs for resources whose tags are to be retrieved @param [String] action from request type @param [Hash] options augmenting or overriding default options for HTTP request @return [Hash] tags retrieved with resource href as key and tags array as value
[ "Query", "API", "for", "tags", "associated", "with", "a", "set", "of", "resources" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/api_client.rb#L271-L275
780
rightscale/right_agent
lib/right_agent/clients/api_client.rb
RightScale.ApiClient.parameterize
def parameterize(actor, action, payload, path) options = {} params = {} if actor == "auditor" path = path.sub(/:id/, payload[:audit_id].to_s || "") params = parameterize_audit(action, payload) options = {:filter_params => AUDIT_FILTER_PARAMS} elsif actor == "router" && action =~ /_tags/ if action != "query_tags" params[:resource_hrefs] = [@self_href] else params[:resource_hrefs] = Array(payload[:hrefs]).flatten.compact if payload[:hrefs] end params[:tags] = Array(payload[:tags]).flatten.compact if payload[:tags] else # Can remove :agent_identity here since now carried in the authorization as the :agent payload.each { |k, v| params[k.to_sym] = v if k.to_sym != :agent_identity } if payload.is_a?(Hash) end [path, params, options] end
ruby
def parameterize(actor, action, payload, path) options = {} params = {} if actor == "auditor" path = path.sub(/:id/, payload[:audit_id].to_s || "") params = parameterize_audit(action, payload) options = {:filter_params => AUDIT_FILTER_PARAMS} elsif actor == "router" && action =~ /_tags/ if action != "query_tags" params[:resource_hrefs] = [@self_href] else params[:resource_hrefs] = Array(payload[:hrefs]).flatten.compact if payload[:hrefs] end params[:tags] = Array(payload[:tags]).flatten.compact if payload[:tags] else # Can remove :agent_identity here since now carried in the authorization as the :agent payload.each { |k, v| params[k.to_sym] = v if k.to_sym != :agent_identity } if payload.is_a?(Hash) end [path, params, options] end
[ "def", "parameterize", "(", "actor", ",", "action", ",", "payload", ",", "path", ")", "options", "=", "{", "}", "params", "=", "{", "}", "if", "actor", "==", "\"auditor\"", "path", "=", "path", ".", "sub", "(", "/", "/", ",", "payload", "[", ":audit_id", "]", ".", "to_s", "||", "\"\"", ")", "params", "=", "parameterize_audit", "(", "action", ",", "payload", ")", "options", "=", "{", ":filter_params", "=>", "AUDIT_FILTER_PARAMS", "}", "elsif", "actor", "==", "\"router\"", "&&", "action", "=~", "/", "/", "if", "action", "!=", "\"query_tags\"", "params", "[", ":resource_hrefs", "]", "=", "[", "@self_href", "]", "else", "params", "[", ":resource_hrefs", "]", "=", "Array", "(", "payload", "[", ":hrefs", "]", ")", ".", "flatten", ".", "compact", "if", "payload", "[", ":hrefs", "]", "end", "params", "[", ":tags", "]", "=", "Array", "(", "payload", "[", ":tags", "]", ")", ".", "flatten", ".", "compact", "if", "payload", "[", ":tags", "]", "else", "# Can remove :agent_identity here since now carried in the authorization as the :agent", "payload", ".", "each", "{", "|", "k", ",", "v", "|", "params", "[", "k", ".", "to_sym", "]", "=", "v", "if", "k", ".", "to_sym", "!=", ":agent_identity", "}", "if", "payload", ".", "is_a?", "(", "Hash", ")", "end", "[", "path", ",", "params", ",", "options", "]", "end" ]
Convert payload to HTTP parameters @param [String] actor from request type @param [String] action from request type @param [Hash, NilClass] payload for request @param [String] path in URI for desired resource @return [Array] path string and parameters and options hashes
[ "Convert", "payload", "to", "HTTP", "parameters" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/api_client.rb#L285-L304
781
rightscale/right_agent
lib/right_agent/clients/api_client.rb
RightScale.ApiClient.parameterize_audit
def parameterize_audit(action, payload) params = {} summary = non_blank(payload[:summary]) detail = non_blank(payload[:detail]) case action when "create_entry" params[:audit_entry] = {:auditee_href => @self_href} params[:audit_entry][:summary] = truncate(summary, MAX_AUDIT_SUMMARY_LENGTH) if summary params[:audit_entry][:detail] = detail if detail if (user_email = non_blank(payload[:user_email])) params[:user_email] = user_email end params[:notify] = payload[:category] if payload[:category] when "update_entry" params[:offset] = payload[:offset] if payload[:offset] if summary params[:summary] = truncate(summary, MAX_AUDIT_SUMMARY_LENGTH) params[:notify] = payload[:category] if payload[:category] end params[:detail] = detail if detail else raise ArgumentError, "Unknown audit request action: #{action}" end params end
ruby
def parameterize_audit(action, payload) params = {} summary = non_blank(payload[:summary]) detail = non_blank(payload[:detail]) case action when "create_entry" params[:audit_entry] = {:auditee_href => @self_href} params[:audit_entry][:summary] = truncate(summary, MAX_AUDIT_SUMMARY_LENGTH) if summary params[:audit_entry][:detail] = detail if detail if (user_email = non_blank(payload[:user_email])) params[:user_email] = user_email end params[:notify] = payload[:category] if payload[:category] when "update_entry" params[:offset] = payload[:offset] if payload[:offset] if summary params[:summary] = truncate(summary, MAX_AUDIT_SUMMARY_LENGTH) params[:notify] = payload[:category] if payload[:category] end params[:detail] = detail if detail else raise ArgumentError, "Unknown audit request action: #{action}" end params end
[ "def", "parameterize_audit", "(", "action", ",", "payload", ")", "params", "=", "{", "}", "summary", "=", "non_blank", "(", "payload", "[", ":summary", "]", ")", "detail", "=", "non_blank", "(", "payload", "[", ":detail", "]", ")", "case", "action", "when", "\"create_entry\"", "params", "[", ":audit_entry", "]", "=", "{", ":auditee_href", "=>", "@self_href", "}", "params", "[", ":audit_entry", "]", "[", ":summary", "]", "=", "truncate", "(", "summary", ",", "MAX_AUDIT_SUMMARY_LENGTH", ")", "if", "summary", "params", "[", ":audit_entry", "]", "[", ":detail", "]", "=", "detail", "if", "detail", "if", "(", "user_email", "=", "non_blank", "(", "payload", "[", ":user_email", "]", ")", ")", "params", "[", ":user_email", "]", "=", "user_email", "end", "params", "[", ":notify", "]", "=", "payload", "[", ":category", "]", "if", "payload", "[", ":category", "]", "when", "\"update_entry\"", "params", "[", ":offset", "]", "=", "payload", "[", ":offset", "]", "if", "payload", "[", ":offset", "]", "if", "summary", "params", "[", ":summary", "]", "=", "truncate", "(", "summary", ",", "MAX_AUDIT_SUMMARY_LENGTH", ")", "params", "[", ":notify", "]", "=", "payload", "[", ":category", "]", "if", "payload", "[", ":category", "]", "end", "params", "[", ":detail", "]", "=", "detail", "if", "detail", "else", "raise", "ArgumentError", ",", "\"Unknown audit request action: #{action}\"", "end", "params", "end" ]
Translate audit request payload to HTTP parameters Truncate audit summary to MAX_AUDIT_SUMMARY_LENGTH, the limit imposed by RightApi @param [String] action requested: create_entry or update_entry @param [Hash] payload from submitted request @return [Hash] HTTP request parameters @raise [ArgumentError] unknown request action
[ "Translate", "audit", "request", "payload", "to", "HTTP", "parameters", "Truncate", "audit", "summary", "to", "MAX_AUDIT_SUMMARY_LENGTH", "the", "limit", "imposed", "by", "RightApi" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/api_client.rb#L315-L339
782
rightscale/right_agent
lib/right_agent/clients/api_client.rb
RightScale.ApiClient.truncate
def truncate(value, max_length) raise ArgumentError, "max_length must be greater than 3" if max_length <= 3 if value.is_a?(String) && value.bytesize > max_length max_truncated = max_length - 3 truncated = value[0, max_truncated] while truncated.bytesize > max_truncated do truncated.chop! end truncated + "..." else value end end
ruby
def truncate(value, max_length) raise ArgumentError, "max_length must be greater than 3" if max_length <= 3 if value.is_a?(String) && value.bytesize > max_length max_truncated = max_length - 3 truncated = value[0, max_truncated] while truncated.bytesize > max_truncated do truncated.chop! end truncated + "..." else value end end
[ "def", "truncate", "(", "value", ",", "max_length", ")", "raise", "ArgumentError", ",", "\"max_length must be greater than 3\"", "if", "max_length", "<=", "3", "if", "value", ".", "is_a?", "(", "String", ")", "&&", "value", ".", "bytesize", ">", "max_length", "max_truncated", "=", "max_length", "-", "3", "truncated", "=", "value", "[", "0", ",", "max_truncated", "]", "while", "truncated", ".", "bytesize", ">", "max_truncated", "do", "truncated", ".", "chop!", "end", "truncated", "+", "\"...\"", "else", "value", "end", "end" ]
Truncate string if it exceeds maximum length Do length check with bytesize rather than size since this method is only intended for use with ruby 1.9 and above, otherwise multi-byte characters could cause this code to be too lenient @param [String, NilClass] value to be truncated @param [Integer] max_length allowed; must be greater than 3 @return [String, NilClass] truncated string or original value if it is not a string @raise [ArgumentError] max_length too small
[ "Truncate", "string", "if", "it", "exceeds", "maximum", "length", "Do", "length", "check", "with", "bytesize", "rather", "than", "size", "since", "this", "method", "is", "only", "intended", "for", "use", "with", "ruby", "1", ".", "9", "and", "above", "otherwise", "multi", "-", "byte", "characters", "could", "cause", "this", "code", "to", "be", "too", "lenient" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/api_client.rb#L352-L364
783
KatanaCode/kirigami
lib/kirigami/image.rb
Kirigami.Image.cut!
def cut! create_backup_copy MiniMagick::Tool::Mogrify.new do |mogrify| mogrify.resize(max_size) mogrify.strip if jpeg? mogrify.colorspace(Kirigami.config.jpeg_colorspace) mogrify.sampling_factor(Kirigami.config.jpeg_sampling_factor) mogrify.interlace(Kirigami.config.jpeg_interlacing) mogrify.quality(Kirigami.config.jpeg_compression_quality) end mogrify << target_filepath end end
ruby
def cut! create_backup_copy MiniMagick::Tool::Mogrify.new do |mogrify| mogrify.resize(max_size) mogrify.strip if jpeg? mogrify.colorspace(Kirigami.config.jpeg_colorspace) mogrify.sampling_factor(Kirigami.config.jpeg_sampling_factor) mogrify.interlace(Kirigami.config.jpeg_interlacing) mogrify.quality(Kirigami.config.jpeg_compression_quality) end mogrify << target_filepath end end
[ "def", "cut!", "create_backup_copy", "MiniMagick", "::", "Tool", "::", "Mogrify", ".", "new", "do", "|", "mogrify", "|", "mogrify", ".", "resize", "(", "max_size", ")", "mogrify", ".", "strip", "if", "jpeg?", "mogrify", ".", "colorspace", "(", "Kirigami", ".", "config", ".", "jpeg_colorspace", ")", "mogrify", ".", "sampling_factor", "(", "Kirigami", ".", "config", ".", "jpeg_sampling_factor", ")", "mogrify", ".", "interlace", "(", "Kirigami", ".", "config", ".", "jpeg_interlacing", ")", "mogrify", ".", "quality", "(", "Kirigami", ".", "config", ".", "jpeg_compression_quality", ")", "end", "mogrify", "<<", "target_filepath", "end", "end" ]
Create a new Image max_size - An ImageSize to specify the size and name of image. Cuts the File down to size! Creates a backup copy first, if required.
[ "Create", "a", "new", "Image" ]
191b8756869b09ad5a9afd4f30fc3c07e8373318
https://github.com/KatanaCode/kirigami/blob/191b8756869b09ad5a9afd4f30fc3c07e8373318/lib/kirigami/image.rb#L28-L41
784
Phybbit/dataflow-rb
lib/dataflow/schema_mixin.rb
Dataflow.SchemaMixin.infer_schema
def infer_schema(samples_count: 0, extended: false) if db_backend == :postgresql # Experimental sch = db_adapter.client.schema(read_dataset_name).to_h sch = sch.reject{ |k, v| k == :_id }.map { |k,v| [k, {type: v[:type].to_s}] }.to_h self.inferred_schema = sch save return sch end data_count = samples_count == 0 ? count : samples_count # invoked in the base class return {} if data_count == 0 # find out how many batches are needed max_per_process = 1000 max_per_process = limit_per_process if respond_to?(:limit_per_process) && limit_per_process > 0 equal_split_per_process = (data_count / Parallel.processor_count.to_f).ceil count_per_process = [max_per_process, equal_split_per_process].min queries = ordered_system_id_queries(batch_size: count_per_process)[0...data_count] self.inferred_schema_at = Time.now self.inferred_schema_from = samples_count on_schema_inference_started sch = schema_inferrer.infer_schema(batch_count: queries.count, extended: extended) do |idx| progress = (idx / queries.count.to_f * 100).ceil on_schema_inference_progressed(pct_complete: progress) all(where: queries[idx]) end self.inferred_schema = sch save on_schema_inference_finished sch end
ruby
def infer_schema(samples_count: 0, extended: false) if db_backend == :postgresql # Experimental sch = db_adapter.client.schema(read_dataset_name).to_h sch = sch.reject{ |k, v| k == :_id }.map { |k,v| [k, {type: v[:type].to_s}] }.to_h self.inferred_schema = sch save return sch end data_count = samples_count == 0 ? count : samples_count # invoked in the base class return {} if data_count == 0 # find out how many batches are needed max_per_process = 1000 max_per_process = limit_per_process if respond_to?(:limit_per_process) && limit_per_process > 0 equal_split_per_process = (data_count / Parallel.processor_count.to_f).ceil count_per_process = [max_per_process, equal_split_per_process].min queries = ordered_system_id_queries(batch_size: count_per_process)[0...data_count] self.inferred_schema_at = Time.now self.inferred_schema_from = samples_count on_schema_inference_started sch = schema_inferrer.infer_schema(batch_count: queries.count, extended: extended) do |idx| progress = (idx / queries.count.to_f * 100).ceil on_schema_inference_progressed(pct_complete: progress) all(where: queries[idx]) end self.inferred_schema = sch save on_schema_inference_finished sch end
[ "def", "infer_schema", "(", "samples_count", ":", "0", ",", "extended", ":", "false", ")", "if", "db_backend", "==", ":postgresql", "# Experimental", "sch", "=", "db_adapter", ".", "client", ".", "schema", "(", "read_dataset_name", ")", ".", "to_h", "sch", "=", "sch", ".", "reject", "{", "|", "k", ",", "v", "|", "k", "==", ":_id", "}", ".", "map", "{", "|", "k", ",", "v", "|", "[", "k", ",", "{", "type", ":", "v", "[", ":type", "]", ".", "to_s", "}", "]", "}", ".", "to_h", "self", ".", "inferred_schema", "=", "sch", "save", "return", "sch", "end", "data_count", "=", "samples_count", "==", "0", "?", "count", ":", "samples_count", "# invoked in the base class", "return", "{", "}", "if", "data_count", "==", "0", "# find out how many batches are needed", "max_per_process", "=", "1000", "max_per_process", "=", "limit_per_process", "if", "respond_to?", "(", ":limit_per_process", ")", "&&", "limit_per_process", ">", "0", "equal_split_per_process", "=", "(", "data_count", "/", "Parallel", ".", "processor_count", ".", "to_f", ")", ".", "ceil", "count_per_process", "=", "[", "max_per_process", ",", "equal_split_per_process", "]", ".", "min", "queries", "=", "ordered_system_id_queries", "(", "batch_size", ":", "count_per_process", ")", "[", "0", "...", "data_count", "]", "self", ".", "inferred_schema_at", "=", "Time", ".", "now", "self", ".", "inferred_schema_from", "=", "samples_count", "on_schema_inference_started", "sch", "=", "schema_inferrer", ".", "infer_schema", "(", "batch_count", ":", "queries", ".", "count", ",", "extended", ":", "extended", ")", "do", "|", "idx", "|", "progress", "=", "(", "idx", "/", "queries", ".", "count", ".", "to_f", "*", "100", ")", ".", "ceil", "on_schema_inference_progressed", "(", "pct_complete", ":", "progress", ")", "all", "(", "where", ":", "queries", "[", "idx", "]", ")", "end", "self", ".", "inferred_schema", "=", "sch", "save", "on_schema_inference_finished", "sch", "end" ]
if this change, update the regex that use the character directly in this mixin Generate a schema based on this collection's records. We evaluate the schema of each record and then merge all the information together. @param extended [Boolean] Set to true to keep each field as a basic type. Set to false to reduce the terminal arrays to a single key (under the type array). @return [Hash] with one entry per 'column'/'field'. The values contains information about the type and usage.
[ "if", "this", "change", "update", "the", "regex", "that", "use", "the", "character", "directly", "in", "this", "mixin", "Generate", "a", "schema", "based", "on", "this", "collection", "s", "records", ".", "We", "evaluate", "the", "schema", "of", "each", "record", "and", "then", "merge", "all", "the", "information", "together", "." ]
6cedf006983f6ed1c72ccff5104bd47de38dd4f3
https://github.com/Phybbit/dataflow-rb/blob/6cedf006983f6ed1c72ccff5104bd47de38dd4f3/lib/dataflow/schema_mixin.rb#L13-L51
785
mumuki/mumukit-assistant
lib/mumukit/assistant.rb
Mumukit.Assistant.assist_with
def assist_with(submission) @rules .select { |it| it.matches?(submission) } .map { |it| it.message_for(submission.attemps_count) } end
ruby
def assist_with(submission) @rules .select { |it| it.matches?(submission) } .map { |it| it.message_for(submission.attemps_count) } end
[ "def", "assist_with", "(", "submission", ")", "@rules", ".", "select", "{", "|", "it", "|", "it", ".", "matches?", "(", "submission", ")", "}", ".", "map", "{", "|", "it", "|", "it", ".", "message_for", "(", "submission", ".", "attemps_count", ")", "}", "end" ]
Provides tips for the student for the given submission, based on the `rules`.
[ "Provides", "tips", "for", "the", "student", "for", "the", "given", "submission", "based", "on", "the", "rules", "." ]
a776ec594a209f3d04fc918426297adf30504f25
https://github.com/mumuki/mumukit-assistant/blob/a776ec594a209f3d04fc918426297adf30504f25/lib/mumukit/assistant.rb#L21-L25
786
danielsdeleo/deep_merge
lib/deep_merge/rails_compat.rb
DeepMerge.RailsCompat.ko_deeper_merge!
def ko_deeper_merge!(source, options = {}) default_opts = {:knockout_prefix => "--", :preserve_unmergeables => false} DeepMerge::deep_merge!(source, self, default_opts.merge(options)) end
ruby
def ko_deeper_merge!(source, options = {}) default_opts = {:knockout_prefix => "--", :preserve_unmergeables => false} DeepMerge::deep_merge!(source, self, default_opts.merge(options)) end
[ "def", "ko_deeper_merge!", "(", "source", ",", "options", "=", "{", "}", ")", "default_opts", "=", "{", ":knockout_prefix", "=>", "\"--\"", ",", ":preserve_unmergeables", "=>", "false", "}", "DeepMerge", "::", "deep_merge!", "(", "source", ",", "self", ",", "default_opts", ".", "merge", "(", "options", ")", ")", "end" ]
ko_hash_merge! will merge and knockout elements prefixed with DEFAULT_FIELD_KNOCKOUT_PREFIX
[ "ko_hash_merge!", "will", "merge", "and", "knockout", "elements", "prefixed", "with", "DEFAULT_FIELD_KNOCKOUT_PREFIX" ]
9b15cc77c5954eebf67365d4f24ca44a9e2b2ca7
https://github.com/danielsdeleo/deep_merge/blob/9b15cc77c5954eebf67365d4f24ca44a9e2b2ca7/lib/deep_merge/rails_compat.rb#L6-L9
787
rails/activerecord-deprecated_finders
lib/active_record/deprecated_finders/base.rb
ActiveRecord.DeprecatedFinders.with_exclusive_scope
def with_exclusive_scope(method_scoping = {}, &block) if method_scoping.values.any? { |e| e.is_a?(ActiveRecord::Relation) } raise ArgumentError, <<-MSG New finder API can not be used with_exclusive_scope. You can either call unscoped to get an anonymous scope not bound to the default_scope: User.unscoped.where(:active => true) Or call unscoped with a block: User.unscoped do User.where(:active => true).all end MSG end with_scope(method_scoping, :overwrite, &block) end
ruby
def with_exclusive_scope(method_scoping = {}, &block) if method_scoping.values.any? { |e| e.is_a?(ActiveRecord::Relation) } raise ArgumentError, <<-MSG New finder API can not be used with_exclusive_scope. You can either call unscoped to get an anonymous scope not bound to the default_scope: User.unscoped.where(:active => true) Or call unscoped with a block: User.unscoped do User.where(:active => true).all end MSG end with_scope(method_scoping, :overwrite, &block) end
[ "def", "with_exclusive_scope", "(", "method_scoping", "=", "{", "}", ",", "&", "block", ")", "if", "method_scoping", ".", "values", ".", "any?", "{", "|", "e", "|", "e", ".", "is_a?", "(", "ActiveRecord", "::", "Relation", ")", "}", "raise", "ArgumentError", ",", "<<-MSG", "MSG", "end", "with_scope", "(", "method_scoping", ",", ":overwrite", ",", "block", ")", "end" ]
Works like with_scope, but discards any nested properties.
[ "Works", "like", "with_scope", "but", "discards", "any", "nested", "properties", "." ]
041c83c9dce8e17b8e1216adfaff48cc9debac02
https://github.com/rails/activerecord-deprecated_finders/blob/041c83c9dce8e17b8e1216adfaff48cc9debac02/lib/active_record/deprecated_finders/base.rb#L124-L140
788
rdp/ruby_gnuplot
lib/gnuplot.rb
Gnuplot.Plot.set
def set ( var, value = "" ) value = "\"#{value}\"" if QUOTED.include? var unless value =~ /^'.*'$/ @settings << [ :set, var, value ] end
ruby
def set ( var, value = "" ) value = "\"#{value}\"" if QUOTED.include? var unless value =~ /^'.*'$/ @settings << [ :set, var, value ] end
[ "def", "set", "(", "var", ",", "value", "=", "\"\"", ")", "value", "=", "\"\\\"#{value}\\\"\"", "if", "QUOTED", ".", "include?", "var", "unless", "value", "=~", "/", "/", "@settings", "<<", "[", ":set", ",", "var", ",", "value", "]", "end" ]
Set a variable to the given value. +Var+ must be a gnuplot variable and +value+ must be the value to set it to. Automatic quoting will be performed if the variable requires it. This is overloaded by the +method_missing+ method so see that for more readable code.
[ "Set", "a", "variable", "to", "the", "given", "value", ".", "+", "Var", "+", "must", "be", "a", "gnuplot", "variable", "and", "+", "value", "+", "must", "be", "the", "value", "to", "set", "it", "to", ".", "Automatic", "quoting", "will", "be", "performed", "if", "the", "variable", "requires", "it", "." ]
79eb51b46ae1a659292d3d4cc15c8a0e321a1c3e
https://github.com/rdp/ruby_gnuplot/blob/79eb51b46ae1a659292d3d4cc15c8a0e321a1c3e/lib/gnuplot.rb#L127-L130
789
potatosalad/ruby-jose
lib/jose/jwt.rb
JOSE.JWT.merge
def merge(object) object = case object when JOSE::Map, Hash object when String JOSE.decode(object) when JOSE::JWT object.to_map else raise ArgumentError, "'object' must be a Hash, String, or JOSE::JWT" end return JOSE::JWT.from_map(self.to_map.merge(object)) end
ruby
def merge(object) object = case object when JOSE::Map, Hash object when String JOSE.decode(object) when JOSE::JWT object.to_map else raise ArgumentError, "'object' must be a Hash, String, or JOSE::JWT" end return JOSE::JWT.from_map(self.to_map.merge(object)) end
[ "def", "merge", "(", "object", ")", "object", "=", "case", "object", "when", "JOSE", "::", "Map", ",", "Hash", "object", "when", "String", "JOSE", ".", "decode", "(", "object", ")", "when", "JOSE", "::", "JWT", "object", ".", "to_map", "else", "raise", "ArgumentError", ",", "\"'object' must be a Hash, String, or JOSE::JWT\"", "end", "return", "JOSE", "::", "JWT", ".", "from_map", "(", "self", ".", "to_map", ".", "merge", "(", "object", ")", ")", "end" ]
Merges object into current map. @param [JOSE::Map, Hash, String, JOSE::JWT] object @return [JOSE::JWT]
[ "Merges", "object", "into", "current", "map", "." ]
e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0
https://github.com/potatosalad/ruby-jose/blob/e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0/lib/jose/jwt.rb#L243-L255
790
potatosalad/ruby-jose
lib/jose/jwk.rb
JOSE.JWK.block_encrypt
def block_encrypt(plain_text, jwe = nil) jwe ||= block_encryptor return JOSE::JWE.block_encrypt(self, plain_text, jwe) end
ruby
def block_encrypt(plain_text, jwe = nil) jwe ||= block_encryptor return JOSE::JWE.block_encrypt(self, plain_text, jwe) end
[ "def", "block_encrypt", "(", "plain_text", ",", "jwe", "=", "nil", ")", "jwe", "||=", "block_encryptor", "return", "JOSE", "::", "JWE", ".", "block_encrypt", "(", "self", ",", "plain_text", ",", "jwe", ")", "end" ]
Encrypts the `plain_text` using the `jwk` and algorithms specified by the `jwe`. @see JOSE::JWE.block_encrypt @param [String] plain_text @param [JOSE::JWE] jwe @return [JOSE::EncryptedMap]
[ "Encrypts", "the", "plain_text", "using", "the", "jwk", "and", "algorithms", "specified", "by", "the", "jwe", "." ]
e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0
https://github.com/potatosalad/ruby-jose/blob/e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0/lib/jose/jwk.rb#L644-L647
791
potatosalad/ruby-jose
lib/jose/jwk.rb
JOSE.JWK.box_decrypt
def box_decrypt(encrypted, public_jwk = nil) if public_jwk return JOSE::JWE.block_decrypt([public_jwk, self], encrypted) else return JOSE::JWE.block_decrypt(self, encrypted) end end
ruby
def box_decrypt(encrypted, public_jwk = nil) if public_jwk return JOSE::JWE.block_decrypt([public_jwk, self], encrypted) else return JOSE::JWE.block_decrypt(self, encrypted) end end
[ "def", "box_decrypt", "(", "encrypted", ",", "public_jwk", "=", "nil", ")", "if", "public_jwk", "return", "JOSE", "::", "JWE", ".", "block_decrypt", "(", "[", "public_jwk", ",", "self", "]", ",", "encrypted", ")", "else", "return", "JOSE", "::", "JWE", ".", "block_decrypt", "(", "self", ",", "encrypted", ")", "end", "end" ]
Key Agreement decryption of the `encrypted` binary or map using `my_private_jwk`. @see JOSE::JWK.box_encrypt @see JOSE::JWE.block_decrypt @param [JOSE::EncryptedBinary, JOSE::EncryptedMap] encrypted @param [JOSE::JWK] public_jwk @return [[String, JOSE::JWE]]
[ "Key", "Agreement", "decryption", "of", "the", "encrypted", "binary", "or", "map", "using", "my_private_jwk", "." ]
e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0
https://github.com/potatosalad/ruby-jose/blob/e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0/lib/jose/jwk.rb#L687-L693
792
potatosalad/ruby-jose
lib/jose/jwk.rb
JOSE.JWK.box_encrypt
def box_encrypt(plain_text, jwk_secret = nil, jwe = nil) epk_secret = nil jwk_public = self if jwk_secret.nil? epk_secret = jwk_secret = jwk_public.generate_key end if not jwk_secret.is_a?(JOSE::JWK) jwk_secret = JOSE::JWK.from(jwk_secret) end if jwe.nil? jwe = jwk_public.block_encryptor end if jwe.is_a?(Hash) jwe = JOSE::Map.new(jwe) end if jwe.is_a?(JOSE::Map) if jwe['apu'].nil? jwe = jwe.put('apu', jwk_secret.fields['kid'] || jwk_secret.thumbprint) end if jwe['apv'].nil? jwe = jwe.put('apv', jwk_public.fields['kid'] || jwk_public.thumbprint) end if jwe['epk'].nil? jwe = jwe.put('epk', jwk_secret.to_public_map) end end if epk_secret return JOSE::JWE.block_encrypt([jwk_public, jwk_secret], plain_text, jwe), epk_secret else return JOSE::JWE.block_encrypt([jwk_public, jwk_secret], plain_text, jwe) end end
ruby
def box_encrypt(plain_text, jwk_secret = nil, jwe = nil) epk_secret = nil jwk_public = self if jwk_secret.nil? epk_secret = jwk_secret = jwk_public.generate_key end if not jwk_secret.is_a?(JOSE::JWK) jwk_secret = JOSE::JWK.from(jwk_secret) end if jwe.nil? jwe = jwk_public.block_encryptor end if jwe.is_a?(Hash) jwe = JOSE::Map.new(jwe) end if jwe.is_a?(JOSE::Map) if jwe['apu'].nil? jwe = jwe.put('apu', jwk_secret.fields['kid'] || jwk_secret.thumbprint) end if jwe['apv'].nil? jwe = jwe.put('apv', jwk_public.fields['kid'] || jwk_public.thumbprint) end if jwe['epk'].nil? jwe = jwe.put('epk', jwk_secret.to_public_map) end end if epk_secret return JOSE::JWE.block_encrypt([jwk_public, jwk_secret], plain_text, jwe), epk_secret else return JOSE::JWE.block_encrypt([jwk_public, jwk_secret], plain_text, jwe) end end
[ "def", "box_encrypt", "(", "plain_text", ",", "jwk_secret", "=", "nil", ",", "jwe", "=", "nil", ")", "epk_secret", "=", "nil", "jwk_public", "=", "self", "if", "jwk_secret", ".", "nil?", "epk_secret", "=", "jwk_secret", "=", "jwk_public", ".", "generate_key", "end", "if", "not", "jwk_secret", ".", "is_a?", "(", "JOSE", "::", "JWK", ")", "jwk_secret", "=", "JOSE", "::", "JWK", ".", "from", "(", "jwk_secret", ")", "end", "if", "jwe", ".", "nil?", "jwe", "=", "jwk_public", ".", "block_encryptor", "end", "if", "jwe", ".", "is_a?", "(", "Hash", ")", "jwe", "=", "JOSE", "::", "Map", ".", "new", "(", "jwe", ")", "end", "if", "jwe", ".", "is_a?", "(", "JOSE", "::", "Map", ")", "if", "jwe", "[", "'apu'", "]", ".", "nil?", "jwe", "=", "jwe", ".", "put", "(", "'apu'", ",", "jwk_secret", ".", "fields", "[", "'kid'", "]", "||", "jwk_secret", ".", "thumbprint", ")", "end", "if", "jwe", "[", "'apv'", "]", ".", "nil?", "jwe", "=", "jwe", ".", "put", "(", "'apv'", ",", "jwk_public", ".", "fields", "[", "'kid'", "]", "||", "jwk_public", ".", "thumbprint", ")", "end", "if", "jwe", "[", "'epk'", "]", ".", "nil?", "jwe", "=", "jwe", ".", "put", "(", "'epk'", ",", "jwk_secret", ".", "to_public_map", ")", "end", "end", "if", "epk_secret", "return", "JOSE", "::", "JWE", ".", "block_encrypt", "(", "[", "jwk_public", ",", "jwk_secret", "]", ",", "plain_text", ",", "jwe", ")", ",", "epk_secret", "else", "return", "JOSE", "::", "JWE", ".", "block_encrypt", "(", "[", "jwk_public", ",", "jwk_secret", "]", ",", "plain_text", ",", "jwe", ")", "end", "end" ]
Key Agreement encryption of `plain_text` by generating an ephemeral private key based on `other_public_jwk` curve. If no private key has been specified in `my_private_key`, it generates an ephemeral private key based on other public key curve. @see JOSE::JWK.box_decrypt @see JOSE::JWE.block_encrypt @param [String] plain_text @param [JOSE::JWK] jwk_secret @param [JOSE::JWE] jwe @return [JOSE::EncryptedMap, [JOSE::EncryptedMap, JOSE::JWK]]
[ "Key", "Agreement", "encryption", "of", "plain_text", "by", "generating", "an", "ephemeral", "private", "key", "based", "on", "other_public_jwk", "curve", "." ]
e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0
https://github.com/potatosalad/ruby-jose/blob/e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0/lib/jose/jwk.rb#L720-L751
793
potatosalad/ruby-jose
lib/jose/jwk.rb
JOSE.JWK.shared_secret
def shared_secret(other_jwk) other_jwk = from(other_jwk) if not other_jwk.is_a?(JOSE::JWK) raise ArgumentError, "key types must match" if other_jwk.kty.class != kty.class raise ArgumentError, "key type does not support shared secret computations" if not kty.respond_to?(:derive_key) return kty.derive_key(other_jwk) end
ruby
def shared_secret(other_jwk) other_jwk = from(other_jwk) if not other_jwk.is_a?(JOSE::JWK) raise ArgumentError, "key types must match" if other_jwk.kty.class != kty.class raise ArgumentError, "key type does not support shared secret computations" if not kty.respond_to?(:derive_key) return kty.derive_key(other_jwk) end
[ "def", "shared_secret", "(", "other_jwk", ")", "other_jwk", "=", "from", "(", "other_jwk", ")", "if", "not", "other_jwk", ".", "is_a?", "(", "JOSE", "::", "JWK", ")", "raise", "ArgumentError", ",", "\"key types must match\"", "if", "other_jwk", ".", "kty", ".", "class", "!=", "kty", ".", "class", "raise", "ArgumentError", ",", "\"key type does not support shared secret computations\"", "if", "not", "kty", ".", "respond_to?", "(", ":derive_key", ")", "return", "kty", ".", "derive_key", "(", "other_jwk", ")", "end" ]
Computes the shared secret between two keys. Currently only works for `"EC"` keys and `"OKP"` keys with `"crv"` set to `"X25519"` or `"X448"`. @param [JOSE::JWK] other_jwk @return [String]
[ "Computes", "the", "shared", "secret", "between", "two", "keys", "." ]
e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0
https://github.com/potatosalad/ruby-jose/blob/e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0/lib/jose/jwk.rb#L875-L880
794
potatosalad/ruby-jose
lib/jose/jwk.rb
JOSE.JWK.sign
def sign(plain_text, jws = nil, header = nil) jws ||= signer return JOSE::JWS.sign(self, plain_text, jws, header) end
ruby
def sign(plain_text, jws = nil, header = nil) jws ||= signer return JOSE::JWS.sign(self, plain_text, jws, header) end
[ "def", "sign", "(", "plain_text", ",", "jws", "=", "nil", ",", "header", "=", "nil", ")", "jws", "||=", "signer", "return", "JOSE", "::", "JWS", ".", "sign", "(", "self", ",", "plain_text", ",", "jws", ",", "header", ")", "end" ]
Signs the `plain_text` using the `jwk` and the default signer algorithm `jws` for the key type. @see JOSE::JWS.sign @param [String] plain_text @param [JOSE::JWS] jws @param [JOSE::Map] header @return [JOSE::SignedMap]
[ "Signs", "the", "plain_text", "using", "the", "jwk", "and", "the", "default", "signer", "algorithm", "jws", "for", "the", "key", "type", "." ]
e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0
https://github.com/potatosalad/ruby-jose/blob/e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0/lib/jose/jwk.rb#L905-L908
795
potatosalad/ruby-jose
lib/jose/jws.rb
JOSE.JWS.sign
def sign(jwk, plain_text, header = nil) protected_binary = JOSE.urlsafe_encode64(to_binary) payload = JOSE.urlsafe_encode64(plain_text) signing_input = signing_input(plain_text, protected_binary) signature = JOSE.urlsafe_encode64(alg.sign(jwk, signing_input)) return signature_to_map(payload, protected_binary, header, jwk, signature) end
ruby
def sign(jwk, plain_text, header = nil) protected_binary = JOSE.urlsafe_encode64(to_binary) payload = JOSE.urlsafe_encode64(plain_text) signing_input = signing_input(plain_text, protected_binary) signature = JOSE.urlsafe_encode64(alg.sign(jwk, signing_input)) return signature_to_map(payload, protected_binary, header, jwk, signature) end
[ "def", "sign", "(", "jwk", ",", "plain_text", ",", "header", "=", "nil", ")", "protected_binary", "=", "JOSE", ".", "urlsafe_encode64", "(", "to_binary", ")", "payload", "=", "JOSE", ".", "urlsafe_encode64", "(", "plain_text", ")", "signing_input", "=", "signing_input", "(", "plain_text", ",", "protected_binary", ")", "signature", "=", "JOSE", ".", "urlsafe_encode64", "(", "alg", ".", "sign", "(", "jwk", ",", "signing_input", ")", ")", "return", "signature_to_map", "(", "payload", ",", "protected_binary", ",", "header", ",", "jwk", ",", "signature", ")", "end" ]
Signs the `plain_text` using the `jwk` and algorithm specified by the `jws`. @see JOSE::JWS.sign @param [JOSE::JWK] jwk @param [String] plain_text @param [JOSE::Map, Hash] header @return [JOSE::SignedMap]
[ "Signs", "the", "plain_text", "using", "the", "jwk", "and", "algorithm", "specified", "by", "the", "jws", "." ]
e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0
https://github.com/potatosalad/ruby-jose/blob/e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0/lib/jose/jws.rb#L572-L578
796
potatosalad/ruby-jose
lib/jose/jws.rb
JOSE.JWS.verify
def verify(jwk, plain_text, signature, protected_binary = nil) protected_binary ||= JOSE.urlsafe_encode64(to_binary) signing_input = signing_input(plain_text, protected_binary) return alg.verify(jwk, signing_input, signature), plain_text, self end
ruby
def verify(jwk, plain_text, signature, protected_binary = nil) protected_binary ||= JOSE.urlsafe_encode64(to_binary) signing_input = signing_input(plain_text, protected_binary) return alg.verify(jwk, signing_input, signature), plain_text, self end
[ "def", "verify", "(", "jwk", ",", "plain_text", ",", "signature", ",", "protected_binary", "=", "nil", ")", "protected_binary", "||=", "JOSE", ".", "urlsafe_encode64", "(", "to_binary", ")", "signing_input", "=", "signing_input", "(", "plain_text", ",", "protected_binary", ")", "return", "alg", ".", "verify", "(", "jwk", ",", "signing_input", ",", "signature", ")", ",", "plain_text", ",", "self", "end" ]
Verifies the `signature` using the `jwk`, `plain_text`, and `protected_binary`. @see JOSE::JWS.verify @see JOSE::JWS.verify_strict @param [JOSE::JWK] jwk @param [String] plain_text @param [String] signature @param [String] protected_binary @return [[Boolean, String, JOSE::JWS]]
[ "Verifies", "the", "signature", "using", "the", "jwk", "plain_text", "and", "protected_binary", "." ]
e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0
https://github.com/potatosalad/ruby-jose/blob/e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0/lib/jose/jws.rb#L645-L649
797
potatosalad/ruby-jose
lib/jose/jwa.rb
JOSE.JWA.supports
def supports jwe_enc = __jwe_enc_support_check__([ 'A128GCM', 'A192GCM', 'A256GCM', 'A128CBC-HS256', 'A192CBC-HS384', 'A256CBC-HS512' ]) jwe_alg = __jwe_alg_support_check__([ ['A128GCMKW', :block], ['A192GCMKW', :block], ['A256GCMKW', :block], ['A128KW', :block], ['A192KW', :block], ['A256KW', :block], ['ECDH-ES', :box], ['ECDH-ES+A128KW', :box], ['ECDH-ES+A192KW', :box], ['ECDH-ES+A256KW', :box], ['PBES2-HS256+A128KW', :block], ['PBES2-HS384+A192KW', :block], ['PBES2-HS512+A256KW', :block], ['RSA1_5', :rsa], ['RSA-OAEP', :rsa], ['RSA-OAEP-256', :rsa], ['dir', :direct] ], jwe_enc) jwe_zip = __jwe_zip_support_check__([ 'DEF' ], jwe_enc) jwk_kty, jwk_kty_EC_crv, jwk_kty_OKP_crv = __jwk_kty_support_check__([ ['EC', ['P-256', 'P-384', 'P-521']], ['OKP', ['Ed25519', 'Ed25519ph', 'Ed448', 'Ed448ph', 'X25519', 'X448']], 'RSA', 'oct' ]) jws_alg = __jws_alg_support_check__([ 'Ed25519', 'Ed25519ph', 'Ed448', 'Ed448ph', 'EdDSA', 'ES256', 'ES384', 'ES512', 'HS256', 'HS384', 'HS512', 'PS256', 'PS384', 'PS512', 'RS256', 'RS384', 'RS512', 'X25519', 'X448', 'none' ]) return { jwe: { alg: jwe_alg, enc: jwe_enc, zip: jwe_zip }, jwk: { kty: jwk_kty, kty_EC_crv: jwk_kty_EC_crv, kty_OKP_crv: jwk_kty_OKP_crv }, jws: { alg: jws_alg } } end
ruby
def supports jwe_enc = __jwe_enc_support_check__([ 'A128GCM', 'A192GCM', 'A256GCM', 'A128CBC-HS256', 'A192CBC-HS384', 'A256CBC-HS512' ]) jwe_alg = __jwe_alg_support_check__([ ['A128GCMKW', :block], ['A192GCMKW', :block], ['A256GCMKW', :block], ['A128KW', :block], ['A192KW', :block], ['A256KW', :block], ['ECDH-ES', :box], ['ECDH-ES+A128KW', :box], ['ECDH-ES+A192KW', :box], ['ECDH-ES+A256KW', :box], ['PBES2-HS256+A128KW', :block], ['PBES2-HS384+A192KW', :block], ['PBES2-HS512+A256KW', :block], ['RSA1_5', :rsa], ['RSA-OAEP', :rsa], ['RSA-OAEP-256', :rsa], ['dir', :direct] ], jwe_enc) jwe_zip = __jwe_zip_support_check__([ 'DEF' ], jwe_enc) jwk_kty, jwk_kty_EC_crv, jwk_kty_OKP_crv = __jwk_kty_support_check__([ ['EC', ['P-256', 'P-384', 'P-521']], ['OKP', ['Ed25519', 'Ed25519ph', 'Ed448', 'Ed448ph', 'X25519', 'X448']], 'RSA', 'oct' ]) jws_alg = __jws_alg_support_check__([ 'Ed25519', 'Ed25519ph', 'Ed448', 'Ed448ph', 'EdDSA', 'ES256', 'ES384', 'ES512', 'HS256', 'HS384', 'HS512', 'PS256', 'PS384', 'PS512', 'RS256', 'RS384', 'RS512', 'X25519', 'X448', 'none' ]) return { jwe: { alg: jwe_alg, enc: jwe_enc, zip: jwe_zip }, jwk: { kty: jwk_kty, kty_EC_crv: jwk_kty_EC_crv, kty_OKP_crv: jwk_kty_OKP_crv }, jws: { alg: jws_alg } } end
[ "def", "supports", "jwe_enc", "=", "__jwe_enc_support_check__", "(", "[", "'A128GCM'", ",", "'A192GCM'", ",", "'A256GCM'", ",", "'A128CBC-HS256'", ",", "'A192CBC-HS384'", ",", "'A256CBC-HS512'", "]", ")", "jwe_alg", "=", "__jwe_alg_support_check__", "(", "[", "[", "'A128GCMKW'", ",", ":block", "]", ",", "[", "'A192GCMKW'", ",", ":block", "]", ",", "[", "'A256GCMKW'", ",", ":block", "]", ",", "[", "'A128KW'", ",", ":block", "]", ",", "[", "'A192KW'", ",", ":block", "]", ",", "[", "'A256KW'", ",", ":block", "]", ",", "[", "'ECDH-ES'", ",", ":box", "]", ",", "[", "'ECDH-ES+A128KW'", ",", ":box", "]", ",", "[", "'ECDH-ES+A192KW'", ",", ":box", "]", ",", "[", "'ECDH-ES+A256KW'", ",", ":box", "]", ",", "[", "'PBES2-HS256+A128KW'", ",", ":block", "]", ",", "[", "'PBES2-HS384+A192KW'", ",", ":block", "]", ",", "[", "'PBES2-HS512+A256KW'", ",", ":block", "]", ",", "[", "'RSA1_5'", ",", ":rsa", "]", ",", "[", "'RSA-OAEP'", ",", ":rsa", "]", ",", "[", "'RSA-OAEP-256'", ",", ":rsa", "]", ",", "[", "'dir'", ",", ":direct", "]", "]", ",", "jwe_enc", ")", "jwe_zip", "=", "__jwe_zip_support_check__", "(", "[", "'DEF'", "]", ",", "jwe_enc", ")", "jwk_kty", ",", "jwk_kty_EC_crv", ",", "jwk_kty_OKP_crv", "=", "__jwk_kty_support_check__", "(", "[", "[", "'EC'", ",", "[", "'P-256'", ",", "'P-384'", ",", "'P-521'", "]", "]", ",", "[", "'OKP'", ",", "[", "'Ed25519'", ",", "'Ed25519ph'", ",", "'Ed448'", ",", "'Ed448ph'", ",", "'X25519'", ",", "'X448'", "]", "]", ",", "'RSA'", ",", "'oct'", "]", ")", "jws_alg", "=", "__jws_alg_support_check__", "(", "[", "'Ed25519'", ",", "'Ed25519ph'", ",", "'Ed448'", ",", "'Ed448ph'", ",", "'EdDSA'", ",", "'ES256'", ",", "'ES384'", ",", "'ES512'", ",", "'HS256'", ",", "'HS384'", ",", "'HS512'", ",", "'PS256'", ",", "'PS384'", ",", "'PS512'", ",", "'RS256'", ",", "'RS384'", ",", "'RS512'", ",", "'X25519'", ",", "'X448'", ",", "'none'", "]", ")", "return", "{", "jwe", ":", "{", "alg", ":", "jwe_alg", ",", "enc", ":", "jwe_enc", ",", "zip", ":", "jwe_zip", "}", ",", "jwk", ":", "{", "kty", ":", "jwk_kty", ",", "kty_EC_crv", ":", "jwk_kty_EC_crv", ",", "kty_OKP_crv", ":", "jwk_kty_OKP_crv", "}", ",", "jws", ":", "{", "alg", ":", "jws_alg", "}", "}", "end" ]
Returns the current listing of supported JOSE algorithms. !!!ruby JOSE::JWA.supports # => {:jwe=> # {:alg=> # ["A128GCMKW", # "A192GCMKW", # "A256GCMKW", # "A128KW", # "A192KW", # "A256KW", # "ECDH-ES", # "ECDH-ES+A128KW", # "ECDH-ES+A192KW", # "ECDH-ES+A256KW", # "PBES2-HS256+A128KW", # "PBES2-HS384+A192KW", # "PBES2-HS512+A256KW", # "RSA1_5", # "RSA-OAEP", # "RSA-OAEP-256", # "dir"], # :enc=> # ["A128GCM", # "A192GCM", # "A256GCM", # "A128CBC-HS256", # "A192CBC-HS384", # "A256CBC-HS512"], # :zip=> # ["DEF"]}, # :jwk=> # {:kty=> # ["EC", # "OKP", # "RSA", # "oct"], # :kty_EC_crv=> # ["P-256", # "P-384", # "P-521"], # :kty_OKP_crv=> # ["Ed25519", # "Ed25519ph", # "Ed448", # "Ed448ph", # "X25519", # "X448"]}, # :jws=> # {:alg=> # ["Ed25519", # "Ed25519ph", # "Ed448", # "Ed448ph", # "EdDSA", # "ES256", # "ES384", # "ES512", # "HS256", # "HS384", # "HS512", # "PS256", # "PS384", # "PS512", # "RS256", # "RS384", # "RS512", # "none"]}} @return [Hash]
[ "Returns", "the", "current", "listing", "of", "supported", "JOSE", "algorithms", "." ]
e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0
https://github.com/potatosalad/ruby-jose/blob/e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0/lib/jose/jwa.rb#L123-L197
798
potatosalad/ruby-jose
lib/jose/jwe.rb
JOSE.JWE.block_decrypt
def block_decrypt(key, aad, cipher_text, cipher_tag, encrypted_key, iv) cek = key_decrypt(key, encrypted_key) return uncompress(enc.block_decrypt([aad, cipher_text, cipher_tag], cek, iv)) end
ruby
def block_decrypt(key, aad, cipher_text, cipher_tag, encrypted_key, iv) cek = key_decrypt(key, encrypted_key) return uncompress(enc.block_decrypt([aad, cipher_text, cipher_tag], cek, iv)) end
[ "def", "block_decrypt", "(", "key", ",", "aad", ",", "cipher_text", ",", "cipher_tag", ",", "encrypted_key", ",", "iv", ")", "cek", "=", "key_decrypt", "(", "key", ",", "encrypted_key", ")", "return", "uncompress", "(", "enc", ".", "block_decrypt", "(", "[", "aad", ",", "cipher_text", ",", "cipher_tag", "]", ",", "cek", ",", "iv", ")", ")", "end" ]
Decrypts the `cipher_text` binary using the `key`, `aad`, `cipher_tag`, `encrypted_key`, and `iv`. @see JOSE::JWE.block_decrypt @param [JOSE::JWK, [JOSE::JWK, JOSE::JWK]] key @param [String] aad @param [String] cipher_text @param [String] cipher_tag @param [String] encrypted_key @param [String] iv @return [[String, JOSE::JWE]]
[ "Decrypts", "the", "cipher_text", "binary", "using", "the", "key", "aad", "cipher_tag", "encrypted_key", "and", "iv", "." ]
e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0
https://github.com/potatosalad/ruby-jose/blob/e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0/lib/jose/jwe.rb#L600-L603
799
potatosalad/ruby-jose
lib/jose/jwe.rb
JOSE.JWE.block_encrypt
def block_encrypt(key, block, cek = nil, iv = nil) jwe = self if cek.nil? cek, jwe = next_cek(key) end iv ||= jwe.next_iv aad, plain_text = block if plain_text.nil? plain_text = aad aad = nil end encrypted_key, jwe = jwe.key_encrypt(key, cek) protected_binary = JOSE.urlsafe_encode64(jwe.to_binary) if aad.nil? cipher_text, cipher_tag = enc.block_encrypt([protected_binary, jwe.compress(plain_text)], cek, iv) return JOSE::EncryptedMap[ 'ciphertext' => JOSE.urlsafe_encode64(cipher_text), 'encrypted_key' => JOSE.urlsafe_encode64(encrypted_key), 'iv' => JOSE.urlsafe_encode64(iv), 'protected' => protected_binary, 'tag' => JOSE.urlsafe_encode64(cipher_tag) ] else aad_b64 = JOSE.urlsafe_encode64(aad) concat_aad = [protected_binary, '.', aad_b64].join cipher_text, cipher_tag = enc.block_encrypt([concat_aad, jwe.compress(plain_text)], cek, iv) return JOSE::EncryptedMap[ 'aad' => aad_b64, 'ciphertext' => JOSE.urlsafe_encode64(cipher_text), 'encrypted_key' => JOSE.urlsafe_encode64(encrypted_key), 'iv' => JOSE.urlsafe_encode64(iv), 'protected' => protected_binary, 'tag' => JOSE.urlsafe_encode64(cipher_tag) ] end end
ruby
def block_encrypt(key, block, cek = nil, iv = nil) jwe = self if cek.nil? cek, jwe = next_cek(key) end iv ||= jwe.next_iv aad, plain_text = block if plain_text.nil? plain_text = aad aad = nil end encrypted_key, jwe = jwe.key_encrypt(key, cek) protected_binary = JOSE.urlsafe_encode64(jwe.to_binary) if aad.nil? cipher_text, cipher_tag = enc.block_encrypt([protected_binary, jwe.compress(plain_text)], cek, iv) return JOSE::EncryptedMap[ 'ciphertext' => JOSE.urlsafe_encode64(cipher_text), 'encrypted_key' => JOSE.urlsafe_encode64(encrypted_key), 'iv' => JOSE.urlsafe_encode64(iv), 'protected' => protected_binary, 'tag' => JOSE.urlsafe_encode64(cipher_tag) ] else aad_b64 = JOSE.urlsafe_encode64(aad) concat_aad = [protected_binary, '.', aad_b64].join cipher_text, cipher_tag = enc.block_encrypt([concat_aad, jwe.compress(plain_text)], cek, iv) return JOSE::EncryptedMap[ 'aad' => aad_b64, 'ciphertext' => JOSE.urlsafe_encode64(cipher_text), 'encrypted_key' => JOSE.urlsafe_encode64(encrypted_key), 'iv' => JOSE.urlsafe_encode64(iv), 'protected' => protected_binary, 'tag' => JOSE.urlsafe_encode64(cipher_tag) ] end end
[ "def", "block_encrypt", "(", "key", ",", "block", ",", "cek", "=", "nil", ",", "iv", "=", "nil", ")", "jwe", "=", "self", "if", "cek", ".", "nil?", "cek", ",", "jwe", "=", "next_cek", "(", "key", ")", "end", "iv", "||=", "jwe", ".", "next_iv", "aad", ",", "plain_text", "=", "block", "if", "plain_text", ".", "nil?", "plain_text", "=", "aad", "aad", "=", "nil", "end", "encrypted_key", ",", "jwe", "=", "jwe", ".", "key_encrypt", "(", "key", ",", "cek", ")", "protected_binary", "=", "JOSE", ".", "urlsafe_encode64", "(", "jwe", ".", "to_binary", ")", "if", "aad", ".", "nil?", "cipher_text", ",", "cipher_tag", "=", "enc", ".", "block_encrypt", "(", "[", "protected_binary", ",", "jwe", ".", "compress", "(", "plain_text", ")", "]", ",", "cek", ",", "iv", ")", "return", "JOSE", "::", "EncryptedMap", "[", "'ciphertext'", "=>", "JOSE", ".", "urlsafe_encode64", "(", "cipher_text", ")", ",", "'encrypted_key'", "=>", "JOSE", ".", "urlsafe_encode64", "(", "encrypted_key", ")", ",", "'iv'", "=>", "JOSE", ".", "urlsafe_encode64", "(", "iv", ")", ",", "'protected'", "=>", "protected_binary", ",", "'tag'", "=>", "JOSE", ".", "urlsafe_encode64", "(", "cipher_tag", ")", "]", "else", "aad_b64", "=", "JOSE", ".", "urlsafe_encode64", "(", "aad", ")", "concat_aad", "=", "[", "protected_binary", ",", "'.'", ",", "aad_b64", "]", ".", "join", "cipher_text", ",", "cipher_tag", "=", "enc", ".", "block_encrypt", "(", "[", "concat_aad", ",", "jwe", ".", "compress", "(", "plain_text", ")", "]", ",", "cek", ",", "iv", ")", "return", "JOSE", "::", "EncryptedMap", "[", "'aad'", "=>", "aad_b64", ",", "'ciphertext'", "=>", "JOSE", ".", "urlsafe_encode64", "(", "cipher_text", ")", ",", "'encrypted_key'", "=>", "JOSE", ".", "urlsafe_encode64", "(", "encrypted_key", ")", ",", "'iv'", "=>", "JOSE", ".", "urlsafe_encode64", "(", "iv", ")", ",", "'protected'", "=>", "protected_binary", ",", "'tag'", "=>", "JOSE", ".", "urlsafe_encode64", "(", "cipher_tag", ")", "]", "end", "end" ]
Encrypts the `block` binary using the `key`, `cek`, and `iv`. @see JOSE::JWE.block_encrypt @param [JOSE::JWK, [JOSE::JWK, JOSE::JWK]] key @param [String, [String, String]] block @param [String] cek @param [String] iv @return [JOSE::EncryptedMap]
[ "Encrypts", "the", "block", "binary", "using", "the", "key", "cek", "and", "iv", "." ]
e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0
https://github.com/potatosalad/ruby-jose/blob/e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0/lib/jose/jwe.rb#L639-L674