_id
stringlengths 2
6
| title
stringlengths 9
130
| partition
stringclasses 3
values | text
stringlengths 66
10.5k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q700 | RightScale.PlannedVolume.is_valid? | train | 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 | {
"resource": ""
} |
q701 | RightScale.Agent.run | train | 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 | {
"resource": ""
} |
q702 | RightScale.Agent.connect | train | 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 | {
"resource": ""
} |
q703 | RightScale.Agent.disconnect | train | 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 | {
"resource": ""
} |
q704 | RightScale.Agent.connect_failed | train | 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 | {
"resource": ""
} |
q705 | RightScale.Agent.terminate | train | 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 | {
"resource": ""
} |
q706 | RightScale.Agent.stats | train | 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 | {
"resource": ""
} |
q707 | RightScale.Agent.agent_stats | train | 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 | {
"resource": ""
} |
q708 | RightScale.Agent.reset_agent_stats | train | 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 | {
"resource": ""
} |
q709 | RightScale.Agent.set_configuration | train | 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 | {
"resource": ""
} |
q710 | RightScale.Agent.handle_event | train | 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 | {
"resource": ""
} |
q711 | RightScale.Agent.event_to_packet | train | 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 | {
"resource": ""
} |
q712 | RightScale.Agent.result_to_event | train | 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 | {
"resource": ""
} |
q713 | RightScale.Agent.create_dispatchers | train | 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 | {
"resource": ""
} |
q714 | RightScale.Agent.load_actors | train | 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 | {
"resource": ""
} |
q715 | RightScale.Agent.setup_http | train | 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 | {
"resource": ""
} |
q716 | RightScale.Agent.setup_status | train | 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 | {
"resource": ""
} |
q717 | RightScale.Agent.setup_non_delivery | train | 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 | {
"resource": ""
} |
q718 | RightScale.Agent.setup_queue | train | 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 | {
"resource": ""
} |
q719 | RightScale.Agent.handle_packet | train | 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 | {
"resource": ""
} |
q720 | RightScale.Agent.dispatch_request | train | 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 | {
"resource": ""
} |
q721 | RightScale.Agent.deliver_response | train | 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 | {
"resource": ""
} |
q722 | RightScale.Agent.finish_setup | train | 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 | {
"resource": ""
} |
q723 | RightScale.Agent.publish_stats | train | 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 | {
"resource": ""
} |
q724 | RightScale.Agent.stop_gracefully | train | 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 | {
"resource": ""
} |
q725 | RightScale.Agent.finish_terminating | train | 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 | {
"resource": ""
} |
q726 | RightScale.CommandClient.send_command | train | 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 | {
"resource": ""
} |
q727 | RightScale.PidFile.check | train | 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 | {
"resource": ""
} |
q728 | RightScale.PidFile.write | train | 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 | {
"resource": ""
} |
q729 | RightScale.PidFile.set_command_options | train | 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 | {
"resource": ""
} |
q730 | RightScale.PidFile.read_pid | train | 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 | {
"resource": ""
} |
q731 | RightScale.Packet.to_msgpack | train | 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 | {
"resource": ""
} |
q732 | RightScale.Packet.to_json | train | 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 | {
"resource": ""
} |
q733 | RightScale.Packet.enough_precision | train | 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 | {
"resource": ""
} |
q734 | RightScale.Packet.ids_to_s | train | 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 | {
"resource": ""
} |
q735 | RightScale.Packet.trace | train | 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 | {
"resource": ""
} |
q736 | RightScale.RouterClient.push | train | def push(type, payload, target, options = {})
params = {
:type => type,
:payload => payload,
:target => target }
make_request(:post, "/push", params, type.split("/")[2], options)
end | ruby | {
"resource": ""
} |
q737 | RightScale.RouterClient.request | train | def request(type, payload, target, options = {})
params = {
:type => type,
:payload => payload,
:target => target }
make_request(:post, "/request", params, type.split("/")[2], options)
end | ruby | {
"resource": ""
} |
q738 | RightScale.RouterClient.notify | train | 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 | {
"resource": ""
} |
q739 | RightScale.RouterClient.listen | train | 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 | {
"resource": ""
} |
q740 | RightScale.RouterClient.listen_loop | train | 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 | {
"resource": ""
} |
q741 | RightScale.RouterClient.listen_loop_wait | train | 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 | {
"resource": ""
} |
q742 | RightScale.RouterClient.update_listen_state | train | 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 | {
"resource": ""
} |
q743 | RightScale.RouterClient.try_connect | train | 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 | {
"resource": ""
} |
q744 | RightScale.RouterClient.connect | train | 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 | {
"resource": ""
} |
q745 | RightScale.RouterClient.try_long_poll | train | def try_long_poll(routing_keys, event_uuids, &handler)
begin
long_poll(routing_keys, event_uuids, &handler)
rescue Exception => e
e
end
end | ruby | {
"resource": ""
} |
q746 | RightScale.RouterClient.try_deferred_long_poll | train | 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 | {
"resource": ""
} |
q747 | RightScale.RouterClient.long_poll | train | 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 | {
"resource": ""
} |
q748 | RightScale.RouterClient.process_long_poll | train | 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 | {
"resource": ""
} |
q749 | RightScale.BaseRetryClient.init | train | 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 | {
"resource": ""
} |
q750 | RightScale.BaseRetryClient.create_http_client | train | 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 | {
"resource": ""
} |
q751 | RightScale.BaseRetryClient.close_http_client | train | 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 | {
"resource": ""
} |
q752 | RightScale.BaseRetryClient.check_health | train | 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 | {
"resource": ""
} |
q753 | RightScale.BaseRetryClient.reconnect | train | 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 | {
"resource": ""
} |
q754 | RightScale.BaseRetryClient.make_request | train | 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 | {
"resource": ""
} |
q755 | RightScale.BaseRetryClient.handle_exception | train | 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 | {
"resource": ""
} |
q756 | RightScale.BaseRetryClient.handle_redirect | train | 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 | {
"resource": ""
} |
q757 | RightScale.BaseRetryClient.handle_retry_with | train | 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 | {
"resource": ""
} |
q758 | RightScale.BaseRetryClient.handle_not_responding | train | 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 | {
"resource": ""
} |
q759 | RightScale.BaseRetryClient.retry_interval | train | 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 | {
"resource": ""
} |
q760 | RightScale.BaseRetryClient.wait | train | 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 | {
"resource": ""
} |
q761 | RightScale.RetryableRequest.handle_response | train | 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 | {
"resource": ""
} |
q762 | RightScale.SecureSerializer.dump | train | 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 | {
"resource": ""
} |
q763 | RightScale.SecureSerializer.load | train | 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 | {
"resource": ""
} |
q764 | RightScale.RightScriptAttachment.fill_out | train | 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 | {
"resource": ""
} |
q765 | RightScale.CommandParser.parse_chunk | train | 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 | {
"resource": ""
} |
q766 | RightScale.SpecHelper.issue_cert | train | 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 | {
"resource": ""
} |
q767 | RightScale.Dispatcher.dispatch | train | 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 | {
"resource": ""
} |
q768 | RightScale.Dispatcher.stats | train | 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 | {
"resource": ""
} |
q769 | RightScale.Dispatcher.expired? | train | 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 | {
"resource": ""
} |
q770 | RightScale.Dispatcher.duplicate? | train | 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 | {
"resource": ""
} |
q771 | RightScale.Dispatcher.route | train | 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 | {
"resource": ""
} |
q772 | RightScale.Dispatcher.perform | train | 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 | {
"resource": ""
} |
q773 | RightScale.Certificate.save | train | def save(file)
File.open(file, "w") do |f|
f.write(@raw_cert.to_pem)
end
true
end | ruby | {
"resource": ""
} |
q774 | RightScale.History.load | train | def load
events = []
File.open(@history, "r") { |f| events = f.readlines.map { |l| JSON.legacy_load(l) } } if File.readable?(@history)
events
end | ruby | {
"resource": ""
} |
q775 | RightScale.ApiClient.map_request | train | 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 | {
"resource": ""
} |
q776 | RightScale.ApiClient.map_response | train | 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 | {
"resource": ""
} |
q777 | RightScale.ApiClient.map_query_tags | train | 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 | {
"resource": ""
} |
q778 | RightScale.ApiClient.query_by_tag | train | 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 | {
"resource": ""
} |
q779 | RightScale.ApiClient.query_by_resource | train | 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 | {
"resource": ""
} |
q780 | RightScale.ApiClient.parameterize | train | 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 | {
"resource": ""
} |
q781 | RightScale.ApiClient.parameterize_audit | train | 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 | {
"resource": ""
} |
q782 | RightScale.ApiClient.truncate | train | 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 | {
"resource": ""
} |
q783 | Kirigami.Image.cut! | train | 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 | {
"resource": ""
} |
q784 | Dataflow.SchemaMixin.infer_schema | train | 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 | {
"resource": ""
} |
q785 | Mumukit.Assistant.assist_with | train | def assist_with(submission)
@rules
.select { |it| it.matches?(submission) }
.map { |it| it.message_for(submission.attemps_count) }
end | ruby | {
"resource": ""
} |
q786 | DeepMerge.RailsCompat.ko_deeper_merge! | train | def ko_deeper_merge!(source, options = {})
default_opts = {:knockout_prefix => "--", :preserve_unmergeables => false}
DeepMerge::deep_merge!(source, self, default_opts.merge(options))
end | ruby | {
"resource": ""
} |
q787 | ActiveRecord.DeprecatedFinders.with_exclusive_scope | train | 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 | {
"resource": ""
} |
q788 | Gnuplot.Plot.set | train | def set ( var, value = "" )
value = "\"#{value}\"" if QUOTED.include? var unless value =~ /^'.*'$/
@settings << [ :set, var, value ]
end | ruby | {
"resource": ""
} |
q789 | JOSE.JWT.merge | train | 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 | {
"resource": ""
} |
q790 | JOSE.JWK.block_encrypt | train | def block_encrypt(plain_text, jwe = nil)
jwe ||= block_encryptor
return JOSE::JWE.block_encrypt(self, plain_text, jwe)
end | ruby | {
"resource": ""
} |
q791 | JOSE.JWK.box_decrypt | train | 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 | {
"resource": ""
} |
q792 | JOSE.JWK.box_encrypt | train | 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 | {
"resource": ""
} |
q793 | JOSE.JWK.shared_secret | train | 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 | {
"resource": ""
} |
q794 | JOSE.JWK.sign | train | def sign(plain_text, jws = nil, header = nil)
jws ||= signer
return JOSE::JWS.sign(self, plain_text, jws, header)
end | ruby | {
"resource": ""
} |
q795 | JOSE.JWS.sign | train | 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 | {
"resource": ""
} |
q796 | JOSE.JWS.verify | train | 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 | {
"resource": ""
} |
q797 | JOSE.JWA.supports | train | 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 | {
"resource": ""
} |
q798 | JOSE.JWE.block_decrypt | train | 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 | {
"resource": ""
} |
q799 | JOSE.JWE.block_encrypt | train | 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 | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.