_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
30
4.3k
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)
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 }
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")
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
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
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)
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,
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
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
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)
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"
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]}
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,
ruby
{ "resource": "" }
q713
RightScale.Agent.create_dispatchers
train
def create_dispatchers cache = DispatchedCache.new(@identity) if @options[:dup_check] @dispatcher = Dispatcher.new(self, cache)
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
ruby
{ "resource": "" }
q715
RightScale.Agent.setup_http
train
def setup_http(auth_client) @auth_client = auth_client if @mode == :http RightHttpClient.init(@auth_client,
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
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
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 =>
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)
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
ruby
{ "resource": "" }
q721
RightScale.Agent.deliver_response
train
def deliver_response(result) begin @sender.handle_response(result) rescue StandardError => e
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)
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}}
ruby
{ "resource": "" }
q724
RightScale.Agent.stop_gracefully
train
def stop_gracefully(timeout) if @mode == :http @client.close else @client.unusable.each {
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
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
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
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
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
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 {}) ||
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'
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(/@/, '')
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 :
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(',
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
ruby
{ "resource": "" }
q736
RightScale.RouterClient.push
train
def push(type, payload, target, options = {}) params = { :type => type, :payload => payload, :target =>
ruby
{ "resource": "" }
q737
RightScale.RouterClient.request
train
def request(type, payload, target, options = {}) params = { :type => type, :payload => payload, :target =>
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}" : ""
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
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
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
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,
ruby
{ "resource": "" }
q743
RightScale.RouterClient.try_connect
train
def try_connect(routing_keys, &handler) connect(routing_keys, &handler) update_listen_state(:check, 1)
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
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)
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|
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)
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
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]
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]
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
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
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
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,
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
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
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}
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
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]
ruby
{ "resource": "" }
q760
RightScale.BaseRetryClient.wait
train
def wait(interval) if @options[:non_blocking] fiber = Fiber.current
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
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 =
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']
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
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
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',
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)
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"
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)
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
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)
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
ruby
{ "resource": "" }
q773
RightScale.Certificate.save
train
def save(file) File.open(file, "w") do |f|
ruby
{ "resource": "" }
q774
RightScale.History.load
train
def load events = [] File.open(@history, "r") { |f| events = f.readlines.map { |l|
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"
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|
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]
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"}
ruby
{ "resource": "" }
q779
RightScale.ApiClient.query_by_resource
train
def query_by_resource(verb, hrefs, action, options) path = "/tags/by_resource"
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] =
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]
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
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)
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
ruby
{ "resource": "" }
q785
Mumukit.Assistant.assist_with
train
def assist_with(submission) @rules .select { |it| it.matches?(submission) }
ruby
{ "resource": "" }
q786
DeepMerge.RailsCompat.ko_deeper_merge!
train
def ko_deeper_merge!(source, options = {}) default_opts = {:knockout_prefix => "--", :preserve_unmergeables => false}
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 =>
ruby
{ "resource": "" }
q788
Gnuplot.Plot.set
train
def set ( var, value = "" ) value = "\"#{value}\"" if QUOTED.include?
ruby
{ "resource": "" }
q789
JOSE.JWT.merge
train
def merge(object) object = case object when JOSE::Map, Hash object when String JOSE.decode(object)
ruby
{ "resource": "" }
q790
JOSE.JWK.block_encrypt
train
def block_encrypt(plain_text, jwe = nil) jwe ||= block_encryptor
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],
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',
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
ruby
{ "resource": "" }
q794
JOSE.JWK.sign
train
def sign(plain_text, jws = nil, header = nil) jws ||= signer return
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)
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,
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',
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
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),
ruby
{ "resource": "" }