idx int64 0 24.9k | question stringlengths 68 4.14k | target stringlengths 9 749 |
|---|---|---|
18,500 | def register ( cloud_name , cloud_script_path ) cloud_script_path = File . normalize_path ( cloud_script_path ) registered_type ( cloud_name . to_s , cloud_script_path ) true end | Registry method for a dynamic metadata type . |
18,501 | def registered_script_path ( cloud_name ) cloud_script_path = registered_type ( cloud_name ) raise UnknownCloud . new ( "Unknown cloud: #{cloud_name}" ) unless cloud_script_path return cloud_script_path end | Gets the path to the script describing a cloud . |
18,502 | def create ( cloud_name , options ) raise ArgumentError . new ( "cloud_name is required" ) if cloud_name . to_s . empty? raise ArgumentError . new ( "options[:logger] is required" ) unless logger = options [ :logger ] raise UnknownCloud . new ( "No cloud definitions available." ) unless @names_to_script_paths cloud_nam... | Factory method for dynamic metadata types . |
18,503 | def default_cloud_name cloud_file_path = RightScale :: AgentConfig . cloud_file_path value = File . read ( cloud_file_path ) . strip if File . file? ( cloud_file_path ) value . to_s . empty? ? UNKNOWN_CLOUD_NAME : value end | Getter for the default cloud name . This currently relies on a cloud file which must be present in an expected RightScale location . |
18,504 | def busy? busy = false @mutex . synchronize { busy = @thread_name_to_queue . any? { | _ , q | q . busy? } } busy end | Determines if queue is busy |
18,505 | def push_to_thread_queue ( context ) thread_name = context . respond_to? ( :thread_name ) ? context . thread_name : :: RightScale :: AgentConfig . default_thread_name queue = nil @mutex . synchronize do queue = @thread_name_to_queue [ thread_name ] unless queue queue = create_thread_queue ( thread_name ) { push ( THREA... | Pushes a context to a thread based on a name determined from the context . |
18,506 | def groom_thread_queues still_active = false @mutex . synchronize do @thread_name_to_queue . delete_if { | _ , queue | false == queue . active? } still_active = false == @thread_name_to_queue . empty? end return still_active end | Deletes any inactive queues from the hash of known queues . |
18,507 | def close_thread_queues still_active = false @mutex . synchronize do @thread_name_to_queue . each_value do | queue | if queue . active? queue . close still_active = true end end end return still_active end | Closes all thread queues . |
18,508 | def create_http_client options = { :api_version => API_VERSION , :open_timeout => DEFAULT_OPEN_TIMEOUT , :request_timeout => DEFAULT_REQUEST_TIMEOUT , :non_blocking => @non_blocking } auth_url = URI . parse ( @api_url ) auth_url . user = @token_id . to_s auth_url . password = @token @http_client = RightScale :: Balance... | Create health - checked HTTP client for performing authorization |
18,509 | def get_authorized retries = redirects = 0 api_url = @api_url begin Log . info ( "Getting authorized via #{@api_url}" ) params = { :grant_type => "client_credentials" , :account_id => @account_id , :r_s_version => AgentConfig . protocol_version , :right_link_version => RightLink . version } response = @http_client . po... | Get authorized with RightApi using OAuth2 As an extension to OAuth2 receive URLs needed for other servers Retry authorization if RightApi not responding or if get redirected |
18,510 | def renew_authorization ( wait = nil ) wait ||= ( state == :authorized ) ? ( ( @expires_at - Time . now ) . to_i / RENEW_FACTOR ) : 0 if @renew_timer && wait == 0 @renew_timer . cancel @renew_timer = nil end unless @renew_timer @renew_timer = EM_S :: Timer . new ( wait ) do @renew_timer = nil previous_state = state beg... | Get authorized and then continuously renew authorization before it expires |
18,511 | def update_urls ( response ) mode = response [ :mode ] . to_sym raise CommunicationModeSwitch , "RightNet communication mode switching from #{@mode.inspect} to #{mode.inspect}" if @mode && @mode != mode @mode = mode @shard_id = response [ :shard_id ] . to_i if ( new_url = response [ :router_url ] ) != @router_url Log .... | Update URLs and other data returned from authorization Recreate client if API URL has changed |
18,512 | def redirected ( exception ) redirected = false location = exception . response . headers [ :location ] if location . nil? || location . empty? ErrorTracker . log ( self , "Redirect exception does contain a redirect location" ) else new_url = URI . parse ( location ) if new_url . scheme !~ / / || new_url . host . empty... | Handle redirect by adjusting URLs to requested location and recreating HTTP client |
18,513 | def reconnect unless @reconnecting @reconnecting = true @stats [ "reconnects" ] . update ( "initiate" ) @reconnect_timer = EM_S :: PeriodicTimer . new ( rand ( HEALTH_CHECK_INTERVAL ) ) do begin @http_client . check_health @stats [ "reconnects" ] . update ( "success" ) @reconnect_timer . cancel if @reconnect_timer @rec... | Reconnect with authorization server by periodically checking health Delay random interval before starting to check to reduce server spiking When again healthy renew authorization |
18,514 | def push ( * values , & block ) raise_future_proof_exception if finished? value = if block_given? begin block . call ( * values ) rescue => e e end else values . size == 1 ? values [ 0 ] : values end super ( value ) end | Pushes value into a queue by executing it . If execution results in an exception then exception is stored itself . |
18,515 | def get_device_ip ( device ) ip_addr = device_config_show ( device ) . lines ( "\n" ) . grep ( / / ) . shift return nil unless ip_addr ip_addr . strip . split . last end | Gets IP address for specified device |
18,516 | def run ( options ) @log_sink = StringIO . new @log = Logger . new ( @log_sink ) RightScale :: Log . force_logger ( @log ) check_privileges if right_agent_running? username = options . delete ( :username ) email = options . delete ( :email ) uuid = options . delete ( :uuid ) superuser = options . delete ( :superuser ) ... | best - effort auditing but try not to block user Manage individual user SSH logins |
18,517 | def create_audit_entry ( email , username , access , command , client_ip = nil ) begin hostname = ` ` . strip rescue Exception => e hostname = 'localhost' end case access when :scp then summary = 'SSH file copy' detail = "User copied files copied (scp) to/from host." when :sftp then summary = 'SSH interactive file tran... | Create an audit entry to record this user s access . The entry is created asynchronously and this method never raises exceptions even if the request fails or times out . Thus this is best - effort auditing and should not be relied upon! |
18,518 | def display_motd if :: File . exists? ( "/var/run/motd.dynamic" ) puts :: File . read ( "/var/run/motd.dynamic" ) elsif :: File . exists? ( "/var/run/motd" ) puts :: File . read ( "/var/run/motd" ) elsif :: File . exists? ( "/etc/motd" ) puts :: File . read ( "/etc/motd" ) end rescue nil end | Display the Message of the Day if it exists . |
18,519 | def quote ( value ) string = value . to_s unquoted = unquote ( string ) escaped = unquoted . gsub ( QuoteNotEscapedMatcher , "\\\"" ) %Q{"#{escaped}"} end | Returns + value + surrounded by double quotes . This method is idempotent so + value + will only be quoted once regardless of how may times the method is called on it . |
18,520 | def control ( options ) fail ( "No action specified on the command line." ) unless ( options [ :action ] || options [ :requires_network_config ] ) name = options [ :name ] parameters = options [ :parameters ] || [ ] only_if = options [ :only_if ] verbose = options [ :verbose ] actions = options [ :action ] . to_s . spl... | Parse arguments and run |
18,521 | def to_fdf fdf = header @data . each do | key , value | if Hash === value value . each do | sub_key , sub_value | fdf << field ( "#{key}_#{sub_key}" , sub_value ) end else fdf << field ( key , value ) end end fdf << footer return fdf end | generate FDF content |
18,522 | def to_xfdf builder = Nokogiri :: XML :: Builder . new ( encoding : 'UTF-8' ) do | xml | xml . xfdf ( 'xmlns' => 'http://ns.adobe.com/xfdf/' , 'xml:space' => 'preserve' ) { xml . f ( href : options [ :file ] ) if options [ :file ] xml . ids ( original : options [ :id ] , modified : options [ :id ] ) if options [ :id ] ... | generate XFDF content |
18,523 | def configure_routes routes = ENV . keys . select { | k | k =~ / \d / } seen_route = { } routes . each do | route | begin nat_server_ip , cidr = ENV [ route ] . strip . split ( / / ) if seen_route [ cidr ] seen_nat_server_ip = seen_route [ cidr ] logger . warn "Already added route #{cidr} to gateway #{seen_nat_server_i... | NAT Routing Support |
18,524 | def network_route_add ( network , nat_server_ip ) raise "ERROR: invalid nat_server_ip : '#{nat_server_ip}'" unless valid_ipv4? ( nat_server_ip ) raise "ERROR: invalid CIDR network : '#{network}'" unless valid_ipv4_cidr? ( network ) true end | Add route to network through NAT server |
18,525 | def network_route_exists? ( network , nat_server_ip ) routes = routes_show ( ) matchdata = routes . match ( route_regex ( network , nat_server_ip ) ) matchdata != nil end | Is a route defined to network via NAT router ? |
18,526 | def add_static_ip ( n_ip = 0 ) begin ipaddr = ENV [ "RS_IP#{n_ip}_ADDR" ] netmask = ENV [ "RS_IP#{n_ip}_NETMASK" ] gateway = ENV [ "RS_IP#{n_ip}_GATEWAY" ] device = shell_escape_if_necessary ( device_name_from_mac ( ENV [ "RS_IP#{n_ip}_MAC" ] ) ) if ipaddr attached_nameservers = nameservers_for_device ( n_ip ) logger .... | Sets single network adapter static IP addresse and nameservers |
18,527 | def configure_network_adaptor ( device , ip , netmask , gateway , nameservers ) raise "ERROR: invalid IP address: '#{ip}'" unless valid_ipv4? ( ip ) raise "ERROR: invalid netmask: '#{netmask}'" unless valid_ipv4? ( netmask ) if gateway raise "ERROR: invalid gateway IP address: '#{gateway}'" unless valid_ipv4? ( gateway... | Configures a single network adapter with a static IP address |
18,528 | def nameservers_for_device ( n_ip ) nameservers = [ ] raw_nameservers = ENV [ "RS_IP#{n_ip}_NAMESERVERS" ] . to_s . strip . split ( / / ) raw_nameservers . each do | nameserver | if valid_ipv4? ( nameserver ) nameservers << nameserver else logger . error ( "Invalid nameserver #{nameserver} for interface##{n_ip}" ) end ... | Returns a validated list of nameservers |
18,529 | def run ( options ) fail_if_right_agent_is_not_running check_privileges set_logger ( options ) missing_argument unless options . include? ( :action ) res = send_command ( build_cmd ( options ) , options [ :verbose ] , options [ :timeout ] ) case options [ :action ] when :get_tags get_tags ( res , options ) when :query_... | Manage instance tags |
18,530 | def format_output ( result , format ) case format when :json JSON . pretty_generate ( result ) when :yaml YAML . dump ( result ) when :text result = result . keys if result . respond_to? ( :keys ) result . join ( " " ) else raise ArgumentError , "Unknown output format #{format}" end end | Format output for display to user |
18,531 | def forward_audit ( kind , text , thread_name , options ) auditor = @auditors [ thread_name ] return unless auditor if kind == :append_output auditor . append_output ( text ) else auditor . __send__ ( kind , text , options ) end end | Forward audit command received from cook using audit proxy |
18,532 | def close ( thread_name ) close_callback = @close_callbacks [ thread_name ] close_callback . call if close_callback true ensure @auditors [ thread_name ] = nil @close_callbacks [ thread_name ] = nil end | Reset proxy object and notify close event listener |
18,533 | def download ( resource ) client = get_http_client @size = 0 @speed = 0 @sanitized_resource = sanitize_resource ( resource ) resource = parse_resource ( resource ) attempts = 0 begin balancer . request do | endpoint | RightSupport :: Net :: SSL . with_expected_hostname ( ips [ endpoint ] ) do logger . info ( "Requestin... | Initializes a Downloader with a list of hostnames |
18,534 | def resolve ( hostnames ) ips = { } hostnames . each do | hostname | infos = nil attempts = RETRY_MAX_ATTEMPTS begin infos = Socket . getaddrinfo ( hostname , 443 , Socket :: AF_INET , Socket :: SOCK_STREAM , Socket :: IPPROTO_TCP ) rescue Exception => e if attempts > 0 attempts -= 1 retry else logger . error "Failed t... | Resolve a list of hostnames to a hash of Hostname = > IP Addresses |
18,535 | def parse_exception_message ( e ) if e . kind_of? ( RightSupport :: Net :: NoResult ) i = 0 e . message . split ( / \[ \] / ) . select { ( ( i += 1 ) % 2 ) == 0 } . map { | s | s . split ( / \s / ) } . flatten else [ e . class . name ] end end | Parse Exception message and return it |
18,536 | def hostnames_ips @hostnames . map do | hostname | ips . select { | ip , host | host == hostname } . keys end . flatten end | Orders ips by hostnames |
18,537 | def balancer @balancer ||= RightSupport :: Net :: RequestBalancer . new ( hostnames_ips , :policy => RightSupport :: Net :: LB :: Sticky , :retry => RETRY_MAX_ATTEMPTS , :fatal => lambda do | e | if RightSupport :: Net :: RequestBalancer :: DEFAULT_FATAL_EXCEPTIONS . any? { | c | e . is_a? ( c ) } true elsif e . respon... | Create and return a RequestBalancer instance |
18,538 | def pad ( padding = ( not_set = true ) , options = { } ) return text if @padding . empty? && not_set if ! not_set @padding = Padder . parse ( padding ) end text_copy = text . dup column_width = maximum_length ( text ) elements = [ ] if @padding . top > 0 elements << ( SPACE * column_width + NEWLINE ) * @padding . top e... | Apply padding to text |
18,539 | def create_sequence ( context ) pid_callback = lambda do | sequence | @mutex . synchronize { @pid = sequence . pid } end return RightScale :: ExecutableSequenceProxy . new ( context , :pid_callback => pid_callback ) end | Factory method for a new sequence . |
18,540 | def audit_status ( sequence ) context = sequence . context title = context . decommission? ? 'decommission ' : '' title += context . succeeded ? 'completed' : 'failed' context . audit . update_status ( "#{title}: #{context.payload}" ) true rescue Exception => e Log . error ( Log . format ( "SingleThreadBundleQueue.audi... | Audit executable sequence status after it ran |
18,541 | def setup_log ( type = :memory ) case type when :memory @log_content = StringIO . new @logger = Logger . new ( @log_content ) else unless defined? ( @@log_file_base_name ) @@log_file_base_name = File . normalize_path ( File . join ( Dir . tmpdir , "#{File.basename(__FILE__, '.rb')}_#{Time.now.strftime("%Y-%m-%d-%H%M%S"... | Setup log for test . |
18,542 | def run_fetcher ( * args , & block ) server = nil done = false last_exception = nil results = [ ] EM . run do begin server = MockHTTPServer . new ( { :Logger => @logger } , & block ) EM . defer do begin args . each do | source | results << source . call ( ) end rescue Exception => e last_exception = e end done = true e... | Runs the metadata provider after starting a server to respond to fetch requests . |
18,543 | def process_lit ( exp ) exp . shift value = exp . shift if value . is_a? ( Numeric ) && ! @ignore . include? ( value ) @file . magic_numbers << MagicNumber . new ( :value => value , :line => exp . line ) end s ( ) end | Process literal node . If a literal is a number and add it to the collection of magic numbers . |
18,544 | def write ( data , output_io , options = { } ) options = { :mode => :compat } . merge! ( options ) if output_io Oj . to_stream ( output_io , data , options ) output_io else string_io = StringIO . new Oj . to_stream ( string_io , data , options ) string_io . string end end | Writes objects to JSON using a streaming mechanism in Oj . |
18,545 | def sensitive_inputs inputs = { } if @attributes @attributes . values . select { | attr | attr . respond_to? ( :has_key? ) && attr . has_key? ( "parameters" ) } . each do | has_params | has_params . each_pair do | _ , params | sensitive = params . select { | name , _ | @sensitive_inputs . include? ( name ) } inputs . m... | Determine inputs that need special security treatment . |
18,546 | def configure_logging Chef :: Log . logger = AuditLogger . new ( sensitive_inputs ) Chef :: Log . logger . level = Log . level_from_sym ( Log . level ) end | Initialize and configure the logger |
18,547 | def configure_chef :: Mixlib :: ShellOut . default_logger = :: Chef :: Log :: Mixlib :: ShellOut . command_failure_callback = lambda do | params | failure_reason = :: RightScale :: SubprocessFormatting . reason ( params [ :status ] ) expected_error_codes = Array ( params [ :args ] [ :returns ] ) . join ( ' or ' ) :: Ri... | Configure chef so it can find cookbooks and so its logs go to the audits |
18,548 | def update_cookbook_path @cookbooks . reverse . each do | cookbook_sequence | local_basedir = File . join ( @download_path , cookbook_sequence . hash ) cookbook_sequence . paths . reverse . each do | path | dir = File . expand_path ( File . join ( local_basedir , path ) ) unless Chef :: Config [ :cookbook_path ] . incl... | Update the Chef cookbook_path based on the cookbooks in the bundle . |
18,549 | def checkout_cookbook_repos return true unless @cookbook_repo_retriever . has_cookbooks? @audit . create_new_section ( 'Checking out cookbooks for development' ) @audit . append_info ( "Cookbook repositories will be checked out to #{@cookbook_repo_retriever.checkout_root}" ) audit_time do @cookbook_repo_retriever . che... | Checkout repositories for selected cookbooks . Audit progress and errors do not fail on checkout error . |
18,550 | def check_ohai ( & block ) ohai = create_ohai if ohai [ :hostname ] block . call ( ohai ) else Log . warning ( "Could not determine node name from Ohai, will retry in #{@ohai_retry_delay}s..." ) EM . add_timer ( @ohai_retry_delay ) { EM . defer { check_ohai ( & block ) } } @ohai_retry_delay = [ 2 * @ohai_retry_delay , ... | Checks whether Ohai is ready and calls given block with it if that s the case otherwise schedules itself to try again indefinitely |
18,551 | def create_ohai ohai = Ohai :: System . new ohai . require_plugin ( 'os' ) ohai . require_plugin ( 'hostname' ) return ohai end | Creates a new ohai and configures it . |
18,552 | def report_success ( node ) ChefState . merge_attributes ( node . normal_attrs ) if node remove_right_script_params_from_chef_state patch = :: RightSupport :: Data :: HashTools . deep_create_patch ( @inputs , ChefState . attributes ) patch [ :right_only ] = { } @inputs_patch = patch EM . next_tick { succeed } true end | Initialize inputs patch and report success |
18,553 | def report_failure ( title , msg ) @ok = false @failure_title = title @failure_message = msg EM . next_tick { fail } true end | Set status with failure message and audit it |
18,554 | def chef_error ( e ) if e . is_a? ( :: RightScale :: Exceptions :: Exec ) msg = "External command error: " if match = / / . match ( e . message ) cmd_output = match [ 1 ] else cmd_output = e . message end msg += cmd_output msg += "\nThe command was run from \"#{e.path}\"" if e . path elsif e . is_a? ( :: Chef :: Except... | Wrap chef exception with explanatory information and show context of failure |
18,555 | def context_line ( lines , index , padding , prefix = nil ) return '' if index < 1 || index > lines . size margin = prefix ? prefix * index . to_s . size : index . to_s "#{margin}#{' ' * ([padding - margin.size, 0].max)} #{lines[index - 1]}" end | Format a single line for the error context return empty string if given index is negative or greater than the lines array size |
18,556 | def retry_execution ( retry_message , times = AgentConfig . max_packages_install_retries ) count = 0 success = false begin count += 1 success = yield @audit . append_info ( "\n#{retry_message}\n" ) unless success || count > times end while ! success && count <= times success end | Retry executing given block given number of times Block should return true when it succeeds |
18,557 | def get_start ( line ) retval = nil m = / \s \s \s \s / . match ( line ) if m && m [ 1 ] retval = m [ 1 ] end return retval end | Determines if the the line is a start_part comment . Return the file name otherwise nil |
18,558 | def get_all ( line ) retval = nil m = / \s \s \s \s / . match ( line ) if m && m [ 1 ] retval = m [ 1 ] end return retval end | Determines if the the line is an all_parts comment . Return the file name otherwise nil |
18,559 | def get_end ( line ) retval = nil m = / \s \s / . match ( line ) if m retval = true end return retval end | Determines if the the line is an end_parts comment . Return true otherwise nil |
18,560 | def process_ruleset ( ruleset , dirname = nil ) all_file_names = [ ] all_parts = [ ] all_parts_name = nil current_part = nil current_part_name = nil ruleset . lines do | line | if ! all_parts_name && ( all_parts_name = get_all ( line ) ) all_parts_name = File . join ( dirname , all_parts_name ) if dirname all_file_name... | processes the lines ruleset is to be a string read in using File . read |
18,561 | def call words = stems_for ( remove_stopwords_in ( @words ) ) score_polarities_for ( frequencies_for ( words ) ) polarities . empty? ? 5.0 : ( polarities . inject ( 0 ) { | sum , polarity | sum + polarity } / polarities . length ) end | Main method that initiates calculating polarity |
18,562 | def score_emoticon_polarity happy = happy_emoticon? ( words ) sad = sad_emoticon? ( words ) polarities << 5.0 if happy && sad polarities << 8.0 if happy polarities << 2.0 if sad end | Checks if words has happy or sad emoji and adds polarity for it |
18,563 | def score_polarities_for ( word_frequencies ) word_frequencies . each do | word , frequency | polarity = SadPanda :: Bank :: POLARITIES [ word . to_sym ] polarities << ( polarity * frequency . to_f ) if polarity end score_emoticon_polarity end | Appends polarities of words to array polarities |
18,564 | def network_route_add ( network , nat_server_ip ) super route_str = "#{network} via #{nat_server_ip}" begin if @boot logger . info "Adding route to network #{route_str}" device = route_device ( network , nat_server_ip ) if device update_route_file ( network , nat_server_ip , device ) else logger . warn "Unable to find ... | This is now quite tricky . We do two routing passes a pass before the system networking is setup ( |
18,565 | def update_route_file ( network , nat_server_ip , device ) raise "ERROR: invalid nat_server_ip : '#{nat_server_ip}'" unless valid_ipv4? ( nat_server_ip ) raise "ERROR: invalid CIDR network : '#{network}'" unless valid_ipv4_cidr? ( network ) routes_file = routes_file ( device ) ip_route_cmd = ip_route_cmd ( network , na... | Persist network route to file |
18,566 | def write_adaptor_config ( device , data ) config_file = config_file ( device ) raise "FATAL: invalid device name of '#{device}' specified for static IP allocation" unless device . match ( / / ) logger . info "Writing persistent network configuration to #{config_file}" File . open ( config_file , "w" ) { | f | f . writ... | Persist device config to a file |
18,567 | def update_config_file ( filename , line , exists_str = nil , append_str = nil ) FileUtils . mkdir_p ( File . dirname ( filename ) ) if read_config_file ( filename ) . include? ( line ) exists_str ||= "Config already exists in #{filename}" logger . info exists_str else append_str ||= "Appending config to #{filename}" l... | Add line to config file |
18,568 | def read_config_file ( filename ) contents = "" File . open ( filename , "r" ) { | f | contents = f . read ( ) } if File . exists? ( filename ) contents end | Read contents of config file |
18,569 | def append_config_file ( filename , line ) File . open ( filename , "a" ) { | f | f . puts ( line ) } end | Appends line to config file |
18,570 | def run options = OptionsBag . load agent_id = options [ :identity ] AgentConfig . root_dir = options [ :root_dir ] Log . program_name = 'RightLink' Log . facility = 'user' Log . log_to_file_only ( options [ :log_to_file_only ] ) Log . init ( agent_id , options [ :log_path ] ) Log . level = CookState . log_level Log . ... | Run bundle given in stdin |
18,571 | def send_push ( type , payload = nil , target = nil , opts = { } ) cmd = { :name => :send_push , :type => type , :payload => payload , :target => target , :options => opts } EM . next_tick { @client . send_command ( cmd ) } end | Helper method to send a request to one or more targets with no response expected See InstanceCommands for details |
18,572 | def load_tags ( timeout ) cmd = { :name => :get_tags } res = blocking_request ( cmd , timeout ) raise TagError . new ( "Retrieving current tags failed: #{res.inspect}" ) unless res . kind_of? ( Array ) :: Chef :: Log . info ( "Successfully loaded current tags: '#{res.join("', '")}'" ) res end | Retrieve current instance tags |
18,573 | def send_inputs_patch ( sequence ) if has_default_thread? begin cmd = { :name => :set_inputs_patch , :patch => sequence . inputs_patch } @client . send_command ( cmd ) rescue Exception => e fail ( 'Failed to update inputs' , Log . format ( "Failed to apply inputs patch after execution" , e , :trace ) ) end end true ens... | Initialize instance variables Report inputs patch to core |
18,574 | def report_failure ( subject ) begin AuditStub . instance . append_error ( subject . failure_title , :category => RightScale :: EventCategories :: CATEGORY_ERROR ) if subject . failure_title AuditStub . instance . append_error ( subject . failure_message ) if subject . failure_message rescue Exception => e fail ( 'Fail... | Report failure to core |
18,575 | def fail ( title , message = nil ) $stderr . puts title $stderr . puts message || title if @client @client . stop { AuditStub . instance . stop { exit ( 1 ) } } else exit ( 1 ) end end | Print failure message and exit abnormally |
18,576 | def stop AuditStub . instance . stop do @client . stop do | timeout | Log . info ( '[cook] Failed to stop command client cleanly, forcing shutdown...' ) if timeout EM . stop end end end | Stop command client then stop auditor stub then EM |
18,577 | def blocking_request ( cmd , timeout ) raise BlockingError , "Blocking request not allowed on EM main thread for command #{cmd.inspect}" if EM . reactor_thread? response_queue = Queue . new EM . next_tick { @client . send_command ( cmd , false , timeout ) { | response | response_queue << response } } return response_qu... | Provides a blocking request for the given command Can only be called when on EM defer thread |
18,578 | def load ( data , error_message , format = nil ) serializer = Serializer . new ( format ) content = nil begin content = serializer . load ( data ) rescue Exception => e fail ( error_message , "Failed to load #{serializer.format.to_s} data (#{e}):\n#{data.inspect}" ) end content end | Load serialized content fail if serialized data is invalid |
18,579 | def wrap ( wrap_at = DEFAULT_WIDTH ) if text . length < wrap_at . to_i || wrap_at . to_i . zero? return text end ansi_stack = [ ] text . split ( NEWLINE , - 1 ) . map do | paragraph | format_paragraph ( paragraph , wrap_at , ansi_stack ) end * NEWLINE end | Wrap a text into lines no longer than wrap_at length . Preserves existing lines and existing word boundaries . |
18,580 | def url_for ( method , params = { } , endpoint = 'rest' ) params [ 'api_key' ] = @api_key params [ 'method' ] = method if method signature = sign ( params ) url = BASE_URL + endpoint + '/' + params_to_url ( params . merge ( { 'api_sig' => signature } ) ) url end | Get the url for a particular call doing the signing and all that other stuff . |
18,581 | def params_to_url ( params ) string = '?' params . each do | k , v | string += CGI :: escape ( k ) string += '=' string += CGI :: escape ( v ) string += '&' end string end | Turns params into a URL |
18,582 | def sign ( params ) raise "Something's wrong; @secret is nil" if @secret . nil? sign_me = @secret params . keys . sort . each do | key | sign_me += key raise "Omit params with nil values; key #{key} was nil" if params [ key ] . nil? sign_me += params [ key ] end return Digest :: MD5 . hexdigest ( sign_me ) end | Signs the request given the params and secret key |
18,583 | def country ( code , limit , params = { } ) paginating_collection ( limit , PER_PAGE , { "ResponseGroup" => "Country" , "CountryCode" => code . to_s . upcase } , params , & top_sites_parser ) end | Top sites for the specified two letter country code . |
18,584 | def list_countries ( params = { } ) collection ( { "ResponseGroup" => "ListCountries" } , params ) do | document | path = "//TopSitesResult/Alexa/TopSites/Countries" document . at ( path ) . elements . map do | node | Country . new ( node . at ( "Name" ) . text , node . at ( "Code" ) . text , node . at ( "TotalSites" )... | All countries that have Alexa top sites . |
18,585 | def reload ( method , path , options = { } ) self . loaded = true response = request ( method , path , self . class , Smash :: filtered_options ( options ) ) self . merge! ( response ) clear_errors ! redirect? rescue Smash :: Error => e self . merge! ( e . response ) if e . response . is_a? ( Hash ) false end | reload the object after doing a query to the api |
18,586 | def [] ( property ) value = nil return value unless ( value = super ( property ) ) . nil? if api and ! loaded self . loaded = true fetch end super ( property ) end | get the property from the hash if the value is not set and the object has not been loaded try to load it |
18,587 | def run_bootstrap ( data , bootstrap_args , overwrite = false ) node_name = data [ 'name' ] args = setup_bootstrap_args ( bootstrap_args , data ) delete_client_node ( node_name ) if overwrite ui . info "Bootstrapping node #{node_name}" run_cmd ( Chef :: Knife :: Bootstrap , args ) rescue StandardError => e raise if Che... | Setup the bootstrap args and run the bootstrap command |
18,588 | def login ( options = { } ) body = { body : { username : options [ :username ] , password : options [ :password ] , account_id : options [ :account_id ] } } self . class . post ( "/#{@api_ver}/auth/login" , body ) end | AUTHORIZATION API Methods |
18,589 | def flags fs = FRAME_FLAGS [ type ] [ 0x01 , 0x02 , 0x04 , 0x08 , 0x10 , 0x20 , 0x40 , 0x80 ] . select { | v | @flags_value & v > 0 } . map { | val | fs && fs . key ( val ) || ( "unknown_%02x" % val ) . to_sym } end | Returns the set flags on the frame . |
18,590 | def flags = ( values ) val = 0 FRAME_FLAGS_MAP . values_at ( * values ) . each { | c | val |= c if c } @flags_value = val end | Sets the frame flags . |
18,591 | def receive ( new_data ) return if @state == :closed return if new_data . empty? @buffer << new_data consume_buffer rescue RemoteConnectionError => e callback ( :connection_error , e ) goaway ( e . http2_error_type ) close end | Receives the specified data and process . |
18,592 | def stream ( stream_id , update_max_id = true ) raise ArgumentError , "stream_id can't be 0" if stream_id == 0 stream = @streams [ stream_id ] if stream if stream . state == :idle && stream_id < @max_stream_ids [ stream_id % 2 ] stream . set_state ( :closed_implicitly ) end elsif stream_id > @max_stream_ids [ stream_id... | Returns a Stream object with the specified ID . |
18,593 | def settings ( ** new_settings ) send_immediately Frame :: Settings . new ( ** new_settings ) old_settings = @local_settings . dup @local_settings . merge! ( new_settings ) @hpack_decoder . limit = @local_settings [ :header_table_size ] update_recv_initial_window_size ( @local_settings [ :initial_window_size ] - old_se... | Sends local settings to the peer . |
18,594 | def goaway ( error_type = :no_error , message = "" ) last_id = @max_stream_ids . max send_immediately Frame :: Goaway . new ( last_id , error_type , message ) end | Sends GOAWAY frame to the peer and closes the connection . |
18,595 | def transition ( name , states = self :: STATES , transitions = self :: TRANSITIONS ) self . state_machines ||= { } self . state_machines [ name ] = { states : states . values , transitions : transitions } self . state_machines [ name ] [ :states ] . each do | this_state | method_name = "#{this_state}?" . to_sym raise ... | This assumes states is a hash |
18,596 | def inuit_find_modules ( current_module ) current_config = YAML . load_file ( @ITCSS_CONFIG_FILE ) current_inuit_modules = current_config [ "inuit_modules" ] . select { | p | p . include? current_module } current_inuit_modules . map { | p | inuit_imports_path p } end | Inuit Helper Methods |
18,597 | def block name , param = nil , & b sp = ' ' * 2 if name == :lang || name == :languages body = yield self if block_given? param = ":#{param.to_s}" unless param . nil? "#{sp}#{name.to_s} #{param} do\n#{body}\n#{sp}end\n" end | Create DSL block |
18,598 | def property name , prop return '' if EXCLUDE_PROPERTIES . include? ( name . to_s ) || prop . nil? || ( prop . kind_of? ( Array ) && prop . empty? ) prop = prop . flatten . map { | p | "'#{p}'" } . join ( ', ' ) if prop . respond_to? ( :flatten ) && name . to_sym != :folders prop = @paths . map { | f | "'#{f}'" } . joi... | Create DSL property of block |
18,599 | def schedule_job ( job = nil ) if can_schedule_job? ( job ) callback = ScheduledJob . config . fast_mode in_fast_mode = callback ? callback . call ( self ) : false run_at = in_fast_mode ? Time . now . utc + 1 : time_to_recur ( Time . now . utc ) Delayed :: Job . enqueue ( new , :run_at => run_at , :queue => queue_name ... | This method should be called when scheduling a recurring job as it checks to ensure no other instances of the job are already running . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.