idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
6,400
def websocket_exec ( path , cmd , interactive : false , shell : false , tty : false ) exit_status = nil write_thread = nil query = { } query [ :interactive ] = interactive if interactive query [ :shell ] = shell if shell query [ :tty ] = tty if tty server = require_current_master url = websocket_url ( path , query ) to...
Connect to server websocket send from stdin and write out messages
6,401
def update_membership ( node ) info 'checking if etcd previous membership needs to be updated' etcd_connection = find_etcd_node ( node ) return 'new' unless etcd_connection weave_ip = node . overlay_ip peer_url = "http://#{weave_ip}:2380" client_url = "http://#{weave_ip}:2379" members = JSON . parse ( etcd_connection ....
Removes possible previous member with the same IP
6,402
def find_etcd_node ( node ) grid_subnet = IPAddr . new ( node . grid [ 'subnet' ] ) tries = node . grid [ 'initial_size' ] begin etcd_host = "http://#{grid_subnet[tries]}:2379/v2/members" info "connecting to existing etcd at #{etcd_host}" connection = Excon . new ( etcd_host ) members = JSON . parse ( connection . get ...
Finds a working etcd node from set of initial nodes
6,403
def add_membership ( connection , peer_url ) info "Adding new etcd membership info with peer URL #{peer_url}" connection . post ( :body => JSON . generate ( peerURLs : [ peer_url ] ) , :headers => { 'Content-Type' => 'application/json' } ) end
Add new peer membership
6,404
def update ( value ) raise RuntimeError , "Observable crashed: #{@value}" if crashed? raise ArgumentError , "Update with nil value" if value . nil? debug { "update: #{value}" } set_and_notify ( value ) end
The Observable has a value . Propagate it to any observers .
6,405
def volume_exist? ( volume_name , driver ) begin debug "volume #{volume_name} exists" volume = Docker :: Volume . get ( volume_name ) if volume && volume . info [ 'Driver' ] == driver return true elsif volume && volume . info [ 'Driver' ] != driver raise DriverMismatchError . new ( "Volume driver not as expected. Expec...
Checks if given volume exists with the expected driver
6,406
def on_container_die ( exit_code : ) cancel_restart_timers return unless @service_pod . running? backoff = @restarts ** 2 backoff = max_restart_backoff if backoff > max_restart_backoff info "#{@service_pod} exited with code #{exit_code}, restarting (delay: #{backoff}s)" log_service_pod_event ( "service:instance_crash" ...
Handles events when container has died
6,407
def restart ( at = Time . now , container_id : nil , started_at : nil ) if container_id && @container . id != container_id debug "stale #{@service_pod} restart for container id=#{container_id}" return end if started_at && @container . started_at != started_at debug "stale #{@service_pod} restart for container started_a...
User requested service restart
6,408
def check_starting! ( service_pod , container ) raise "service stopped" if ! @service_pod . running? raise "service redeployed" if @service_pod . deploy_rev != service_pod . deploy_rev raise "container recreated" if @container . id != container . id raise "container restarted" if @container . started_at != container . ...
Check that the given container is still running for the given service pod revision .
6,409
def document_changes ( document ) ( document . changed + document . _children . select { | child | child . changed? } . map { | child | "#{child.metadata_name.to_s}{#{child.changed.join(", ")}}" } ) . join ( ", " ) end
List changed fields of model
6,410
def save_grid_service ( grid_service ) if grid_service . save return grid_service else grid_service . errors . each do | key , message | add_error ( key , :invalid , message ) end return nil end end
Adds errors if save fails
6,411
def update_grid_service ( grid_service , force : false ) if grid_service . changed? || force grid_service . revision += 1 info "updating service #{grid_service.to_path} revision #{grid_service.revision} with changes: #{document_changes(grid_service)}" else debug "not updating service #{grid_service.to_path} revision #{...
Bump grid_service . revision if changed or force and save Adds errors if save fails
6,412
def error @values . each_pair { | observable , value | return Error . new ( observable , value ) if Exception === value } return nil end
Return Error for first crashed observable .
6,413
def each ( timeout : nil ) @deadline = Time . now + timeout if timeout while true Celluloid . exclusive { if error? debug { "raise: #{self.describe_observables}" } raise self . error elsif ready? yield * self . values @deadline = Time . now + timeout if timeout end } debug { "wait: #{self.describe_observables}" } updat...
Yield each set of ready? observed values while alive or raise on error?
6,414
def validate_secrets validate_each :secrets do | s | secret = self . grid . grid_secrets . find_by ( name : s [ :secret ] ) unless secret [ :not_found , "Secret #{s[:secret]} does not exist" ] else nil end end end
Validates that the defined secrets exist
6,415
def validate_certificates validate_each :certificates do | c | cert = self . grid . certificates . find_by ( subject : c [ :subject ] ) unless cert [ :not_found , "Certificate #{c[:subject]} does not exist" ] else nil end end end
Validates that the defined certificates exist
6,416
def start ( ws ) @ws = ws @ws . on ( :message ) do | event | on_websocket_message ( event . data ) end @ws . on ( :error ) do | exc | warn exc end @ws . on ( :close ) do | event | on_websocket_close ( event . code , event . reason ) end started! end
Does not raise .
6,417
def parse_service_data_from_options data = { } data [ :strategy ] = deploy_strategy if deploy_strategy data [ :ports ] = parse_ports ( ports_list ) unless ports_list . empty? data [ :links ] = parse_links ( link_list ) unless link_list . empty? data [ :memory ] = parse_memory ( memory ) if memory data [ :memory_swap ] ...
parse given options to hash
6,418
def time_since ( time , terse : false ) return '' if time . nil? || time . empty? dt = Time . now - Time . parse ( time ) dt_s = dt . to_i dt_m , dt_s = dt_s / 60 , dt_s % 60 dt_h , dt_m = dt_m / 60 , dt_m % 60 dt_d , dt_h = dt_h / 60 , dt_h % 60 parts = [ ] parts << "%dd" % dt_d if dt_d > 0 parts << "%dh" % dt_h if dt...
Return an approximation of how long ago the given time was .
6,419
def connect! info "connecting to master at #{@api_uri}" headers = { 'Kontena-Node-Id' => @node_id . to_s , 'Kontena-Node-Name' => @node_name , 'Kontena-Version' => Kontena :: Agent :: VERSION , 'Kontena-Node-Labels' => @node_labels . join ( ',' ) , 'Kontena-Connected-At' => Time . now . utc . strftime ( STRFTIME ) , } ...
Connect to server and start connect_client task
6,420
def send_message ( msg ) ws . send ( msg ) rescue => exc warn exc abort exc end
Called from RpcServer does not crash the Actor on errors .
6,421
def on_error ( exc ) case exc when Kontena :: Websocket :: SSLVerifyError if exc . cert error "unable to connect to SSL server with KONTENA_SSL_VERIFY=true: #{exc} (subject #{exc.subject}, issuer #{exc.issuer})" else error "unable to connect to SSL server with KONTENA_SSL_VERIFY=true: #{exc}" end when Kontena :: Websoc...
Websocket connection failed
6,422
def on_close ( code , reason ) debug "Server closed connection with code #{code}: #{reason}" case code when 4001 handle_invalid_token when 4010 handle_invalid_version ( reason ) when 4040 , 4041 handle_invalid_connection ( reason ) else warn "connection closed with code #{code}: #{reason}" end end
Server closed websocket connection
6,423
def symbolize_path ( path ) path . gsub ( / \/ \/ / , '' ) . split ( '/' ) . map do | path_part | path_part . split ( '_' ) . map { | e | e . capitalize } . join end . map ( & :to_sym ) end
Create a subcommand loader instance
6,424
def authentication_ok? ( token_verify_path ) return false unless token return false unless token [ 'access_token' ] return false unless token_verify_path final_path = token_verify_path . gsub ( / \: \_ / , token [ 'access_token' ] ) debug { "Requesting user info from #{final_path}" } request ( path : final_path ) true ...
Requests path supplied as argument and returns true if the request was a success . For checking if the current authentication is valid .
6,425
def exchange_code ( code ) return nil unless token_account return nil unless token_account [ 'token_endpoint' ] response = request ( http_method : token_account [ 'token_method' ] . downcase . to_sym , path : token_account [ 'token_endpoint' ] , headers : { CONTENT_TYPE => token_account [ 'token_post_content_type' ] } ...
Calls the code exchange endpoint in token s config to exchange an authorization_code to a access_token
6,426
def get_stream ( path , response_block , params = nil , headers = { } , auth = true ) request ( path : path , query : params , headers : headers , response_block : response_block , auth : auth , gzip : false ) end
Get stream request
6,427
def request ( http_method : :get , path : '/' , body : nil , query : { } , headers : { } , response_block : nil , expects : [ 200 , 201 , 204 ] , host : nil , port : nil , auth : true , gzip : true ) retried ||= false if auth && token_expired? raise Excon :: Error :: Unauthorized , "Token expired or not valid, you need...
Perform a HTTP request . Will try to refresh the access token and retry if it s expired or if the server responds with HTTP 401 .
6,428
def token_account return { } unless token if token . respond_to? ( :account ) token . account elsif token . kind_of? ( Hash ) && token [ 'account' ] . kind_of? ( String ) config . find_account ( token [ 'account' ] ) else { } end rescue => ex error { "Access token refresh exception" } error { ex } false end
Accessor to token s account settings
6,429
def refresh_token debug { "Performing token refresh" } return false if token . nil? return false if token [ 'refresh_token' ] . nil? uri = URI . parse ( token_account [ 'token_endpoint' ] ) endpoint_data = { path : uri . path } endpoint_data [ :host ] = uri . host if uri . host endpoint_data [ :port ] = uri . port if u...
Perform refresh token request to auth provider . Updates the client s Token object and writes changes to configuration .
6,430
def encode_body ( body , content_type ) if content_type =~ JSON_REGEX dump_json ( body ) elsif content_type == CONTENT_URLENCODED && body . kind_of? ( Hash ) URI . encode_www_form ( body ) else body end end
Encode body based on content type .
6,431
def in_to_at ( expires_in ) if expires_in . to_i < 1 0 else Time . now . utc . to_i + expires_in . to_i end end
Convert expires_in into expires_at
6,432
def request ( method , params , timeout : 30 ) if ! wait_until ( "websocket client is connected" , timeout : timeout , threshold : 10.0 , interval : 0.1 ) { connected? } raise TimeoutError . new ( 500 , 'WebsocketClient is not connected' ) end id = request_id observable = @requests [ id ] = RequestObservable . new ( me...
Aborts caller on errors .
6,433
def reject! ( connected_at , code , reason ) self . update_node! ( connected_at , connected : false , updated : false , websocket_connection : { opened : false , close_code : code , close_reason : reason , } , ) info "Rejected connection for node #{@node.to_path} at #{connected_at} with code #{code}: #{reason}" rescue ...
Connection was rejected
6,434
def sort_services ( services ) service_links = { } services . each do | service | service_links [ service [ :name ] ] = __links_for_service ( service ) end service_links . each do | service , links | links . dup . each do | linked_service | if linked_service_links = service_links [ linked_service ] service_links [ serv...
Sort services with a stack such that services come after any services that they link to . This can only be used to sort services within the same stack . Links to services in other stacks are ignored .
6,435
def grid_health ( grid , nodes ) initial = grid [ 'initial_size' ] minimum = grid [ 'initial_size' ] / 2 + 1 online = nodes . select { | node | node [ 'initial_member' ] && node [ 'connected' ] } if online . length < minimum return :error elsif online . length < initial return :warning else return :ok end end
Validate grid nodes configuration and status
6,436
def stack @stack ||= reader . execute ( name : stack_name , parent_name : self . respond_to? ( :parent_name ) ? self . parent_name : nil , values : ( self . respond_to? ( :values_from_options ) ? self . values_from_options : { } ) ) end
An accessor to the YAML Reader outcome . Passes parent name values from command line and the stackname to the reader .
6,437
def set_env_variables ( stack , grid , platform = grid ) ENV [ 'STACK' ] = stack ENV [ 'GRID' ] = grid ENV [ 'PLATFORM' ] = platform end
Sets environment variables from parameters
6,438
def stacks_client @stacks_client ||= Kontena :: StacksClient . new ( current_account . stacks_url , current_account . token , read_requires_token : current_account . stacks_read_authentication ) end
An accessor to stack registry client
6,439
def stack_upgraded? ( name ) old_stack = old_data . stack ( name ) new_stack = new_data . stack ( name ) return true if new_stack . root? return true if old_stack . version != new_stack . version return true if old_stack . stack_name != new_stack . stack_name return true if old_stack . variables != new_stack . variable...
Stack is upgraded if version stack name variables change or stack is root
6,440
def process_queue loop do sleep 1 until processing? buffer = @queue . shift ( BATCH_SIZE ) if buffer . size > 0 rpc_client . notification ( '/containers/log_batch' , [ buffer ] ) sleep 0.01 else sleep 1 end end end
Process items from
6,441
def start_streaming info 'start streaming logs from containers' Docker :: Container . all . each do | container | begin self . stream_container_logs ( container ) unless container . skip_logs? rescue Docker :: Error :: NotFoundError => exc warn exc . message rescue => exc error exc end end @streaming = true end
requires etcd to be available to read log timestamps
6,442
def stop_streaming @streaming = false info 'stop log streaming' @workers . keys . dup . each do | id | queued_item = @queue . find { | i | i [ :id ] == id } time = queued_item . nil? ? Time . now . to_i : Time . parse ( queued_item [ :time ] ) . to_i self . stop_streaming_container_logs ( id ) self . mark_timestamp ( i...
best - effort attempt to write etcd timestamps ; may not be possible
6,443
def process_data ( old_data , new_data ) logger . debug { "Master stacks: #{old_data.keys.join(",")} YAML stacks: #{new_data.keys.join(",")}" } new_data . reverse_each do | stackname , data | spinner "Processing stack #{pastel.cyan(stackname)}" process_stack_data ( stackname , data , old_data ) hint_on_validation_notif...
Preprocess data and return a ChangeResolver
6,444
def serve_one Kontena . logger . debug ( "LHWS" ) { "Waiting for connection on port #{port}.." } socket = server . accept content = socket . recvfrom ( 2048 ) . first . split ( / \r \n / ) request = content . shift headers = { } while line = content . shift break if line . nil? break if line == '' header , value = line...
Serve one request and return query params .
6,445
def handle return unless engine? return if decorators . empty? validate_decorators! validate_pattern_matching! engine . add_method_decorator ( method_type , method_name , decorator ) mark_pattern_matching_decorators method_reference . make_alias ( target ) redefine_method end
Creates new instance of MethodHandler
6,446
def make_definition ( this , & blk ) is_private = private? ( this ) is_protected = protected? ( this ) alias_target ( this ) . send ( :define_method , name , & blk ) make_private ( this ) if is_private make_protected ( this ) if is_protected end
Makes a method re - definition in proper way
6,447
def make_alias ( this ) _aliased_name = aliased_name original_name = name alias_target ( this ) . class_eval do alias_method _aliased_name , original_name end end
Aliases original method to a special unique name which is known only to this class . Usually done right before re - defining the method .
6,448
def flatten ( value , named = false ) return value unless value . instance_of? Array tag , * tail = value result = tail . map { | e | flatten ( e ) } case tag when :sequence return flatten_sequence ( result ) when :maybe return named ? result . first : result . first || '' when :repetition return flatten_repetition ( r...
Takes a mixed value coming out of a parslet and converts it to a return value for the user by dropping things and merging hashes .
6,449
def foldl ( list , & block ) return '' if list . empty? list [ 1 .. - 1 ] . inject ( list . first , & block ) end
Lisp style fold left where the first element builds the basis for an inject .
6,450
def flatten_sequence ( list ) foldl ( list . compact ) { | r , e | merge_fold ( r , e ) } end
Flatten results from a sequence of parslets .
6,451
def flatten_repetition ( list , named ) if list . any? { | e | e . instance_of? ( Hash ) } return list . select { | e | e . instance_of? ( Hash ) } end if list . any? { | e | e . instance_of? ( Array ) } return list . select { | e | e . instance_of? ( Array ) } . flatten ( 1 ) end return [ ] if named && list . empty? f...
Flatten results from a repetition of a single parslet . named indicates whether the user has named the result or not . If the user has named the results we want to leave an empty list alone - otherwise it is turned into an empty string .
6,452
def rule ( name , opts = { } , & definition ) undef_method name if method_defined? name define_method ( name ) do @rules ||= { } return @rules [ name ] if @rules . has_key? ( name ) definition_closure = proc { self . instance_eval ( & definition ) } @rules [ name ] = Atoms :: Entity . new ( name , opts [ :label ] , & d...
Define an entity for the parser . This generates a method of the same name that can be used as part of other patterns . Those methods can be freely mixed in your parser class with real ruby methods .
6,453
def raise ( exception_klass = Parslet :: ParseFailed ) exception = exception_klass . new ( self . to_s , self ) Kernel . raise exception end
Signals to the outside that the parse has failed . Use this in conjunction with . format for nice error messages .
6,454
def consume ( n ) position = self . pos slice_str = @str . scan ( @re_cache [ n ] ) slice = Parslet :: Slice . new ( position , slice_str , @line_cache ) return slice end
Consumes n characters from the input returning them as a slice of the input .
6,455
def construct_collection ( schema , instance , key , value ) schema [ key ] = instance . send ( key ) . map do | inst | call ( Copier . deep_copy ( value ) , inst ) end end
Makes the value of appropriate key of the schema an array and pushes in results of iterating through records and surrealizing them
6,456
def surrealize ( ** args ) return args [ :serializer ] . new ( self ) . surrealize ( args ) if args [ :serializer ] if ( serializer = find_serializer ( args [ :for ] ) ) return serializer . new ( self ) . surrealize ( args ) end Oj . dump ( Surrealist . build_schema ( instance : self , ** args ) , mode : :compat ) end
Dumps the object s methods corresponding to the schema provided in the object s class and type - checks the values .
6,457
def build_schema ( ** args ) return args [ :serializer ] . new ( self ) . build_schema ( args ) if args [ :serializer ] if ( serializer = find_serializer ( args [ :for ] ) ) return serializer . new ( self ) . build_schema ( args ) end Surrealist . build_schema ( instance : self , ** args ) end
Invokes + Surrealist + s class method + build_schema +
6,458
def build_schema ( ** args ) if Helper . collection? ( object ) build_collection_schema ( args ) else Surrealist . build_schema ( instance : self , ** args ) end end
Passes build_schema to Surrealist
6,459
def build_collection_schema ( ** args ) object . map { | object | self . class . new ( object , context ) . build_schema ( args ) } end
Maps collection and builds schema for each instance .
6,460
def parameters { camelize : camelize , include_root : include_root , include_namespaces : include_namespaces , root : root , namespaces_nesting_level : namespaces_nesting_level } end
Returns all arguments
6,461
def check_booleans! booleans_hash . each do | key , value | unless BOOLEANS . include? ( value ) raise ArgumentError , "Expected `#{key}` to be either true, false or nil, got #{value}" end end end
Checks all boolean arguments
6,462
def check_root! unless root . nil? || ( root . is_a? ( String ) && ! root . strip . empty? ) || root . is_a? ( Symbol ) Surrealist :: ExceptionRaiser . raise_invalid_root! ( root ) end end
Checks if root is not nil a non - empty string or symbol
6,463
def delegate_surrealization_to ( klass ) raise TypeError , "Expected type of Class got #{klass.class} instead" unless klass . is_a? ( Class ) Surrealist :: ExceptionRaiser . raise_invalid_schema_delegation! unless Helper . surrealist? ( klass ) hash = Surrealist :: VarsHelper . find_schema ( klass ) Surrealist :: VarsH...
A DSL method to delegate schema in a declarative style . Must reference a valid class that includes Surrealist
6,464
def surrealize_with ( klass , tag : Surrealist :: VarsHelper :: DEFAULT_TAG ) if klass < Surrealist :: Serializer Surrealist :: VarsHelper . add_serializer ( self , klass , tag : tag ) instance_variable_set ( VarsHelper :: PARENT_VARIABLE , klass . defined_schema ) else raise ArgumentError , "#{klass} should be inherit...
A DSL method for defining a class that holds serialization logic .
6,465
def fetch ( * queues ) job = nil transaction do command ( "FETCH" , * queues ) job = result! end JSON . parse ( job ) if job end
Returns either a job hash or falsy .
6,466
def beat transaction do command ( "BEAT" , %Q[{"wid":"#{@@random_process_wid}"}] ) str = result! if str == "OK" str else hash = JSON . parse ( str ) hash [ "state" ] end end end
Sends a heartbeat to the server in order to prove this worker process is still alive .
6,467
def url ( page ) @base_url_params ||= begin url_params = merge_get_params ( default_url_params ) merge_optional_params ( url_params ) end url_params = @base_url_params . dup add_current_page_param ( url_params , page ) ( @options [ :url_builder ] || @template ) . url_for ( url_params ) end
This method adds the url_builder option so we can pass in the mounted Rails engine s scope for will_paginate
6,468
def fetch_prerelease_versions Utils . logger . info ( "Fetching #{Configuration.prerelease_versions_file}" " on #{@name} (#{@host})" ) Http . get ( host + '/' + Configuration . prerelease_versions_file ) . body end
Fetches a list of all the available Gems and their versions .
6,469
def add_file ( name , content ) full_path = File . join ( @path , name ) file = MirrorFile . new ( full_path ) file . write ( content ) file end
Creates a new file with the given name and content .
6,470
def versions_for ( gem ) available = @versions_file . versions_for ( gem . name ) return [ available . last ] if gem . only_latest? versions = available . select do | v | gem . requirement . satisfied_by? ( v [ 0 ] ) end versions = [ available . last ] if versions . empty? versions end
Returns an Array containing the versions that should be fetched for a Gem .
6,471
def fetch_gemspec ( gem , version ) filename = gem . gemspec_filename ( version ) satisfied = if gem . only_latest? true else gem . requirement . satisfied_by? ( version ) end if gemspec_exists? ( filename ) || ! satisfied Utils . logger . debug ( "Skipping #{filename}" ) return end Utils . logger . info ( "Fetching #{...
Tries to download gemspec from a given name and version
6,472
def fetch_gem ( gem , version ) filename = gem . filename ( version ) satisfied = if gem . only_latest? true else gem . requirement . satisfied_by? ( version ) end name = gem . name if gem_exists? ( filename ) || ignore_gem? ( name , version , gem . platform ) || ! satisfied Utils . logger . debug ( "Skipping #{filenam...
Tries to download the gem file from a given nam and version
6,473
def read_file ( file , prerelease = false ) destination = Gemirro . configuration . destination file_dst = File . join ( destination , file ) unless File . exist? ( file_dst ) File . write ( file_dst , @source . fetch_versions ) unless prerelease File . write ( file_dst , @source . fetch_prerelease_versions ) if prerel...
Read file if exists otherwise download its from source
6,474
def filename ( gem_version = nil ) gem_version ||= version . to_s n = [ name , gem_version ] n . push ( @platform ) if @platform != 'ruby' "#{n.join('-')}.gem" end
Returns the filename of the gem file .
6,475
def gemspec_filename ( gem_version = nil ) gem_version ||= version . to_s n = [ name , gem_version ] n . push ( @platform ) if @platform != 'ruby' "#{n.join('-')}.gemspec.rz" end
Returns the filename of the gemspec file .
6,476
def fetch_gem ( resource ) return unless Utils . configuration . fetch_gem name = File . basename ( resource ) result = name . match ( URI_REGEXP ) return unless result gem_name , gem_version , gem_platform , gem_type = result . captures return unless gem_name && gem_version begin gem = Utils . stored_gem ( gem_name , ...
Try to fetch gem and download its if it s possible and build and install indicies .
6,477
def update_indexes indexer = Gemirro :: Indexer . new ( Utils . configuration . destination ) indexer . only_origin = true indexer . ui = :: Gem :: SilentUI . new Utils . logger . info ( 'Generating indexes' ) indexer . update_index indexer . updated_gems . each do | gem | Utils . cache . flush_key ( File . basename ( ...
Update indexes files
6,478
def query_gems_list Utils . gems_collection ( false ) gems = Parallel . map ( query_gems , in_threads : 4 ) do | query_gem | gem_dependencies ( query_gem ) end gems . flatten! gems . reject! ( & :empty? ) gems end
Return gems list from query params
6,479
def gem_dependencies ( gem_name ) Utils . cache . cache ( gem_name ) do gems = Utils . gems_collection ( false ) gem_collection = gems . find_by_name ( gem_name ) return '' if gem_collection . nil? gem_collection = Parallel . map ( gem_collection , in_threads : 4 ) do | gem | [ gem , spec_for ( gem . name , gem . numbe...
List of versions and dependencies of each version from a gem name .
6,480
def download_from_source ( file ) source_host = Gemirro . configuration . source . host Utils . logger . info ( "Download from source: #{file}" ) resp = Http . get ( "#{source_host}/#{File.basename(file)}" ) return unless resp . code == 200 resp . body end
Download file from source
6,481
def map_gems_to_specs ( gems ) gems . map . with_index do | gemfile , index | Utils . logger . info ( "[#{index + 1}/#{gems.size}]: Processing #{gemfile.split('/')[-1]}" ) if File . size ( gemfile ) . zero? Utils . logger . warn ( "Skipping zero-length gem: #{gemfile}" ) next end begin spec = if :: Gem :: Package . res...
Map gems file to specs
6,482
def by_name ( & block ) if @grouped . nil? @grouped = @gems . group_by ( & :name ) . map do | name , collection | [ name , GemVersionCollection . new ( collection ) ] end @grouped . reject! do | name , _collection | name . nil? end @grouped . sort_by! do | name , _collection | name . downcase end end if block_given? @g...
Group gems by name
6,483
def find_by_name ( gemname ) gem = by_name . select do | name , _collection | name == gemname end gem . first . last if gem . any? end
Find gem by name
6,484
def logger_level = ( level ) logger . level = LOGGER_LEVEL [ level ] if LOGGER_LEVEL . key? ( level ) logger end
Set log level
6,485
def ignore_gem ( name , version , platform ) ignored_gems [ platform ] ||= { } ignored_gems [ platform ] [ name ] ||= [ ] ignored_gems [ platform ] [ name ] << version end
Adds a Gem to the list of Gems to ignore .
6,486
def ignore_gem? ( name , version , platform ) if ignored_gems [ platform ] [ name ] ignored_gems [ platform ] [ name ] . include? ( version ) else false end end
Checks if a Gem should be ignored .
6,487
def define_source ( name , url , & block ) source = Source . new ( name , url ) source . instance_eval ( & block ) @source = source end
Define the source to mirror .
6,488
def read handle = File . open ( @path , 'r' ) content = handle . read handle . close content end
Reads the content of the current file .
6,489
def next_index_page_url ( url , pagination_index ) return url unless @paginated if pagination_index > @pagination_max_pages puts "Exceeded pagination limit of #{@pagination_max_pages}" if @verbose EMPTY_STRING else uri = URI . parse ( url ) query = uri . query ? Hash [ URI . decode_www_form ( uri . query ) ] : { } quer...
Return the next URL to scrape given the current URL and its index .
6,490
def scrape_to_csv filename , & blk require 'csv' self . url_array = self . get_index unless self . url_array CSV . open filename , 'wb' do | csv | self . scrape_from_list ( self . url_array , blk ) . compact . each do | document | if document [ 0 ] . respond_to? :map document . each { | row | csv << row } else csv << d...
Writes the scraped result to a CSV at the given filename .
6,491
def get_page ( url , stash = false , options = { } ) return EMPTY_STRING if url . nil? || url . empty? global_options = { :cache => stash , :verbose => @verbose } if @readable_filenames global_options [ :readable_filenames ] = true end if @stash_folder global_options [ :readable_filenames ] = true global_options [ :cac...
Handles getting pages with Downlader which handles stashing .
6,492
def get_instance ( url , pagination_index = 0 , options = { } ) resps = [ self . get_page ( url , @debug , options ) ] pagination_index = pagination_index . to_i prev_url = url while ! resps . last . empty? next_url = self . next_instance_page_url ( url , pagination_index + 1 ) break if next_url == prev_url || next_url...
Returns the instance at url .
6,493
def scrape_from_list ( list , blk ) puts "Scraping #{list.size} instances" if @verbose list . each_with_index . map do | instance_url , instance_index | instance_resps = get_instance instance_url , nil , :instance_index => instance_index instance_resps . each_with_index . map do | instance_resp , pagination_index | blk...
Just a helper for + scrape + .
6,494
def varz ( name , pwd ) json_get ( target , "/varz" , key_style , "authorization" => Http . basic_auth ( name , pwd ) ) end
Gets various monitoring and status variables from the server . Authenticates using + name + and + pwd + for basic authentication .
6,495
def server reply = json_get ( target , '/login' , key_style ) return reply if reply && ( reply [ :prompts ] || reply [ 'prompts' ] ) raise BadResponse , "Invalid response from target #{target}" end
Gets basic information about the target server including version number commit ID and links to API endpoints .
6,496
def discover_uaa info = server links = info [ 'links' ] || info [ :links ] uaa = links && ( links [ 'uaa' ] || links [ :uaa ] ) uaa || target end
Gets a base url for the associated UAA from the target server by inspecting the links returned from its info endpoint .
6,497
def validation_key ( client_id = nil , client_secret = nil ) hdrs = client_id && client_secret ? { "authorization" => Http . basic_auth ( client_id , client_secret ) } : { } json_get ( target , "/token_key" , key_style , hdrs ) end
Gets the key from the server that is used to validate token signatures . If the server is configured to use a symetric key the caller must authenticate by providing a a + client_id + and + client_secret + . If the server is configured to sign with a private key this call will retrieve the public key and + client_id + m...
6,498
def password_strength ( password ) json_parse_reply ( key_style , * request ( target , :post , '/password/score' , Util . encode_form ( :password => password ) , "content-type" => Http :: FORM_UTF8 , "accept" => Http :: JSON_UTF8 ) ) end
Gets information about the given password including a strength score and an indication of what strength is required .
6,499
def type_info ( type , elem ) scimfo = { user : { path : '/Users' , name_attr : 'userName' , origin_attr : 'origin' } , group : { path : '/Groups' , name_attr : 'displayName' , origin_attr : 'zoneid' } , client : { path : '/oauth/clients' , name_attr : 'client_id' } , user_id : { path : '/ids/Users' , name_attr : 'user...
an attempt to hide some scim and uaa oddities