_id
stringlengths 2
6
| title
stringlengths 9
130
| partition
stringclasses 3
values | text
stringlengths 30
4.3k
| 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)))
| 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) | ruby | {
"resource": ""
} |
q602 | Topsy.Client.search_count | train | def search_count(q)
counts = handle_response(get("/searchcount.json", | 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" , | ruby | {
"resource": ""
} |
q604 | Topsy.Client.stats | train | def stats(url, options={})
query = {:url => url}
query.merge!(options)
response = handle_response(get("/stats.json", | ruby | {
"resource": ""
} |
q605 | Topsy.Client.tags | train | def tags(url, options={})
response = handle_response(get("/tags.json", :query => {:url => | ruby | {
"resource": ""
} |
q606 | Topsy.Client.trending | train | def trending(options={})
response = handle_response(get("/trending.json", :query => options))
| ruby | {
"resource": ""
} |
q607 | Topsy.Client.url_info | train | def url_info(url)
response = handle_response(get("/urlinfo.json", :query => {:url => | ruby | {
"resource": ""
} |
q608 | Topsy.Client.extract_header_value | train | def extract_header_value(response, key)
response.headers[key].class | 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 | ruby | {
"resource": ""
} |
q610 | RightScale.NonBlockingClient.beautify_headers | train | def beautify_headers(headers)
headers.inject({}) { |out, (key, value)| out[key.gsub(/-/, | 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)
| ruby | {
"resource": ""
} |
q612 | RightScale.AgentTagManager.query_tags | train | def query_tags(tags, options = {})
tags = ensure_flat_array_value(tags) unless tags.nil? || tags.empty?
| 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?
| 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?
| 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
| 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
| ruby | {
"resource": ""
} |
q617 | RightScale.ErrorTracker.init | train | def init(agent, agent_name, options = {})
@agent = agent
@trace_level = options[:trace_level] || {}
| 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)
| 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)
| 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"]
| ruby | {
"resource": ""
} |
q621 | RightScale.ErrorTracker.notify_callback | train | def notify_callback
Proc.new do |exception, packet, agent, component|
| 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]
| ruby | {
"resource": ""
} |
q623 | RightScale.ErrorTracker.filter | train | def filter(params)
if @filter_params
filtered_params = {}
params.each | 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 - | 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
| 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 | ruby | {
"resource": ""
} |
q627 | RightScale.DispatchedCache.serviced_by | train | def serviced_by(token)
if @cache[token]
@cache[token] = Time.now.to_i
| ruby | {
"resource": ""
} |
q628 | RightScale.DispatchedCache.stats | train | def stats
if (s = size) > 0
now = Time.now.to_i
{
"local total" | 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)
| 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 => | 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)
| 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
| 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]) &&
| ruby | {
"resource": ""
} |
q634 | RightScale.AgentController.configure_proxy | train | def configure_proxy(proxy_setting, exceptions)
ENV['HTTP_PROXY'] = proxy_setting
ENV['http_proxy'] = proxy_setting
| 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, | ruby | {
"resource": ""
} |
q636 | RightScale.Multiplexer.method_missing | train | def method_missing(m, *args)
res = @targets.inject([]) { |res, t| res | ruby | {
"resource": ""
} |
q637 | RightScale.Multiplexer.respond_to? | train | def respond_to?(m, *args)
super(m, *args) || @targets.all? { |t| | 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' + | ruby | {
"resource": ""
} |
q639 | RightScale.OperationResult.truncated_error | train | def truncated_error
e = @content.is_a?(String) ? @content : @content.inspect
e = e[0, | 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', | ruby | {
"resource": ""
} |
q641 | RightScale.CommandIO.reply | train | def reply(conn, data, close_after_writing=true)
conn.send_data(CommandSerializer.dump(data))
| 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
| 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 = | 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
| 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 | ruby | {
"resource": ""
} |
q646 | RightScale.CommonParser.agent_type | train | def agent_type(type, name)
unless type
if name =~ /^(.*)_[0-9]+$/
type = Regexp.last_match(1)
| 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 += | 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)
| 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
| 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
| 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 | ruby | {
"resource": ""
} |
q652 | RightScale.BalancedHttpClient.request_headers | train | def request_headers(request_uuid, options)
headers = {"X-Request-Lineage-Uuid" => request_uuid, :accept => "application/json"}
| 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)
| 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]
| 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
| 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}> | 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)
| 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
| 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
| ruby | {
"resource": ""
} |
q660 | RightScale.BalancedHttpClient.split | train | def split(object, pattern = /,\s*/)
object ? (object.is_a?(Array) ? object | ruby | {
"resource": ""
} |
q661 | RightScale.StatsManager.manage | train | def manage(options)
init_log if options[:verbose]
AgentConfig.cfg_dir = options[:cfg_dir]
options[:timeout] ||= | 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
| 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) | ruby | {
"resource": ""
} |
q664 | RightScale.OfflineHandler.disable | train | def disable
if offline? && @state != :created
Log.info("[offline] Connection to RightNet re-established")
@offline_stats.finish
| 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) >= | 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 | 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),
| 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 = | 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 | 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, | 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 - | 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, | 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
| 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 | 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 | 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],
| 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 { | 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])
| ruby | {
"resource": ""
} |
q679 | RightScale.Sender.send_push | train | def send_push(type, payload = nil, target = nil, options = {}, &callback) | 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
| 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)
| 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])
| 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}")
| 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)
| ruby | {
"resource": ""
} |
q685 | RightScale.Sender.dump_requests | train | def dump_requests
info = []
if @pending_requests
@pending_requests.kind(:send_request).each do |token, request|
| 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)
| 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
| 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)
| 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
| 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")
| 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 + | 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)
| 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)
| 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] | ruby | {
"resource": ""
} |
q695 | RightScale.RightHttpClient.push | train | def push(type, payload = nil, target = nil, options = {})
raise RuntimeError, "#{self.class.name}#init was | 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? | 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,
| ruby | {
"resource": ""
} |
q698 | RightScale.AuthClient.check_authorized | train | def check_authorized
if state == :expired
raise Exceptions::RetryableError, "Authorization expired"
elsif state != :authorized
| 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
| ruby | {
"resource": ""
} |