_id
stringlengths 2
6
| title
stringlengths 9
130
| partition
stringclasses 3
values | text
stringlengths 66
10.5k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q600 | Topsy.Client.related | train | def related(url, options={})
response = handle_response(get("/related.json", :query => {:url => url}.merge(options)))
Topsy::Page.new(response,Topsy::LinkSearchResult)
end | ruby | {
"resource": ""
} |
q601 | Topsy.Client.search | train | def search(q, options={})
if q.is_a?(Hash)
options = q
q = "site:#{options.delete(:site)}" if options[:site]
else
q += " site:#{options.delete(:site)}" if options[:site]
end
options = set_window_or_default(options)
results = handle_response(get("/search.json", :query => {:q => q}.merge(options)))
Topsy::Page.new(results,Topsy::LinkSearchResult)
end | ruby | {
"resource": ""
} |
q602 | Topsy.Client.search_count | train | def search_count(q)
counts = handle_response(get("/searchcount.json", :query => {:q => q}))
Topsy::SearchCounts.new(counts)
end | ruby | {
"resource": ""
} |
q603 | Topsy.Client.search_histogram | train | def search_histogram( q , count_method = 'target' , slice = 86400 , period = 30 )
response = handle_response(get("/searchhistogram.json" , :query => { :q => q , :slice => slice , :period => period , :count_method => count_method } ))
Topsy::SearchHistogram.new(response)
end | ruby | {
"resource": ""
} |
q604 | Topsy.Client.stats | train | def stats(url, options={})
query = {:url => url}
query.merge!(options)
response = handle_response(get("/stats.json", :query => query))
Topsy::Stats.new(response)
end | ruby | {
"resource": ""
} |
q605 | Topsy.Client.tags | train | def tags(url, options={})
response = handle_response(get("/tags.json", :query => {:url => url}.merge(options)))
Topsy::Page.new(response,Topsy::Tag)
end | ruby | {
"resource": ""
} |
q606 | Topsy.Client.trending | train | def trending(options={})
response = handle_response(get("/trending.json", :query => options))
Topsy::Page.new(response,Topsy::Trend)
end | ruby | {
"resource": ""
} |
q607 | Topsy.Client.url_info | train | def url_info(url)
response = handle_response(get("/urlinfo.json", :query => {:url => url}))
Topsy::UrlInfo.new(response)
end | ruby | {
"resource": ""
} |
q608 | Topsy.Client.extract_header_value | train | def extract_header_value(response, key)
response.headers[key].class == Array ? response.headers[key].first.to_i : response.headers[key].to_i
end | ruby | {
"resource": ""
} |
q609 | RightScale.NonBlockingClient.poll_again | train | def poll_again(fiber, connection, request_options, stop_at)
http = connection.send(:get, request_options)
http.errback { fiber.resume(*handle_error("POLL", http.error)) }
http.callback do
code, body, headers = http.response_header.status, http.response, http.response_header
if code == 200 && (body.nil? || body == "null") && Time.now < stop_at
poll_again(fiber, connection, request_options, stop_at)
else
fiber.resume(code, body, headers)
end
end
true
end | ruby | {
"resource": ""
} |
q610 | RightScale.NonBlockingClient.beautify_headers | train | def beautify_headers(headers)
headers.inject({}) { |out, (key, value)| out[key.gsub(/-/, '_').downcase.to_sym] = value; out }
end | ruby | {
"resource": ""
} |
q611 | RightScale.AgentTagManager.tags | train | def tags(options = {})
# TODO remove use of agent identity when fully drop AMQP
do_query(nil, @agent.mode == :http ? @agent.self_href : @agent.identity, options) do |result|
if result.kind_of?(Hash)
yield(result.size == 1 ? result.values.first['tags'] : [])
else
yield result
end
end
end | ruby | {
"resource": ""
} |
q612 | RightScale.AgentTagManager.query_tags | train | def query_tags(tags, options = {})
tags = ensure_flat_array_value(tags) unless tags.nil? || tags.empty?
do_query(tags, nil, options) { |result| yield result }
end | ruby | {
"resource": ""
} |
q613 | RightScale.AgentTagManager.add_tags | train | def add_tags(new_tags, options = {})
new_tags = ensure_flat_array_value(new_tags) unless new_tags.nil? || new_tags.empty?
do_update(new_tags, [], options) { |raw_response| yield raw_response if block_given? }
end | ruby | {
"resource": ""
} |
q614 | RightScale.AgentTagManager.remove_tags | train | def remove_tags(old_tags, options = {})
old_tags = ensure_flat_array_value(old_tags) unless old_tags.nil? || old_tags.empty?
do_update([], old_tags, options) { |raw_response| yield raw_response if block_given? }
end | ruby | {
"resource": ""
} |
q615 | RightScale.AgentTagManager.do_query | train | def do_query(tags = nil, hrefs = nil, options = {})
raw = options[:raw]
timeout = options[:timeout]
request_options = {}
request_options[:timeout] = timeout if timeout
agent_check
payload = {:agent_identity => @agent.identity}
payload[:tags] = ensure_flat_array_value(tags) unless tags.nil? || tags.empty?
# TODO remove use of agent identity when fully drop AMQP
if @agent.mode == :http
payload[:hrefs] = ensure_flat_array_value(hrefs) unless hrefs.nil? || hrefs.empty?
else
payload[:agent_ids] = ensure_flat_array_value(hrefs) unless hrefs.nil? || hrefs.empty?
end
request = RightScale::RetryableRequest.new("/router/query_tags", payload, request_options)
request.callback { |result| yield raw ? request.raw_response : result }
request.errback do |message|
ErrorTracker.log(self, "Failed to query tags (#{message})")
yield((raw ? request.raw_response : nil) || message)
end
request.run
true
end | ruby | {
"resource": ""
} |
q616 | RightScale.AgentTagManager.do_update | train | def do_update(new_tags, old_tags, options = {}, &block)
agent_check
raise ArgumentError.new("Cannot add and remove tags in same update") if new_tags.any? && old_tags.any?
tags = @agent.tags
tags += new_tags
tags -= old_tags
tags.uniq!
if new_tags.any?
request = RightScale::RetryableRequest.new("/router/add_tags", {:tags => new_tags}, options)
elsif old_tags.any?
request = RightScale::RetryableRequest.new("/router/delete_tags", {:tags => old_tags}, options)
else
return
end
if block
# Always yield raw response
request.callback do |_|
# Refresh agent's copy of tags on successful update
@agent.tags = tags
block.call(request.raw_response)
end
request.errback { |message| block.call(request.raw_response || message) }
end
request.run
true
end | ruby | {
"resource": ""
} |
q617 | RightScale.ErrorTracker.init | train | def init(agent, agent_name, options = {})
@agent = agent
@trace_level = options[:trace_level] || {}
notify_init(agent_name, options)
reset_stats
true
end | ruby | {
"resource": ""
} |
q618 | RightScale.ErrorTracker.log | train | def log(component, description, exception = nil, packet = nil, trace = nil)
if exception.nil?
Log.error(description)
elsif exception.is_a?(String)
Log.error(description, exception)
else
trace = (@trace_level && @trace_level[exception.class]) || trace || :trace
Log.error(description, exception, trace)
track(component, exception, packet) if trace != :no_trace
end
true
rescue StandardError => e
Log.error("Failed to log error", e, :trace) rescue nil
false
end | ruby | {
"resource": ""
} |
q619 | RightScale.ErrorTracker.track | train | def track(component, exception, packet = nil)
if @exception_stats
component = component.class.name.split("::").last.snake_case unless component.is_a?(String)
@exception_stats.track(component, exception, packet)
end
true
end | ruby | {
"resource": ""
} |
q620 | RightScale.ErrorTracker.notify | train | def notify(exception, packet = nil, agent = nil, component = nil)
if @notify_enabled
if packet && packet.is_a?(Packet)
action = packet.type.split("/").last if packet.respond_to?(:type)
params = packet.respond_to?(:payload) && packet.payload
uuid = packet.respond_to?(:token) && packet.token
elsif packet.is_a?(Hash)
action_path = packet[:path] || packet["path"]
action = action_path.split("/").last if action_path
params = packet[:data] || packet["data"]
uuid = packet[:uuid] || packet["uuid"]
else
params = uuid = nil
end
component = component.class.name unless component.is_a?(String)
n = Airbrake.build_notice(
exception,
{ component: component, action: action },
:right_agent )
n[:params] = params.is_a?(Hash) ? filter(params) : {:param => params} if params
n[:session] = { :uuid => uuid } if uuid
if agent
n[:environment] = (@cgi_data || {}).merge(:agent_class => agent.class.name)
elsif @cgi_data
n[:environment] = @cgi_data || {}
end
Airbrake.notify(n, {}, :right_agent)
end
true
rescue Exception => e
raise if e.class.name =~ /^RSpec/ # keep us from going insane while running tests
Log.error("Failed to notify Errbit", e, :trace)
end | ruby | {
"resource": ""
} |
q621 | RightScale.ErrorTracker.notify_callback | train | def notify_callback
Proc.new do |exception, packet, agent, component|
notify(exception, packet, agent, component)
end
end | ruby | {
"resource": ""
} |
q622 | RightScale.ErrorTracker.notify_init | train | def notify_init(agent_name, options)
if options[:airbrake_endpoint] && options[:airbrake_api_key]
unless require_succeeds?("airbrake-ruby")
raise RuntimeError, "airbrake-ruby gem missing - required if airbrake options used in ErrorTracker"
end
@cgi_data = {
:process => $0,
:pid => Process.pid,
:agent_name => agent_name
}
@cgi_data[:shard_id] = options[:shard_id] if options[:shard_id]
@filter_params = (options[:filter_params] || []).map { |p| p.to_s }
@notify_enabled = true
return true if Airbrake.send(:configured?, :right_agent)
Airbrake.configure(:right_agent) do |config|
config.host = options[:airbrake_endpoint]
config.project_id = options[:airbrake_api_key]
config.project_key = options[:airbrake_api_key]
config.root_directory = AgentConfig.root_dir
config.environment = ENV['RAILS_ENV']
config.app_version = CURRENT_SOURCE_SHA if defined?(CURRENT_SOURCE_SHA)
end
else
@notify_enabled = false
end
true
end | ruby | {
"resource": ""
} |
q623 | RightScale.ErrorTracker.filter | train | def filter(params)
if @filter_params
filtered_params = {}
params.each { |k, p| filtered_params[k] = @filter_params.include?(k.to_s) ? FILTERED_PARAM_VALUE : p }
filtered_params
end
end | ruby | {
"resource": ""
} |
q624 | RightScale.ConnectivityChecker.message_received | train | def message_received(&callback)
if block_given?
@message_received_callbacks << callback
else
@message_received_callbacks.each { |c| c.call }
if @check_interval > 0
now = Time.now
if (now - @last_received) > MIN_RESTART_INACTIVITY_TIMER_INTERVAL
@last_received = now
restart_inactivity_timer
end
end
end
true
end | ruby | {
"resource": ""
} |
q625 | RightScale.ConnectivityChecker.check | train | def check(id = nil, max_ping_timeouts = MAX_PING_TIMEOUTS)
unless @terminating || @ping_timer || (id && !@sender.agent.client.connected?(id))
@ping_id = id
@ping_timer = EM::Timer.new(PING_TIMEOUT) do
if @ping_id
begin
@ping_stats.update("timeout")
@ping_timer = nil
@ping_timeouts[@ping_id] = (@ping_timeouts[@ping_id] || 0) + 1
if @ping_timeouts[@ping_id] >= max_ping_timeouts
ErrorTracker.log(self, "Mapper ping via broker #{@ping_id} timed out after #{PING_TIMEOUT} seconds and now " +
"reached maximum of #{max_ping_timeouts} timeout#{max_ping_timeouts > 1 ? 's' : ''}, " +
"attempting to reconnect")
host, port, index, priority = @sender.client.identity_parts(@ping_id)
@sender.agent.connect(host, port, index, priority, force = true)
else
Log.warning("Mapper ping via broker #{@ping_id} timed out after #{PING_TIMEOUT} seconds")
end
rescue Exception => e
ErrorTracker.log(self, "Failed to reconnect to broker #{@ping_id}", e)
end
else
@ping_timer = nil
end
end
handler = lambda do |_|
begin
if @ping_timer
@ping_stats.update("success")
@ping_timer.cancel
@ping_timer = nil
@ping_timeouts[@ping_id] = 0
@ping_id = nil
end
rescue Exception => e
ErrorTracker.log(self, "Failed to cancel router ping", e)
end
end
request = Request.new("/router/ping", nil, {:from => @sender.identity, :token => AgentIdentity.generate})
@sender.pending_requests[request.token] = PendingRequest.new(Request, Time.now, handler)
ids = [@ping_id] if @ping_id
@ping_id = @sender.send(:publish, request, ids).first
end
true
end | ruby | {
"resource": ""
} |
q626 | RightScale.ConnectivityChecker.restart_inactivity_timer | train | def restart_inactivity_timer
@inactivity_timer.cancel if @inactivity_timer
@inactivity_timer = EM::Timer.new(@check_interval) do
begin
check(id = nil, max_ping_timeouts = 1)
rescue Exception => e
ErrorTracker.log(self, "Failed connectivity check", e)
end
end
true
end | ruby | {
"resource": ""
} |
q627 | RightScale.DispatchedCache.serviced_by | train | def serviced_by(token)
if @cache[token]
@cache[token] = Time.now.to_i
@lru.push(@lru.delete(token))
@identity
end
end | ruby | {
"resource": ""
} |
q628 | RightScale.DispatchedCache.stats | train | def stats
if (s = size) > 0
now = Time.now.to_i
{
"local total" => s,
"local max age" => RightSupport::Stats.elapsed(now - @cache[@lru.first])
}
end
end | ruby | {
"resource": ""
} |
q629 | RightScale.AgentController.control | train | def control(options)
# Initialize directory settings
AgentConfig.cfg_dir = options[:cfg_dir]
AgentConfig.pid_dir = options[:pid_dir]
# List agents if requested
list_configured_agents if options[:list]
# Validate arguments
action = options.delete(:action)
fail("No action specified on the command line.", print_usage = true) unless action
if action == 'kill' && (options[:pid_file].nil? || !File.file?(options[:pid_file]))
fail("Missing or invalid pid file #{options[:pid_file]}", print_usage = true)
end
if options[:agent_name]
if action == 'start'
cfg = configure_agent(action, options)
else
cfg = AgentConfig.load_cfg(options[:agent_name])
fail("Deployment is missing configuration file #{AgentConfig.cfg_file(options[:agent_name]).inspect}.") unless cfg
end
options.delete(:identity)
options = cfg.merge(options)
AgentConfig.root_dir = options[:root_dir]
AgentConfig.pid_dir = options[:pid_dir]
Log.program_name = syslog_program_name(options)
Log.facility = syslog_facility(options)
Log.log_to_file_only(options[:log_to_file_only])
configure_proxy(options[:http_proxy], options[:http_no_proxy]) if options[:http_proxy]
elsif options[:identity]
options[:agent_name] = AgentConfig.agent_name(options[:identity])
end
@options = DEFAULT_OPTIONS.clone.merge(options.merge(FORCED_OPTIONS))
FileUtils.mkdir_p(@options[:pid_dir]) unless @options[:pid_dir].nil? || File.directory?(@options[:pid_dir])
# Execute request
success = case action
when /show|killall/
action = 'stop' if action == 'killall'
s = true
AgentConfig.cfg_agents.each { |agent_name| s &&= dispatch(action, agent_name) }
s
when 'kill'
kill_process
else
dispatch(action, @options[:agent_name])
end
exit(1) unless success
end | ruby | {
"resource": ""
} |
q630 | RightScale.AgentController.kill_process | train | def kill_process(sig = 'TERM')
content = IO.read(@options[:pid_file])
pid = content.to_i
fail("Invalid pid file content #{content.inspect}") if pid == 0
begin
Process.kill(sig, pid)
rescue Errno::ESRCH => e
fail("Could not find process with pid #{pid}")
rescue Errno::EPERM => e
fail("You don't have permissions to stop process #{pid}")
rescue Exception => e
fail(e.message)
end
true
end | ruby | {
"resource": ""
} |
q631 | RightScale.AgentController.stop_agent | train | def stop_agent(agent_name)
res = false
if (pid_file = AgentConfig.pid_file(agent_name))
name = human_readable_name(agent_name, pid_file.identity)
if (pid = pid_file.read_pid[:pid])
begin
Process.kill('TERM', pid)
res = true
puts "#{name} stopped"
rescue Errno::ESRCH
puts "#{name} not running"
end
elsif File.file?(pid_file.to_s)
puts "Invalid pid file '#{pid_file.to_s}' content: #{IO.read(pid_file.to_s)}"
else
puts "#{name} not running"
end
else
puts "Non-existent pid file for #{agent_name}"
end
res
end | ruby | {
"resource": ""
} |
q632 | RightScale.AgentController.list_configured_agents | train | def list_configured_agents
agents = AgentConfig.cfg_agents
if agents.empty?
puts "Found no configured agents"
else
puts "Configured agents:"
agents.each { |a| puts " - #{a}" }
end
exit
end | ruby | {
"resource": ""
} |
q633 | RightScale.AgentController.configure_agent | train | def configure_agent(action, options)
agent_type = options[:agent_type]
agent_name = options[:agent_name]
if agent_name != agent_type && (cfg = AgentConfig.load_cfg(agent_type))
base_id = (options[:base_id] || AgentIdentity.parse(cfg[:identity]).base_id.to_s).to_i
unless (identity = AgentConfig.agent_options(agent_name)[:identity]) &&
AgentIdentity.parse(identity).base_id == base_id
identity = AgentIdentity.new(options[:prefix] || 'rs', options[:agent_type], base_id, options[:token]).to_s
end
cfg.merge!(:identity => identity)
cfg_file = AgentConfig.store_cfg(agent_name, cfg)
puts "Generated configuration file for #{agent_name} agent: #{cfg_file}"
elsif !(cfg = AgentConfig.load_cfg(agent_name))
fail("Deployment is missing configuration file #{AgentConfig.cfg_file(agent_name).inspect}")
end
cfg
end | ruby | {
"resource": ""
} |
q634 | RightScale.AgentController.configure_proxy | train | def configure_proxy(proxy_setting, exceptions)
ENV['HTTP_PROXY'] = proxy_setting
ENV['http_proxy'] = proxy_setting
ENV['HTTPS_PROXY'] = proxy_setting
ENV['https_proxy'] = proxy_setting
ENV['NO_PROXY'] = exceptions
ENV['no_proxy'] = exceptions
true
end | ruby | {
"resource": ""
} |
q635 | RightScale.Serializer.cascade_serializers | train | def cascade_serializers(action, packet, serializers, id = nil)
errors = []
serializers.map do |serializer|
obj = nil
begin
obj = serializer == SecureSerializer ? serializer.send(action, packet, id) : serializer.send(action, packet)
rescue RightSupport::Net::NoResult, SocketError => e
raise Exceptions::ConnectivityFailure.new("Failed to #{action} with #{serializer.name} due to external " +
"service access failures (#{e.class.name}: #{e.message})", e)
rescue SecureSerializer::MissingCertificate, SecureSerializer::MissingPrivateKey, SecureSerializer::InvalidSignature => e
errors << Log.format("Failed to #{action} with #{serializer.name}", e)
rescue StandardError => e
errors << Log.format("Failed to #{action} with #{serializer.name}", e, :trace)
end
return obj if obj
end
raise SerializationError.new(action, packet, serializers, errors.join("\n"))
end | ruby | {
"resource": ""
} |
q636 | RightScale.Multiplexer.method_missing | train | def method_missing(m, *args)
res = @targets.inject([]) { |res, t| res << t.send(m, *args) }
res[0]
end | ruby | {
"resource": ""
} |
q637 | RightScale.Multiplexer.respond_to? | train | def respond_to?(m, *args)
super(m, *args) || @targets.all? { |t| t.respond_to?(m, *args) }
end | ruby | {
"resource": ""
} |
q638 | RightScale.OperationResult.status | train | def status(reason = false)
case @status_code
when SUCCESS then 'success'
when ERROR then 'error' + (reason ? " (#{truncated_error})" : "")
when CONTINUE then 'continue'
when RETRY then 'retry' + (reason ? " (#{@content})" : "")
when NON_DELIVERY then 'non-delivery' + (reason ? " (#{@content})" : "")
when MULTICAST then 'multicast'
when CANCEL then 'cancel' + (reason ? " (#{@content})" : "")
end
end | ruby | {
"resource": ""
} |
q639 | RightScale.OperationResult.truncated_error | train | def truncated_error
e = @content.is_a?(String) ? @content : @content.inspect
e = e[0, MAX_ERROR_SIZE - 3] + "..." if e.size > (MAX_ERROR_SIZE - 3)
e
end | ruby | {
"resource": ""
} |
q640 | RightScale.CommandIO.listen | train | def listen(socket_port, &block)
raise ArgumentError, 'Missing listener block' unless block_given?
raise Exceptions::Application, 'Already listening' if listening
begin
@conn = EM.start_server('127.0.0.1', socket_port, ServerInputHandler, block)
rescue Exception => e
raise Exceptions::IO, 'Listen port unavailable' if e.message =~ /no acceptor/
end
true
end | ruby | {
"resource": ""
} |
q641 | RightScale.CommandIO.reply | train | def reply(conn, data, close_after_writing=true)
conn.send_data(CommandSerializer.dump(data))
conn.close_connection_after_writing if close_after_writing
true
end | ruby | {
"resource": ""
} |
q642 | RightScale.LogLevelManager.manage | train | def manage(options)
# Initialize configuration directory setting
AgentConfig.cfg_dir = options[:cfg_dir]
# Determine command
level = options[:level]
command = { :name => (level ? 'set_log_level' : 'get_log_level') }
command[:level] = level.to_sym if level
# Determine candidate agents
agent_names = if options[:agent_name]
[options[:agent_name]]
else
AgentConfig.cfg_agents
end
fail("No agents configured") if agent_names.empty?
# Perform command for each agent
count = 0
agent_names.each do |agent_name|
count += 1 if request_log_level(agent_name, command, options)
end
puts("No agents running") if count == 0
true
end | ruby | {
"resource": ""
} |
q643 | RightScale.LogLevelManager.request_log_level | train | def request_log_level(agent_name, command, options)
res = false
config_options = AgentConfig.agent_options(agent_name)
unless config_options.empty? || (listen_port = config_options[:listen_port]).nil?
fail("Could not retrieve #{agent_name} agent listen port") unless listen_port
client = CommandClient.new(listen_port, config_options[:cookie])
begin
client.send_command(command, options[:verbose], timeout = 5) do |level|
puts "Agent #{agent_name} log level: #{level.to_s.upcase}"
end
res = true
rescue Exception => e
puts "Command #{command.inspect} to #{agent_name} agent failed (#{e})"
end
end
res
end | ruby | {
"resource": ""
} |
q644 | RightScale.CommonParser.parse_common | train | def parse_common(opts, options)
opts.on("--test") do
options[:user] = 'test'
options[:pass] = 'testing'
options[:vhost] = '/right_net'
options[:test] = true
options[:pid_dir] = Dir.tmpdir
options[:base_id] = "#{rand(1000000)}"
options[:options][:log_dir] = Dir.tmpdir
end
opts.on("-i", "--identity ID") do |id|
options[:base_id] = id
end
opts.on("-t", "--token TOKEN") do |t|
options[:token] = t
end
opts.on("-S", "--secure-identity") do
options[:secure_identity] = true
end
opts.on("-x", "--prefix PREFIX") do |p|
options[:prefix] = p
end
opts.on("--url URL") do |url|
uri = URI.parse(url)
options[:user] = uri.user if uri.user
options[:pass] = uri.password if uri.password
options[:host] = uri.host
options[:port] = uri.port if uri.port
options[:vhost] = uri.path if (uri.path && !uri.path.empty?)
end
opts.on("-u", "--user USER") do |user|
options[:user] = user
end
opts.on("-p", "--pass PASSWORD") do |pass|
options[:pass] = pass
end
opts.on("-v", "--vhost VHOST") do |vhost|
options[:vhost] = vhost
end
opts.on("-P", "--port PORT") do |port|
options[:port] = port
end
opts.on("-h", "--host HOST") do |host|
options[:host] = host
end
opts.on('--type TYPE') do |t|
options[:agent_type] = t
end
opts.on_tail("--help") do
puts Usage.scan(__FILE__)
exit
end
opts.on_tail("--version") do
puts version
exit
end
true
end | ruby | {
"resource": ""
} |
q645 | RightScale.CommonParser.resolve_identity | train | def resolve_identity(options)
options[:agent_type] = agent_type(options[:agent_type], options[:agent_name])
if options[:base_id]
base_id = options[:base_id].to_i
if base_id.abs.to_s != options[:base_id]
puts "** Identity needs to be a positive integer"
exit(1)
end
token = if options[:secure_identity]
RightScale::SecureIdentity.derive(base_id, options[:token])
else
options[:token]
end
options[:identity] = AgentIdentity.new(options[:prefix] || 'rs', options[:agent_type], base_id, token).to_s
end
end | ruby | {
"resource": ""
} |
q646 | RightScale.CommonParser.agent_type | train | def agent_type(type, name)
unless type
if name =~ /^(.*)_[0-9]+$/
type = Regexp.last_match(1)
else
type = name || "instance"
end
end
type
end | ruby | {
"resource": ""
} |
q647 | RightScale.ActorRegistry.register | train | def register(actor, prefix)
raise ArgumentError, "#{actor.inspect} is not a RightScale::Actor subclass instance" unless RightScale::Actor === actor
log_msg = "[actor] #{actor.class.to_s}"
log_msg += ", prefix #{prefix}" if prefix && !prefix.empty?
Log.info(log_msg)
prefix ||= actor.class.default_prefix
@actors[prefix.to_s] = actor
end | ruby | {
"resource": ""
} |
q648 | RightScale.CertificateCache.put | train | def put(key, item)
if @items.include?(key)
delete(key)
end
if @list.size == @max_count
delete(@list.first)
end
@items[key] = item
@list.push(key)
item
end | ruby | {
"resource": ""
} |
q649 | RightScale.CertificateCache.get | train | def get(key)
if @items.include?(key)
@list.each_index do |i|
if @list[i] == key
@list.delete_at(i)
break
end
end
@list.push(key)
@items[key]
else
return nil unless block_given?
self[key] = yield
end
end | ruby | {
"resource": ""
} |
q650 | RightScale.CertificateCache.delete | train | def delete(key)
c = @items[key]
if c
@items.delete(key)
@list.each_index do |i|
if @list[i] == key
@list.delete_at(i)
break
end
end
c
end
end | ruby | {
"resource": ""
} |
q651 | RightScale.BalancedHttpClient.check_health | train | def check_health(host = nil)
begin
@http_client.health_check_proc.call(host || @urls.first)
rescue StandardError => e
if e.respond_to?(:http_code) && RETRY_STATUS_CODES.include?(e.http_code)
raise NotResponding.new("#{@server_name || host} not responding", e)
else
raise
end
end
end | ruby | {
"resource": ""
} |
q652 | RightScale.BalancedHttpClient.request_headers | train | def request_headers(request_uuid, options)
headers = {"X-Request-Lineage-Uuid" => request_uuid, :accept => "application/json"}
headers["X-API-Version"] = @api_version if @api_version
headers.merge!(options[:headers]) if options[:headers]
headers["X-DEBUG"] = true if Log.level == :debug
headers
end | ruby | {
"resource": ""
} |
q653 | RightScale.BalancedHttpClient.rest_request | train | def rest_request(verb, path, connect_options, request_options, used)
result, code, body, headers = @balancer.request do |host|
uri = URI.parse(host)
uri.user = uri.password = nil
used[:host] = uri.to_s
@http_client.request(verb, path, host, connect_options, request_options)
end
[result, code, body, headers]
end | ruby | {
"resource": ""
} |
q654 | RightScale.BalancedHttpClient.poll_request | train | def poll_request(path, connect_options, request_options, request_timeout, started_at, used)
result = code = body = headers = nil
if (connection = @http_client.connections[path]).nil? || Time.now >= connection[:expires_at]
# Use normal :get request using request balancer for first poll
result, code, body, headers = rest_request(:get, path, connect_options, request_options.dup, used)
return [result, code, body, headers] if (Time.now - started_at) >= request_timeout
end
if result.nil? && (connection = @http_client.connections[path]) && Time.now < connection[:expires_at]
begin
# Continue to poll using same connection until get result, timeout, or hit error
used[:host] = connection[:host]
result, code, body, headers = @http_client.poll(connection, request_options, started_at + request_timeout)
rescue HttpException, RestClient::Exception => e
raise NotResponding.new(e.http_body, e) if RETRY_STATUS_CODES.include?(e.http_code)
raise NotResponding.new("Request timeout", e) if e.is_a?(RestClient::RequestTimeout)
raise
end
end
[result, code, body, headers]
end | ruby | {
"resource": ""
} |
q655 | RightScale.BalancedHttpClient.handle_no_result | train | def handle_no_result(no_result, host)
server_name = @server_name || host
e = no_result.details.values.flatten.last
if no_result.details.empty?
yield(no_result)
raise NotResponding.new("#{server_name} not responding", no_result)
elsif e.respond_to?(:http_code) && RETRY_STATUS_CODES.include?(e.http_code)
yield(e)
if e.http_code == 504 && (e.http_body && !e.http_body.empty?)
raise NotResponding.new(e.http_body, e)
else
raise NotResponding.new("#{server_name} not responding", e)
end
elsif e.is_a?(RestClient::RequestTimeout)
# Special case RequestTimeout because http_code is typically nil given no actual response
yield(e)
raise NotResponding.new("Request timeout", e)
else
yield(e)
raise e
end
true
end | ruby | {
"resource": ""
} |
q656 | RightScale.BalancedHttpClient.log_success | train | def log_success(result, code, body, headers, host, path, request_uuid, started_at, log_level)
length = (headers && headers[:content_length]) || (body && body.size) || "-"
duration = "%.0fms" % ((Time.now - started_at) * 1000)
completed = "Completed <#{request_uuid}> in #{duration} | #{code || "nil"} [#{host}#{path}] | #{length} bytes"
completed << " | #{result.inspect}" if Log.level == :debug
Log.send(log_level, completed)
true
end | ruby | {
"resource": ""
} |
q657 | RightScale.BalancedHttpClient.log_failure | train | def log_failure(host, path, params, filter, request_uuid, started_at, exception)
code = exception.respond_to?(:http_code) ? exception.http_code : "nil"
duration = "%.0fms" % ((Time.now - started_at) * 1000)
ErrorTracker.log(self, "Failed <#{request_uuid}> in #{duration} | #{code} " + log_text(path, params, filter, host, exception))
true
end | ruby | {
"resource": ""
} |
q658 | RightScale.BalancedHttpClient.log_text | train | def log_text(path, params, filter, host = nil, exception = nil)
text = "#{path} #{filter(params, filter).inspect}"
text = "[#{host}#{text}]" if host
text << " | #{self.class.exception_text(exception)}" if exception
text
end | ruby | {
"resource": ""
} |
q659 | RightScale.BalancedHttpClient.filter | train | def filter(params, filter)
if filter.empty? || !params.is_a?(Hash)
params
else
filtered_params = {}
params.each do |k, p|
s = k.to_s
if filter.include?(s)
filtered_params[k] = FILTERED_PARAM_VALUE
else
filtered_params[k] = CONTENT_FILTERED_PARAMS.include?(s) ? filter(p, filter) : p
end
end
filtered_params
end
end | ruby | {
"resource": ""
} |
q660 | RightScale.BalancedHttpClient.split | train | def split(object, pattern = /,\s*/)
object ? (object.is_a?(Array) ? object : object.split(pattern)) : []
end | ruby | {
"resource": ""
} |
q661 | RightScale.StatsManager.manage | train | def manage(options)
init_log if options[:verbose]
AgentConfig.cfg_dir = options[:cfg_dir]
options[:timeout] ||= DEFAULT_TIMEOUT
request_stats(options)
rescue Exception => e
fail("#{e}\n#{e.backtrace.join("\n")}") unless e.is_a?(SystemExit)
end | ruby | {
"resource": ""
} |
q662 | RightScale.StatsManager.request_stats | train | def request_stats(options)
# Determine candidate agents
agent_names = if options[:agent_name]
[options[:agent_name]]
else
AgentConfig.cfg_agents
end
fail("No agents configured") if agent_names.empty?
# Request stats from agents
count = 0
agent_names.each do |agent_name|
begin
count += 1 if request_agent_stats(agent_name, options)
rescue Exception => e
$stderr.puts "Command to #{agent_name} agent failed (#{e})" unless e.is_a?(SystemExit)
end
end
$stderr.puts("No agents running") if count == 0
end | ruby | {
"resource": ""
} |
q663 | RightScale.StatsManager.request_agent_stats | train | def request_agent_stats(agent_name, options)
res = false
config_options = AgentConfig.agent_options(agent_name)
unless config_options.empty? || (listen_port = config_options[:listen_port]).nil?
client = CommandClient.new(listen_port, config_options[:cookie])
command = {:name => :stats, :reset => options[:reset]}
begin
client.send_command(command, verbose = false, options[:timeout]) { |r| display(agent_name, r, options) }
res = true
rescue Exception => e
msg = "Could not retrieve #{agent_name} agent stats: #{e}"
msg += "\n" + e.backtrace.join("\n") unless e.message =~ /Timed out/
fail(msg)
end
end
res
end | ruby | {
"resource": ""
} |
q664 | RightScale.OfflineHandler.disable | train | def disable
if offline? && @state != :created
Log.info("[offline] Connection to RightNet re-established")
@offline_stats.finish
cancel_timer
@state = :flushing
# Wait a bit to avoid flooding RightNet
EM.add_timer(rand(MAX_QUEUE_FLUSH_DELAY)) { flush }
end
true
end | ruby | {
"resource": ""
} |
q665 | RightScale.OfflineHandler.queue_request | train | def queue_request(kind, type, payload, target, token, expires_at, skewed_by, &callback)
request = {:kind => kind, :type => type, :payload => payload, :target => target,
:token => token, :expires_at => expires_at, :skewed_by => skewed_by,
:callback => callback}
Log.info("[offline] Queuing request: #{request.inspect}")
vote_to_restart if (@restart_vote_count += 1) >= MAX_QUEUED_REQUESTS
if @state == :initializing
# We are in the initialization callback, requests should be put at the head of the queue
@queue.unshift(request)
else
@queue << request
end
true
end | ruby | {
"resource": ""
} |
q666 | RightScale.OfflineHandler.flush | train | def flush(again = false)
if @state == :flushing
Log.info("[offline] Starting to flush request queue of size #{@queue.size}") unless again || @mode == :initializing
if @queue.any?
r = @queue.shift
options = {:token => r[:token]}
if r[:expires_at] != 0 && (options[:time_to_live] = r[:expires_at] - Time.now.to_i) <= 0
Log.info("[offline] Dropping queued request <#{r[:token]}> because it expired " +
"#{(-options[:time_to_live]).round} sec ago")
else
Sender.instance.send(r[:kind], r[:type], r[:payload], r[:target], options, &r[:callback])
end
end
if @queue.empty?
Log.info("[offline] Request queue flushed, resuming normal operations") unless @mode == :initializing
@mode = :online
@state = :running
else
EM.next_tick { flush(true) }
end
end
true
end | ruby | {
"resource": ""
} |
q667 | RightScale.LoginPolicy.fingerprint | train | def fingerprint
h = Digest::SHA2.new
h << (self.exclusive ? 'true' : 'false')
users = self.users.sort { |a, b| a.uuid <=> b.uuid }
users.each do |u|
h << format(",(%d,%s,%s,%d,%s",
u.uuid, u.common_name,
(u.superuser ? 'true' : 'false'),
(u.expires_at ? u.expires_at.to_i : 0),
u.username)
u.public_key_fingerprints.each do |fp|
h << "," << fp
end
h << ')'
end
h.hexdigest
end | ruby | {
"resource": ""
} |
q668 | RightScale.BlockingClient.request | train | def request(verb, path, host, connect_options, request_options)
url = host + path + request_options.delete(:query).to_s
result = request_once(verb, url, request_options)
@connections[path] = {:host => host, :path => path, :expires_at => Time.now + BalancedHttpClient::CONNECTION_REUSE_TIMEOUT }
result
end | ruby | {
"resource": ""
} |
q669 | RightScale.BlockingClient.poll | train | def poll(connection, request_options, stop_at)
url = connection[:host] + connection[:path] + request_options.delete(:query).to_s
begin
result, code, body, headers = request_once(:get, url, request_options)
end until result || Time.now >= stop_at
connection[:expires_at] = Time.now + BalancedHttpClient::CONNECTION_REUSE_TIMEOUT
[result, code, body, headers]
end | ruby | {
"resource": ""
} |
q670 | RightScale.BlockingClient.request_once | train | def request_once(verb, url, request_options)
if (r = RightSupport::Net::HTTPClient.new.send(verb, url, request_options))
[BalancedHttpClient.response(r.code, r.body, r.headers, request_options[:headers][:accept]), r.code, r.body, r.headers]
else
[nil, nil, nil, nil]
end
end | ruby | {
"resource": ""
} |
q671 | RightScale.PendingRequests.[]= | train | def []=(token, pending_request)
now = Time.now
if (now - @last_cleanup) > MIN_CLEANUP_INTERVAL
self.reject! { |t, r| r.kind == :send_push && (now - r.receive_time) > MAX_PUSH_AGE }
@last_cleanup = now
end
super
end | ruby | {
"resource": ""
} |
q672 | RightScale.AgentDeployer.deploy | train | def deploy(options)
# Initialize directory settings
AgentConfig.root_dir = options[:root_dir]
AgentConfig.cfg_dir = options[:cfg_dir]
AgentConfig.pid_dir = options[:pid_dir]
# Configure agent
cfg = load_init_cfg
check_agent(options, cfg)
cfg = configure(options, cfg)
# Persist configuration
persist(options, cfg)
# Setup agent monitoring
monitor(options) if options[:monit]
true
end | ruby | {
"resource": ""
} |
q673 | RightScale.AgentDeployer.load_init_cfg | train | def load_init_cfg
cfg = {}
if (cfg_file = AgentConfig.init_cfg_file) && (cfg_data = YAML.load(IO.read(cfg_file)))
cfg = SerializationHelper.symbolize_keys(cfg_data) rescue nil
fail("Cannot read configuration for agent #{cfg_file.inspect}") unless cfg
end
cfg
end | ruby | {
"resource": ""
} |
q674 | RightScale.AgentDeployer.check_agent | train | def check_agent(options, cfg)
identity = options[:identity]
agent_type = options[:agent_type]
type = AgentIdentity.parse(identity).agent_type if identity
fail("Agent type #{agent_type.inspect} and identity #{identity.inspect} are inconsistent") if agent_type != type
fail("Cannot find agent init.rb file in init directory of #{AgentConfig.root_dir.inspect}") unless AgentConfig.init_file
actors = cfg[:actors]
fail('Agent configuration is missing actors') unless actors && actors.respond_to?(:each)
actors_dirs = AgentConfig.actors_dirs
actors.each do |a|
found = false
actors_dirs.each { |d| break if (found = File.exist?(File.normalize_path(File.join(d, "#{a}.rb")))) }
fail("Cannot find source for actor #{a.inspect} in #{actors_dirs.inspect}") unless found
end
true
end | ruby | {
"resource": ""
} |
q675 | RightScale.AgentDeployer.persist | train | def persist(options, cfg)
overrides = options[:options]
overrides.each { |k, v| cfg[k] = v } if overrides
cfg_file = AgentConfig.store_cfg(options[:agent_name], cfg)
unless options[:quiet]
puts "Generated configuration file for #{options[:agent_name]} agent: #{cfg_file}" unless options[:quiet]
end
true
end | ruby | {
"resource": ""
} |
q676 | RightScale.DevRepositories.add_repo | train | def add_repo(repo_sha, repo_detail, cookbook_positions)
@repositories ||= {}
@repositories[repo_sha] = DevRepository.new(repo_detail[:repo_type],
repo_detail[:url],
repo_detail[:tag],
repo_detail[:cookboooks_path],
repo_detail[:ssh_key],
repo_detail[:username],
repo_detail[:password],
repo_sha,
cookbook_positions)
end | ruby | {
"resource": ""
} |
q677 | RightScale.AgentManagerCommands.list_command | train | def list_command(opts)
usage = "Agent exposes the following commands:\n"
COMMANDS.reject { |k, _| k == :list || k.to_s =~ /test/ }.each do |c|
c.each { |k, v| usage += " - #{k.to_s}: #{v}\n" }
end
CommandIO.instance.reply(opts[:conn], usage)
end | ruby | {
"resource": ""
} |
q678 | RightScale.AgentManagerCommands.set_log_level_command | train | def set_log_level_command(opts)
Log.level = opts[:level] if [ :debug, :info, :warn, :error, :fatal ].include?(opts[:level])
CommandIO.instance.reply(opts[:conn], Log.level)
end | ruby | {
"resource": ""
} |
q679 | RightScale.Sender.send_push | train | def send_push(type, payload = nil, target = nil, options = {}, &callback)
build_and_send_packet(:send_push, type, payload, target, options, &callback)
end | ruby | {
"resource": ""
} |
q680 | RightScale.Sender.send_request | train | def send_request(type, payload = nil, target = nil, options = {}, &callback)
raise ArgumentError, "Missing block for response callback" unless callback
build_and_send_packet(:send_request, type, payload, target, options, &callback)
end | ruby | {
"resource": ""
} |
q681 | RightScale.Sender.build_and_send_packet | train | def build_and_send_packet(kind, type, payload, target, options = {}, &callback)
if (packet = build_packet(kind, type, payload, target, options, &callback))
action = type.split('/').last
received_at = @request_stats.update(action, packet.token)
@request_kind_stats.update((packet.selector == :all ? "fanout" : kind.to_s)[5..-1])
send("#{@mode}_send", kind, target, packet, received_at, &callback)
end
true
end | ruby | {
"resource": ""
} |
q682 | RightScale.Sender.build_packet | train | def build_packet(kind, type, payload, target, options = {}, &callback)
validate_target(target, kind == :send_push)
if kind == :send_push
packet = Push.new(type, payload)
packet.selector = target[:selector] || :any if target.is_a?(Hash)
packet.persistent = true
packet.confirm = true if callback
time_to_live = options[:time_to_live] || 0
else
packet = Request.new(type, payload)
packet.selector = :any
time_to_live = options[:time_to_live] || @options[:time_to_live]
end
packet.from = @identity
packet.token = options[:token] || RightSupport::Data::UUID.generate
packet.expires_at = Time.now.to_i + time_to_live if time_to_live && time_to_live > 0
if target.is_a?(Hash)
if (agent_id = target[:agent_id])
packet.target = agent_id
else
packet.tags = target[:tags] || []
packet.scope = target[:scope]
end
else
packet.target = target
end
if queueing?
@offline_handler.queue_request(kind, type, payload, target, packet.token, packet.expires_at, packet.skewed_by, &callback)
nil
else
packet
end
end | ruby | {
"resource": ""
} |
q683 | RightScale.Sender.handle_response | train | def handle_response(response)
if response.is_a?(Result)
token = response.token
if (result = OperationResult.from_results(response))
if result.non_delivery?
@non_delivery_stats.update(result.content.nil? ? "nil" : result.content)
elsif result.error?
@result_error_stats.update(result.content.nil? ? "nil" : result.content)
end
@result_stats.update(result.status)
else
@result_stats.update(response.results.nil? ? "nil" : response.results)
end
if (pending_request = @pending_requests[token])
if result && result.non_delivery? && pending_request.kind == :send_request
if result.content == OperationResult::TARGET_NOT_CONNECTED
# Log and temporarily ignore so that timeout retry mechanism continues, but save reason for use below if timeout
# Leave purging of associated request until final response, i.e., success response or retry timeout
if (parent_token = pending_request.retry_parent_token)
@pending_requests[parent_token].non_delivery = result.content
else
pending_request.non_delivery = result.content
end
Log.info("Non-delivery of <#{token}> because #{result.content}")
elsif result.content == OperationResult::RETRY_TIMEOUT && pending_request.non_delivery
# Request timed out but due to another non-delivery reason, so use that reason since more germane
response.results = OperationResult.non_delivery(pending_request.non_delivery)
deliver_response(response, pending_request)
else
deliver_response(response, pending_request)
end
else
deliver_response(response, pending_request)
end
elsif result && result.non_delivery?
Log.info("Non-delivery of <#{token}> because #{result.content}")
else
Log.debug("No pending request for response #{response.to_s([])}")
end
end
true
end | ruby | {
"resource": ""
} |
q684 | RightScale.Sender.terminate | train | def terminate
if @offline_handler
@offline_handler.terminate
@connectivity_checker.terminate if @connectivity_checker
pending = @pending_requests.kind(:send_request)
[pending.size, PendingRequests.youngest_age(pending)]
else
[0, nil]
end
end | ruby | {
"resource": ""
} |
q685 | RightScale.Sender.dump_requests | train | def dump_requests
info = []
if @pending_requests
@pending_requests.kind(:send_request).each do |token, request|
info << "#{request.receive_time.localtime} <#{token}>"
end
info.sort!.reverse!
info = info[0..49] + ["..."] if info.size > 50
end
info
end | ruby | {
"resource": ""
} |
q686 | RightScale.Sender.stats | train | def stats(reset = false)
stats = {}
if @agent
offlines = @offline_stats.all
offlines.merge!("duration" => @offline_stats.avg_duration) if offlines
if @pending_requests.size > 0
pending = {}
pending["pushes"] = @pending_requests.kind(:send_push).size
requests = @pending_requests.kind(:send_request)
if (pending["requests"] = requests.size) > 0
pending["oldest age"] = PendingRequests.oldest_age(requests)
end
end
stats = {
"non-deliveries" => @non_delivery_stats.all,
"offlines" => offlines,
"pings" => @ping_stats.all,
"request kinds" => @request_kind_stats.all,
"requests" => @request_stats.all,
"requests pending" => pending,
"result errors" => @result_error_stats.all,
"results" => @result_stats.all,
"retries" => @retry_stats.all,
"send failures" => @send_failure_stats.all
}
reset_stats if reset
end
stats
end | ruby | {
"resource": ""
} |
q687 | RightScale.Sender.reset_stats | train | def reset_stats
@ping_stats = RightSupport::Stats::Activity.new
@retry_stats = RightSupport::Stats::Activity.new
@request_stats = RightSupport::Stats::Activity.new
@result_stats = RightSupport::Stats::Activity.new
@result_error_stats = RightSupport::Stats::Activity.new
@non_delivery_stats = RightSupport::Stats::Activity.new
@offline_stats = RightSupport::Stats::Activity.new(measure_rate = false)
@request_kind_stats = RightSupport::Stats::Activity.new(measure_rate = false)
@send_failure_stats = RightSupport::Stats::Activity.new
true
end | ruby | {
"resource": ""
} |
q688 | RightScale.Sender.http_send | train | def http_send(kind, target, packet, received_at, &callback)
if @options[:async_response]
EM_S.next_tick do
begin
http_send_once(kind, target, packet, received_at, &callback)
rescue StandardError => e
ErrorTracker.log(self, "Failed sending or handling response for #{packet.trace} #{packet.type}", e)
end
end
else
http_send_once(kind, target, packet, received_at, &callback)
end
true
end | ruby | {
"resource": ""
} |
q689 | RightScale.Sender.http_send_once | train | def http_send_once(kind, target, packet, received_at, &callback)
begin
method = packet.class.name.split("::").last.downcase
options = {:request_uuid => packet.token}
options[:time_to_live] = (packet.expires_at - Time.now.to_i) if packet.expires_at > 0
result = success_result(@agent.client.send(method, packet.type, packet.payload, target, options))
rescue Exceptions::Unauthorized => e
result = error_result(e.message)
rescue Exceptions::ConnectivityFailure => e
if queueing?
@offline_handler.queue_request(kind, packet.type, packet.payload, target, packet.token, packet.expires_at, packet.skewed_by, &callback)
result = nil
else
result = retry_result(e.message)
end
rescue Exceptions::RetryableError => e
result = retry_result(e.message)
rescue Exceptions::InternalServerError => e
result = error_result("#{e.server} internal error")
rescue Exceptions::Terminating => e
result = nil
rescue StandardError => e
# These errors are either unexpected errors or HttpExceptions with an http_body
# giving details about the error that are conveyed in the error_result
if e.respond_to?(:http_body)
# No need to log here since any HTTP request errors have already been logged
result = error_result(e.inspect)
else
agent_type = AgentIdentity.parse(@identity).agent_type
ErrorTracker.log(self, "Failed to send #{packet.trace} #{packet.type}", e)
result = error_result("#{agent_type.capitalize} agent internal error")
end
end
if result && packet.is_a?(Request)
result = Result.new(packet.token, @identity, result, from = packet.target)
result.received_at = received_at.to_f
@pending_requests[packet.token] = PendingRequest.new(kind, received_at, callback) if callback
handle_response(result)
end
true
end | ruby | {
"resource": ""
} |
q690 | RightScale.Sender.amqp_send | train | def amqp_send(kind, target, packet, received_at, &callback)
begin
@pending_requests[packet.token] = PendingRequest.new(kind, received_at, callback) if callback
if packet.class == Request
amqp_send_retry(packet, packet.token)
else
amqp_send_once(packet)
end
rescue TemporarilyOffline => e
if queueing?
# Queue request until come back online
@offline_handler.queue_request(kind, packet.type, packet.payload, target, packet.token, packet.expires_at, packet.skewed_by, &callback)
@pending_requests.delete(packet.token) if callback
else
# Send retry response so that requester, e.g., RetryableRequest, can retry
result = OperationResult.retry("lost RightNet connectivity")
handle_response(Result.new(packet.token, @identity, result, @identity))
end
rescue SendFailure => e
# Send non-delivery response so that requester, e.g., RetryableRequest, can retry
result = OperationResult.non_delivery("send failed unexpectedly")
handle_response(Result.new(packet.token, @identity, result, @identity))
end
true
end | ruby | {
"resource": ""
} |
q691 | RightScale.Sender.amqp_send_once | train | def amqp_send_once(packet, ids = nil)
exchange = {:type => :fanout, :name => @request_queue, :options => {:durable => true, :no_declare => @secure}}
@agent.client.publish(exchange, packet, :persistent => packet.persistent, :mandatory => true,
:log_filter => [:tags, :target, :tries, :persistent], :brokers => ids)
rescue RightAMQP::HABrokerClient::NoConnectedBrokers => e
ErrorTracker.log(self, error = "Failed to publish request #{packet.trace} #{packet.type}", e, packet)
@send_failure_stats.update("NoConnectedBrokers")
raise TemporarilyOffline.new(error + " (#{e.class}: #{e.message})")
rescue StandardError => e
ErrorTracker.log(self, error = "Failed to publish request #{packet.trace} #{packet.type}", e, packet)
@send_failure_stats.update(e.class.name)
raise SendFailure.new(error + " (#{e.class}: #{e.message})")
end | ruby | {
"resource": ""
} |
q692 | RightScale.Sender.amqp_send_retry | train | def amqp_send_retry(packet, parent_token, count = 0, multiplier = 1, elapsed = 0, broker_ids = nil)
check_broker_ids = amqp_send_once(packet, broker_ids)
if @retry_interval && @retry_timeout && parent_token
interval = [(@retry_interval * multiplier) + (@request_stats.avg_duration || 0), @retry_timeout - elapsed].min
EM.add_timer(interval) do
begin
if @pending_requests[parent_token]
count += 1
elapsed += interval
if elapsed < @retry_timeout && (packet.expires_at <= 0 || Time.now.to_i < packet.expires_at)
packet.tries << packet.token
packet.token = RightSupport::Data::UUID.generate
@pending_requests[parent_token].retry_parent_token = parent_token if count == 1
@pending_requests[packet.token] = @pending_requests[parent_token]
broker_ids ||= @agent.client.all
amqp_send_retry(packet, parent_token, count, multiplier * RETRY_BACKOFF_FACTOR, elapsed,
broker_ids.push(broker_ids.shift))
@retry_stats.update(packet.type.split('/').last)
else
Log.warning("RE-SEND TIMEOUT after #{elapsed.to_i} seconds for #{packet.trace} #{packet.type}")
result = OperationResult.non_delivery(OperationResult::RETRY_TIMEOUT)
handle_response(Result.new(packet.token, @identity, result, @identity))
end
@connectivity_checker.check(check_broker_ids.first) if check_broker_ids.any? && count == 1
end
rescue TemporarilyOffline => e
ErrorTracker.log(self, "Failed retry for #{packet.trace} #{packet.type} because temporarily offline")
rescue SendFailure => e
ErrorTracker.log(self, "Failed retry for #{packet.trace} #{packet.type} because of send failure")
rescue Exception => e
# Not sending a response here because something more basic is broken in the retry
# mechanism and don't want an error response to preempt a delayed actual response
ErrorTracker.log(self, "Failed retry for #{packet.trace} #{packet.type} without responding", e, packet)
end
end
end
true
end | ruby | {
"resource": ""
} |
q693 | RightScale.Sender.deliver_response | train | def deliver_response(response, pending_request)
@request_stats.finish(pending_request.receive_time, response.token)
@pending_requests.delete(response.token) if pending_request.kind == :send_request
if (parent_token = pending_request.retry_parent_token)
@pending_requests.reject! { |k, v| k == parent_token || v.retry_parent_token == parent_token }
end
pending_request.response_handler.call(response) if pending_request.response_handler
true
end | ruby | {
"resource": ""
} |
q694 | RightScale.RightHttpClient.init | train | def init(auth_client, options = {})
raise ArgumentError, "No authorization client provided" unless auth_client.is_a?(AuthClient)
@status = {}
callback = lambda { |type, state| update_status(type, state) }
@auth = auth_client
@status[:auth] = @auth.status(&callback)
@router = RouterClient.new(@auth, options)
@status[:router] = @router.status(&callback)
if @auth.api_url
@api = ApiClient.new(@auth, options)
@status[:api] = @api.status(&callback)
end
true
end | ruby | {
"resource": ""
} |
q695 | RightScale.RightHttpClient.push | train | def push(type, payload = nil, target = nil, options = {})
raise RuntimeError, "#{self.class.name}#init was not called" unless @auth
client = (@api && @api.support?(type)) ? @api : @router
client.push(type, payload, target, options)
end | ruby | {
"resource": ""
} |
q696 | RightScale.RightHttpClient.communicated | train | def communicated(types = [], &callback)
raise RuntimeError, "#{self.class.name}#init was not called" unless @auth
@auth.communicated(&callback) if types.empty? || types.include?(:auth)
@api.communicated(&callback) if @api && (types.empty? || types.include?(:api))
@router.communicated(&callback) if @router && (types.empty? || types.include?(:router))
true
end | ruby | {
"resource": ""
} |
q697 | RightScale.EnrollmentResult.to_s | train | def to_s
@serializer.dump({
'r_s_version' => @r_s_version.to_s,
'timestamp' => @timestamp.to_i.to_s,
'iv' => Base64::encode64(@iv).chop,
'ciphertext' => Base64::encode64(@ciphertext).chop,
'mac' => Base64::encode64(@mac).chop
})
end | ruby | {
"resource": ""
} |
q698 | RightScale.AuthClient.check_authorized | train | def check_authorized
if state == :expired
raise Exceptions::RetryableError, "Authorization expired"
elsif state != :authorized
raise Exceptions::Unauthorized, "Not authorized with RightScale" if state != :authorized
end
true
end | ruby | {
"resource": ""
} |
q699 | RightScale.DevRepository.to_scraper_hash | train | def to_scraper_hash
repo = {}
repo[:repo_type] = repo_type.to_sym unless repo_type.nil?
repo[:url] = url
repo[:tag] = tag
repo[:resources_path] = cookbooks_path
if !ssh_key.nil?
repo[:first_credential] = ssh_key
elsif !(username.nil? && password.nil?)
repo[:first_credential] = dev_repo.username
repo[:second_credential] = dev_repo.password
end
repo
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.