idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
15,300
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_pref...
Initialize registry Register as an actor
15,301
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
Initialize cache Add item to cache
15,302
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
Retrieve item from cache Store item returned by given block if any
15,303
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
Delete item from cache
15,304
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
Create client for making HTTP REST requests
15,305
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...
Construct headers for request
15,306
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 [ re...
Make REST request
15,307
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 ] result , code , body , headers = rest_request ( :get , path , connect_option...
Make long - polling request
15,308
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 . includ...
Handle no result from balancer Distinguish the not responding case since it likely warrants a retry by the client Also try to distinguish between the targeted server not responding and that server gatewaying to another server that is not responding so that the receiver of the resulting exception is clearer as to the so...
15,309
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 || ...
Log successful request completion
15,310
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...
Log request failure Also report it as audit entry if an instance is targeted
15,311
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
Generate log text describing request and failure if any
15,312
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 ) :...
Apply parameter hiding filter
15,313
def split ( object , pattern = / \s / ) object ? ( object . is_a? ( Array ) ? object : object . split ( pattern ) ) : [ ] end
Split string into an array unless nil or already an array
15,314
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
Initialize manager Handle stats request
15,315
def request_stats ( options ) agent_names = if options [ :agent_name ] [ options [ :agent_name ] ] else AgentConfig . cfg_agents end fail ( "No agents configured" ) if agent_names . empty? count = 0 agent_names . each do | agent_name | begin count += 1 if request_agent_stats ( agent_name , options ) rescue Exception =>...
Request and display statistics for agents
15,316
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 , :res...
Request and display statistics for agent
15,317
def disable if offline? && @state != :created Log . info ( "[offline] Connection to RightNet re-established" ) @offline_stats . finish cancel_timer @state = :flushing EM . add_timer ( rand ( MAX_QUEUE_FLUSH_DELAY ) ) { flush } end true end
Switch back to sending requests after in - memory queue gets flushed Idempotent
15,318
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...
Queue given request in memory
15,319
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 ...
Send any requests that were queued while in offline mode and have not yet timed out Do this asynchronously to allow for agents to respond to requests Once all in - memory requests have been flushed switch off offline mode
15,320
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 ...
Compute a cryptographic hash of the information in this policy ; helps callers compare two policies to see if they are equivalent .
15,321
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_TIMEOU...
Make HTTP request
15,322
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 + Bala...
Make long - polling requests until receive data hit error or timeout
15,323
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...
Make HTTP request once
15,324
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
Create cache Store pending request
15,325
def deploy ( options ) AgentConfig . root_dir = options [ :root_dir ] AgentConfig . cfg_dir = options [ :cfg_dir ] AgentConfig . pid_dir = options [ :pid_dir ] cfg = load_init_cfg check_agent ( options , cfg ) cfg = configure ( options , cfg ) persist ( options , cfg ) monitor ( options ) if options [ :monit ] true end
Generate configuration from specified options and the agent s base options and write them to a file
15,326
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
Load initial configuration for agent if any
15,327
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...
Check agent type consistency and existence of initialization file and actors directory
15,328
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 [ :qui...
Write configuration options to file after applying any overrides
15,329
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 [ :passwo...
Add a repository ...
15,330
def list_command ( opts ) usage = "Agent exposes the following commands:\n" COMMANDS . reject { | k , _ | k == :list || k . to_s =~ / / } . each do | c | c . each { | k , v | usage += " - #{k.to_s}: #{v}\n" } end CommandIO . instance . reply ( opts [ :conn ] , usage ) end
List command implementation
15,331
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
Set log level command
15,332
def send_push ( type , payload = nil , target = nil , options = { } , & callback ) build_and_send_packet ( :send_push , type , payload , target , options , & callback ) end
Send a request to a single target or multiple targets with no response expected other than routing failures Persist the request en route to reduce the chance of it being lost at the expense of some additional network overhead Enqueue the request if the target is not currently available Never automatically retry the req...
15,333
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
Send a request to a single target with a response expected Automatically retry the request if a response is not received in a reasonable amount of time or if there is a non - delivery response indicating the target is not currently available Timeout the request if a response is not received in time typically configured...
15,334
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 ...
Build and send packet
15,335
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 ...
Build packet or queue it if offline
15,336
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 ....
Handle response to a request
15,337
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
Take any actions necessary to quiesce client interaction in preparation for agent termination but allow message receipt to continue
15,338
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
Create displayable dump of unfinished non - push request information Truncate list if there are more than 50 requests
15,339
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_...
Get sender statistics
15,340
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 ...
Reset dispatch statistics
15,341
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}...
Send request via HTTP Use next_tick for asynchronous response and to ensure that the request is sent using the main EM reactor thread
15,342
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 ( @age...
Send request via HTTP and then immediately handle response
15,343
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 i...
Send request via AMQP If lack connectivity and queueing enabled queue request
15,344
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 , :persisten...
Send request via AMQP without retrying Use mandatory flag to request return of message if it cannot be delivered
15,345
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_timeo...
Send request via AMQP with one or more retries if do not receive a response in time Send timeout result if reach configured retry timeout limit Use exponential backoff with RETRY_BACKOFF_FACTOR for retry spacing Adjust retry interval by average response time to avoid adding to system load when system gets slow Rotate t...
15,346
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 | ...
Deliver the response and remove associated non - push requests from pending including all associated retry requests
15,347
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 . n...
Initialize RightNet client Must be called before any other functions are usable
15,348
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
Route a request to a single target or multiple targets with no response expected Persist the request en route to reduce the chance of it being lost at the expense of some additional network overhead Enqueue the request if the target is not currently available Never automatically retry the request if there is the possib...
15,349
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 . communicate...
Set callback for each successful communication excluding health checks
15,350
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
Create a new instance of this class
15,351
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
Check whether authorized
15,352
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 ...
Maps the given DevRepository to a has that can be consumed by the RightScraper gem
15,353
def is_valid? result = false == is_blank? ( @volume_id ) && false == is_blank? ( @device_name ) && false == is_blank? ( @volume_status ) && false == is_blank? ( @mount_points ) && nil == @mount_points . find { | mount_point | is_blank? ( mount_point ) } return result end
Determines if this object is valid .
15,354
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 , :air...
Initialize the new agent
15,355
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}"...
Connect to an additional AMQP broker or reconnect it if connection has failed Subscribe to identity queue on this broker Update config file if this is a new broker Assumes already has credentials on this broker and identity queue exists
15,356
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 ) @con...
Disconnect from an AMQP broker and optionally remove it from the configuration Refuse to do so if it is the last connected broker
15,357
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 =...
There were problems while setting up service for this agent on the given AMQP brokers so mark these brokers as failed if not currently connected and later during the periodic status check attempt to reconnect
15,358
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_cr...
Gracefully terminate execution by allowing unfinished tasks to complete Immediately terminate if called a second time Report reason for termination if it is abnormal
15,359
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 st...
Retrieve statistics about agent operation
15,360
def agent_stats ( reset = false ) stats = { "request failures" => @request_failure_stats . all , "response failures" => @response_failure_stats . all } . merge ( ErrorTracker . stats ( reset ) ) if @mode != :http stats [ "connect requests" ] = @connect_request_stats . all stats [ "non-deliveries" ] = @non_delivery_stat...
Get request statistics
15,361
def reset_agent_stats @connect_request_stats = RightSupport :: Stats :: Activity . new ( measure_rate = false ) @non_delivery_stats = RightSupport :: Stats :: Activity . new @request_failure_stats = RightSupport :: Stats :: Activity . new @response_failure_stats = RightSupport :: Stats :: Activity . new true end
Reset agent statistics
15,362
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 ] |...
Set the agent s configuration using the supplied options
15,363
def handle_event ( event ) if event . is_a? ( Hash ) if [ "Push" , "Request" ] . include? ( event [ :type ] ) 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 Dispat...
Handle events received by this agent
15,364
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...
Convert event hash to packet
15,365
def result_to_event ( result ) { :type => "Result" , :from => result . from , :data => { :result => result . results , :duration => result . duration , :request_uuid => result . token , :request_from => result . request_from } } end
Convert result packet to event
15,366
def create_dispatchers cache = DispatchedCache . new ( @identity ) if @options [ :dup_check ] @dispatcher = Dispatcher . new ( self , cache ) @queues . inject ( { } ) { | dispatchers , queue | dispatchers [ queue ] = @dispatcher ; dispatchers } end
Create dispatcher per queue for use in handling incoming requests
15,367
def load_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 . ...
Load the ruby code for the actors
15,368
def setup_http ( auth_client ) @auth_client = auth_client if @mode == :http RightHttpClient . init ( @auth_client , @options . merge ( :retry_enabled => true ) ) @client = RightHttpClient . instance end true end
Create client for HTTP - based RightNet communication The code loaded with the actors specific to this application is responsible for calling this function
15,369
def setup_status @status = { } if @client if @mode == :http @status = @client . status { | type , state | update_status ( type , state ) } . dup else @client . connection_status { | state | update_status ( :broker , state ) } @status [ :broker ] = :connected @status [ :auth ] = @auth_client . status { | type , state | ...
Setup client status collection
15,370
def setup_non_delivery @client . non_delivery do | reason , type , token , from , to | begin @non_delivery_stats . update ( type ) reason = case reason when "NO_ROUTE" then OperationResult :: NO_ROUTE_TO_TARGET when "NO_CONSUMERS" then OperationResult :: TARGET_NOT_CONNECTED else reason . to_s end result = Result . new...
Setup non - delivery handler
15,371
def setup_queue ( name , ids = nil ) queue = { :name => name , :options => { :durable => true , :no_declare => @options [ :secure ] } } filter = [ :from , :tags , :tries , :persistent ] options = { :ack => true , Push => filter , Request => filter , Result => [ :from ] , :brokers => ids } @client . subscribe ( queue , ...
Setup queue for this agent
15,372
def handle_packet ( queue , packet , header ) begin case packet when Push , Request then dispatch_request ( packet , queue ) when Result then deliver_response ( packet ) end @sender . message_received rescue Exception => e ErrorTracker . log ( self , "#{queue} queue processing error" , e ) ensure header . ack end true ...
Handle packet from queue
15,373
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 , :persi...
Dispatch request and then send response if any
15,374
def deliver_response ( result ) begin @sender . handle_response ( result ) rescue StandardError => e ErrorTracker . log ( self , "Failed to deliver response #{result.trace}" , e ) @response_failure_stats . update ( e . class . name ) end true end
Deliver response to request sender
15,375
def finish_setup @client . failed . each do | id | p = { :agent_identity => @identity } p [ :host ] , p [ :port ] , p [ :id ] , p [ :priority ] = @client . identity_parts ( id ) @sender . send_push ( "/registrar/connect" , p ) end true end
Finish any remaining agent setup
15,376
def publish_stats s = stats ( { } ) . content if @mode == :http @client . notify ( { :type => "Stats" , :from => @identity , :data => s } , nil ) else exchange = { :type => :topic , :name => "stats" , :options => { :no_declare => true } } @client . publish ( exchange , Stats . new ( s , @identity ) , :no_log => true , ...
Publish current stats
15,377
def stop_gracefully ( timeout ) if @mode == :http @client . close else @client . unusable . each { | id | @client . close_one ( id , propagate = false ) } end finish_terminating ( timeout ) end
Gracefully stop processing Close clients except for authorization
15,378
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 . d...
Finish termination after all requests have been processed
15,379
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 && @pend...
Send command to running agent
15,380
def check if pid = read_pid [ :pid ] if process_running? ( pid ) raise AlreadyRunning . new ( "#{@pid_file} already exists and process is running (pid: #{pid})" ) else Log . info ( "Removing stale pid file: #{@pid_file}" ) remove end end true end
Initialize pid file location from agent identity and pid directory Check whether pid file can be created Delete any existing pid file if process is not running anymore
15,381
def write begin FileUtils . mkdir_p ( @pid_dir ) open ( @pid_file , 'w' ) { | f | f . write ( Process . pid ) } File . chmod ( 0644 , @pid_file ) rescue StandardError => e ErrorTracker . log ( self , "Failed to create PID file" , e , nil , :caller ) raise end true end
Write pid to pid file
15,382
def set_command_options ( options ) content = { :listen_port => options [ :listen_port ] , :cookie => options [ :cookie ] } content [ :cookie ] . force_encoding ( 'utf-8' ) open ( @cookie_file , 'w' ) { | f | f . write ( YAML . dump ( content ) ) } File . chmod ( 0600 , @cookie_file ) true end
Update associated command protocol port
15,383
def read_pid content = { } if exists? open ( @pid_file , 'r' ) { | f | content [ :pid ] = f . read . to_i } open ( @cookie_file , 'r' ) do | f | command_options = ( YAML . load ( f . read ) rescue { } ) || { } content . merge! ( command_options ) end if File . readable? ( @cookie_file ) end content end
Read pid file content Empty hash if pid file does not exist or content cannot be loaded
15,384
def to_msgpack ( * a ) msg = { 'msgpack_class' => self . class . name , 'data' => instance_variables . inject ( { } ) do | m , ivar | name = ivar . to_s . sub ( / / , '' ) m [ name ] = instance_variable_get ( ivar ) unless NOT_SERIALIZED . include? ( name ) m end , 'size' => nil } . to_msgpack ( * a ) @size = msg . siz...
Marshal packet into MessagePack format
15,385
def to_json ( * a ) class_name = self . class . name if class_name =~ / / class_name = "Nanite::" + Regexp . last_match ( 1 ) end js = { 'json_class' => class_name , 'data' => instance_variables . inject ( { } ) do | m , ivar | name = ivar . to_s . sub ( / / , '' ) m [ name ] = instance_variable_get ( ivar ) unless NOT...
Marshal packet into JSON format
15,386
def enough_precision ( value ) scale = [ 1.0 , 10.0 , 100.0 , 1000.0 , 10000.0 , 100000.0 ] enough = lambda { | v | ( v >= 10.0 ? 0 : ( v >= 1.0 ? 1 : ( v >= 0.1 ? 2 : ( v >= 0.01 ? 3 : ( v > 0.001 ? 4 : ( v > 0.0 ? 5 : 0 ) ) ) ) ) ) } digit_str = lambda { | p , v | sprintf ( "%.#{p}f" , ( v * scale [ p ] ) . round / s...
Determine enough precision for floating point value to give at least two significant digits and then convert the value to a decimal digit string of that precision
15,387
def ids_to_s ( ids ) if ids . is_a? ( Array ) s = ids . each { | i | id_to_s ( i ) } . join ( ', ' ) s . size > 1000 ? "[#{s[0, 1000]}...]" : "[#{s}]" else id_to_s ( ids ) end end
Generate log friendly serialized identity for one or more ids Limit to 1000 bytes
15,388
def trace audit_id = self . respond_to? ( :payload ) && payload . is_a? ( Hash ) && ( payload [ 'audit_id' ] || payload [ :audit_id ] ) tok = self . respond_to? ( :token ) && token tr = "<#{audit_id || nil}> <#{tok}>" end
Generate token used to trace execution of operation across multiple packets
15,389
def push ( type , payload , target , options = { } ) params = { :type => type , :payload => payload , :target => target } make_request ( :post , "/push" , params , type . split ( "/" ) [ 2 ] , options ) end
Create RightNet router client
15,390
def request ( type , payload , target , options = { } ) params = { :type => type , :payload => payload , :target => target } make_request ( :post , "/request" , params , type . split ( "/" ) [ 2 ] , options ) end
Route a request to a single target with a response expected Automatically retry the request if a response is not received in a reasonable amount of time or if there is a non - delivery response indicating the target is not currently available Timeout the request if a response is not received in time typically configure...
15,391
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 ? " ...
Route event Use WebSocket if possible Do not block this request even if in the process of closing since used for request responses
15,392
def listen ( routing_keys , & handler ) raise ArgumentError , "Block missing" unless block_given? @event_uuids = nil @listen_interval = 0 @listen_state = :choose @listen_failures = 0 @connect_interval = CONNECT_INTERVAL @reconnect_interval = RECONNECT_INTERVAL listen_loop ( routing_keys , & handler ) true end
Receive events via an HTTP WebSocket if available otherwise via an HTTP long - polling
15,393
def listen_loop ( routing_keys , & handler ) @listen_timer = nil begin case @listen_state when :choose choose_listen_method when :check 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 ...
Perform listen action then wait prescribed time for next action A periodic timer is not effective here because it does not wa
15,394
def listen_loop_wait ( started_at , interval , routing_keys , & handler ) if @listen_interval == 0 EM_S . next_tick { listen_loop ( routing_keys , & handler ) } else @listen_timer = EM_S :: Timer . new ( interval ) do remaining = @listen_interval - ( Time . now - started_at ) if remaining > 0 listen_loop_wait ( started...
Wait specified interval before next listen loop Continue waiting if interval changes while waiting
15,395
def update_listen_state ( state , interval = 0 ) if state == :cancel @listen_timer . cancel if @listen_timer @listen_timer = nil @listen_state = state elsif [ :choose , :check , :connect , :long_poll , :wait ] . include? ( state ) @listen_checks = 0 if state == :check && @listen_state != :check @listen_state = state @l...
Update listen state
15,396
def try_connect ( routing_keys , & handler ) connect ( routing_keys , & handler ) update_listen_state ( :check , 1 ) rescue Exception => e ErrorTracker . log ( self , "Failed creating WebSocket" , e , nil , :caller ) backoff_connect_interval update_listen_state ( :long_poll ) end
Try to create WebSocket connection
15,397
def connect ( routing_keys , & handler ) raise ArgumentError , "Block missing" unless block_given? @attempted_connect_at = Time . now @close_code = @close_reason = nil if ( v = BalancedHttpClient :: PROXY_ENVIRONMENT_VARIABLES . detect { | v | ENV . has_key? ( v ) } ) proxy_uri = ENV [ v ] . match ( / \/ \/ / ) ? URI ....
Connect to RightNet router using WebSocket for receiving events
15,398
def try_long_poll ( routing_keys , event_uuids , & handler ) begin long_poll ( routing_keys , event_uuids , & handler ) rescue Exception => e e end end
Try to make long - polling request to receive events
15,399
def try_deferred_long_poll ( routing_keys , event_uuids , & handler ) @defer_operation_proc = Proc . new { try_long_poll ( routing_keys , event_uuids , & handler ) } @defer_callback_proc = Proc . new { | result | @event_uuids = process_long_poll ( result ) } EM . defer ( @defer_operation_proc , @defer_callback_proc ) t...
Try to make long - polling request to receive events using EM defer thread Repeat long - polling until there is an error or the stop time has been reached