idx int64 0 24.9k | question stringlengths 68 4.14k | target stringlengths 9 749 |
|---|---|---|
18,400 | def http_get ( path , keep_alive = true ) uri = safe_parse_http_uri ( path ) history = [ ] loop do Log . debug ( "http_get(#{uri})" ) host = uri . host connection = Rightscale :: HttpConnection . new ( :logger => Log , :exception => QueryFailed ) request = Net :: HTTP :: Get . new ( uri . path ) request [ 'Connection' ... | Performs an HTTP get request with built - in retries and redirection based on HTTP responses . |
18,401 | def safe_parse_http_uri ( path ) raise ArgumentError . new ( "URI path cannot be empty" ) if path . to_s . empty? begin uri = URI . parse ( path ) rescue URI :: InvalidURIError => e raise e if path . start_with? ( "http://" ) || path . start_with? ( "https://" ) uri = URI . parse ( "http://" + path ) uri = URI . parse ... | Handles some cases which raise exceptions in the URI class . |
18,402 | def process_file ( path ) code = File . read ( path ) sexp_node = RubyParser . new . parse ( code ) file = Mago :: RubyFile . new ( path ) sexp_processor = Mago :: SexpProcessor . new ( file , @ignore ) sexp_processor . process ( sexp_node ) @report . files << file @on_file . call ( file ) if @on_file rescue Errno :: E... | Process a file and add a result to the report . |
18,403 | def process ( errback = nil , audit = nil , & block ) if continue? || @shutdown_scheduled block . call if block return true end sender = Sender . instance agent_identity = sender . identity if audit case @level when REBOOT , STOP , TERMINATE operation = "/forwarder/shutdown" payload = { :agent_identity => agent_identit... | Processes shutdown requests by communicating the need to shutdown an instance with the core agent if necessary . |
18,404 | def fail ( errback , audit , msg , res = nil ) if msg . kind_of? ( Exception ) e = msg detailed = Log . format ( "Could not process shutdown state #{self}" , e , :trace ) msg = e . message else detailed = nil end msg += ": #{res.content}" if res && res . content audit . append_error ( msg , :category => RightScale :: E... | Handles any shutdown failure . |
18,405 | def predicates_for_and_conditions ( conditions ) return nil if conditions . empty? predicates = conditions . map do | q | q = HashWithIndifferentAccess . new ( Netzke :: Support . permit_hash_params ( q ) ) attr = q [ :attr ] method , assoc = method_and_assoc ( attr ) arel_table = assoc ? Arel :: Table . new ( assoc . ... | The following is a hack to get around Netzke s broken handling of filtering on PostgreSQL enums columns . |
18,406 | def send_command ( cmd , content , options ) begin options ||= { } cmd = { :name => cmd , :content => RightScale :: AuditProxy . force_utf8 ( content ) , :options => options } EM . next_tick { @agent_connection . send_command ( cmd ) } rescue Exception => e $stderr . puts 'Failed to audit' $stderr . puts Log . format (... | Helper method used to send command client request to RightLink agent |
18,407 | def webpacked_tags ( entries , kind ) common_entry = :: Rails . configuration . webpacked . common_entry_name common_bundle = asset_tag ( common_entry , kind ) page_bundle = Array ( entries ) . reduce ( '' ) do | memo , entry | tag = asset_tag ( entry , kind ) memo << tag if tag end common_bundle ? [ common_bundle , pa... | Return include tags for entry points by given asset kind . Also common file could be included |
18,408 | def asset_tag ( entry , kind ) path = webpacked_asset_path ( entry , kind ) if path case kind when :js then javascript_include_tag path when :css then stylesheet_link_tag path end end end | Return include tags for entry point by given asset kind . No extra common file included even if it exists |
18,409 | def cook_path relative_path = File . join ( File . dirname ( __FILE__ ) , '..' , '..' , 'bin' , 'cook_runner' ) return File . normalize_path ( relative_path ) end | Path to cook_runner ruby script |
18,410 | def report_failure ( title , msg = nil ) @context . audit . append_error ( title , :category => RightScale :: EventCategories :: CATEGORY_ERROR ) @context . audit . append_error ( msg ) unless msg . nil? @context . succeeded = false fail true end | Report cook process execution failure |
18,411 | def get_updated_userdata ( data ) result = RightScale :: CloudUtilities . parse_rightscale_userdata ( data ) api_url = "https://#{result['RS_server']}/api" client_id = result [ 'RS_rn_id' ] client_secret = result [ 'RS_rn_auth' ] new_userdata = retrieve_updated_data ( api_url , client_id , client_secret ) if ( new_user... | Parses azure user metadata into a hash . |
18,412 | def run if done? report_success return true end @audit . create_new_section ( 'Retrieving credentials' ) ok = true @executables_inputs . each_pair do | exe , inputs | inputs . each_pair do | name , location | next if location . is_a? ( RightScale :: SecureDocumentLocation ) msg = "The provided credential (#{location.cl... | Initialize parameter gatherer |
18,413 | def handle_response ( exe , name , location , response ) result = @serializer . load ( response ) if result . success? if result . content secure_document = result . content . first if secure_document . envelope_mime_type . nil? @executables_inputs [ exe ] [ name ] = secure_document @audit . append_info ( "Got #{name} ... | Handle a RightNet response to our retryable request . Could be success failure or unexpected . |
18,414 | def count_remaining count = @executables_inputs . values . map { | a | a . values . count { | p | not p . is_a? ( RightScale :: SecureDocument ) } } return count . inject { | sum , x | sum + x } || 0 end | Return the number of credentials remaining to be gathered |
18,415 | def substitute_parameters @executables_inputs . each_pair do | exe , inputs | inputs . each_pair do | name , value | case exe when RightScale :: RecipeInstantiation exe . attributes [ name ] = value . content when RightScale :: RightScriptInstantiation exe . parameters [ name ] = value . content end end end end | Do the actual substitution of credential values into the bundle |
18,416 | def report_failure ( title , message , exception = nil ) if exception Log . error ( "ExternalParameterGatherer failed due to " + "#{exception.class.name}: #{exception.message} (#{exception.backtrace.first})" ) end @failure_title = title @failure_message = message EM . next_tick { fail } end | Report a failure by setting some attributes that our caller will query then updating our Deferrable disposition so our caller gets notified via errback . |
18,417 | def send_retryable_request ( operation , payload , options = { } , & callback ) connection = EM . connect ( '127.0.0.1' , @listen_port , AgentConnection , @cookie , @thread_name , callback ) EM . next_tick do connection . send_command ( :name => :send_retryable_request , :type => operation , :payload => payload , :opti... | Use the command protocol to send a retryable request . This class cannot reuse Cook s implementation of the command - proto request wrappers because we must gather credentials concurrently for performance reasons . The easiest way to do this is simply to open a new command proto socket for every distinct request we mak... |
18,418 | def should_be_linked? ( repo_sha , position ) @dev_cookbooks . has_key? ( repo_sha ) && @dev_cookbooks [ repo_sha ] . positions && @dev_cookbooks [ repo_sha ] . positions . detect { | dev_position | dev_position . position == position } end | Should there be a link created for this cookbook? |
18,419 | def checkout_cookbook_repos ( & callback ) @dev_cookbooks . each_pair do | repo_sha , dev_repo | repo = dev_repo . to_scraper_hash repo_dir = @scraper . repo_dir ( repo ) if File . directory? ( repo_dir ) if callback callback . call ( :commit , :initialize , "Skipping checkout -- repository already exists in #{repo_dir... | Checkout the given repo and link each dev cookbook to it s matching repose path |
18,420 | def link ( repo_sha , position ) if repo_dir = @registered_checkouts [ repo_sha ] checkout_path = CookbookPathMapping . checkout_path ( repo_dir , position ) raise ArgumentError . new ( "Missing directory cannot be linked: #{checkout_path}" ) unless File . directory? ( checkout_path ) repose_path = CookbookPathMapping ... | Creates a symlink from the checked out cookbook to the expected repose download location |
18,421 | def send_command ( options ) return if @stopped_callback @pending += 1 command = options . dup command [ :cookie ] = @cookie command [ :thread_name ] = @thread_name send_data ( CommandSerializer . dump ( command ) ) true end | Set command client cookie and initialize responses parser Send command to running agent |
18,422 | def stop ( & callback ) send_command ( :name => :close_connection ) @stopped_callback = callback Log . info ( "[cook] Disconnecting from agent (#{@pending} response#{@pending > 1 ? 's' : ''} pending)" ) @stop_timeout = EM :: Timer . new ( STOP_TIMEOUT ) do Log . warning ( "[cook] Time out waiting for responses from age... | Stop command client wait for all pending commands to finish prior to calling given callback |
18,423 | def uuid_to_uid ( uuid ) uuid = Integer ( uuid ) if uuid >= 0 && uuid <= MAX_UUID 10_000 + uuid else raise RangeError , "#{uuid} is not within (0..#{MAX_UUID})" end end | Map a universally - unique integer RightScale user ID to a locally - unique Unix UID . |
18,424 | def pick_username ( ideal ) name = ideal i = 0 while user_exists? ( name ) i += 1 name = "#{ideal}_#{i}" end name end | Pick a username that does not yet exist on the system . If the given username does not exist it is returned ; else we add a _1 suffix and continue incrementing the number until we arrive at a username that does not yet exist . |
18,425 | def create_user ( username , uuid , superuser ) uid = LoginUserManager . uuid_to_uid ( uuid ) if uid_exists? ( uid , [ 'rightscale' ] ) username = uid_to_username ( uid ) elsif ! uid_exists? ( uid ) username = pick_username ( username ) yield ( username ) if block_given? add_user ( username , uid ) modify_group ( 'righ... | Ensure that a given user exists and that his group membership is correct . |
18,426 | def manage_user ( uuid , superuser , options = { } ) uid = LoginUserManager . uuid_to_uid ( uuid ) username = uid_to_username ( uid ) force = options [ :force ] || false disable = options [ :disable ] || false if ( force && uid_exists? ( uid ) ) || uid_exists? ( uid , [ 'rightscale' ] ) modify_user ( username , disable... | If the given user exists and is RightScale - managed then ensure his login information and group membership are correct . If force == true then management tasks are performed irrespective of the user s group membership status . |
18,427 | def add_user ( username , uid , shell = nil ) uid = Integer ( uid ) shell ||= DEFAULT_SHELLS . detect { | sh | File . exists? ( sh ) } useradd = find_sbin ( 'useradd' ) unless shell . nil? dash_s = "-s #{Shellwords.escape(shell)}" end result = sudo ( "#{useradd} #{dash_s} -u #{uid} -p #{random_password} -m #{Shellwords... | Create a Unix user with the useradd command . |
18,428 | def modify_user ( username , locked = false , shell = nil ) shell ||= DEFAULT_SHELLS . detect { | sh | File . exists? ( sh ) } usermod = find_sbin ( 'usermod' ) if locked dash_e = "-e 1970-01-01 -L" else dash_e = "-e 99999 -U" end unless shell . nil? dash_s = "-s #{Shellwords.escape(shell)}" end result = sudo ( "#{user... | Modify a user with the usermod command . |
18,429 | def modify_group ( group , operation , username ) Etc . getgrnam ( group ) Etc . getpwnam ( username ) groups = Set . new Etc . group { | g | groups << g . name if g . mem . include? ( username ) } case operation when :add return false if groups . include? ( group ) groups << group when :remove return false unless grou... | Adds or removes a user from an OS group ; does nothing if the user is already in the correct membership state . |
18,430 | def uid_exists? ( uid , groups = [ ] ) uid = Integer ( uid ) user_exists = Etc . getpwuid ( uid ) . uid == uid if groups . empty? user_belongs = true else mem = Set . new username = Etc . getpwuid ( uid ) . name Etc . group { | g | mem << g . name if g . mem . include? ( username ) } user_belongs = groups . all? { | g ... | Check if user with specified Unix UID exists in the system and optionally whether he belongs to all of the specified groups . |
18,431 | def group_exists? ( name ) groups = Set . new Etc . group { | g | groups << g . name } groups . include? ( name ) end | Check if group with specified name exists in the system . |
18,432 | def find_sbin ( cmd ) path = SBIN_PATHS . detect do | dir | File . exists? ( File . join ( dir , cmd ) ) end raise RightScale :: LoginManager :: SystemConflict , "Failed to find a suitable implementation of '#{cmd}'." unless path File . join ( path , cmd ) end | Search through some directories to find the location of a binary . Necessary because different Linux distributions put their user - management utilities in slightly different places . |
18,433 | def recursive_flatten_metadata ( tree_metadata , flat_metadata = { } , metadata_path = [ ] , path_index = 0 ) unless tree_metadata . empty? tree_metadata . each do | key , value | metadata_path [ path_index ] = key if value . respond_to? ( :has_key? ) recursive_flatten_metadata ( value , flat_metadata , metadata_path ,... | Recursively flattens metadata . |
18,434 | def flatten_metadata_path ( metadata_path ) flat_path = transform_path ( metadata_path ) if @formatted_path_prefix && ! ( flat_path . start_with? ( RS_METADATA_PREFIX ) || flat_path . start_with? ( @formatted_path_prefix ) ) return @formatted_path_prefix + flat_path end return flat_path end | Flattens a sequence of metadata keys into a simple key string distinguishing the path to a value stored at some depth in a tree of metadata . |
18,435 | def script_path ( nickname ) base_path = nickname . gsub ( / / , '_' ) base_path = File . join ( @recipes_dir , base_path ) candidate_path = RightScale :: Platform . shell . format_script_file_name ( base_path ) i = 1 path = candidate_path path = candidate_path + ( i += 1 ) . to_s while File . exists? ( path ) path end | Produce file name for given script nickname |
18,436 | def cache_dir ( script ) path = File . normalize_path ( File . join ( AgentConfig . cache_dir , 'right_scripts_content' , "rs_attach" + script . object_id . to_s ) ) return RightScale :: Platform . filesystem . pretty_path ( path , true ) end | Path to cache directory for given script |
18,437 | def search ( criteria ) begin @api_options = { :part => 'snippet' , :type => 'video' , :order => 'relevance' , :safeSearch => 'none' , } @categories = [ ] @count_filter = { } @criteria = Yourub :: Validator . confirm ( criteria ) search_by_criteria do | result | yield result end rescue ArgumentError => e Yourub . logge... | Search through the youtube API executing multiple queries where necessary |
18,438 | def get_views ( video_id ) params = { :id => video_id , :part => 'statistics' } request = Yourub :: REST :: Videos . list ( self , params ) v = Yourub :: Result . format ( request ) . first v ? Yourub :: CountFilter . get_views_count ( v ) : nil end | return the number of times a video was watched |
18,439 | def get ( video_id ) params = { :id => video_id , :part => 'snippet,statistics' } request = Yourub :: REST :: Videos . list ( self , params ) Yourub :: Result . format ( request ) . first end | return an hash containing the metadata for the given video |
18,440 | def parse_text_block ( text_indent = nil , from = nil ) empty_lines = 0 first_line = true embedded = nil case from when :from_tag first_line = true when :from_embedded embedded = true end close_bracket = false until @lines . empty? if @lines . first =~ / \A \s \s \Z / next_line @stacks . last << [ :newline ] empty_line... | This is fundamentally broken Can keep this for multi - lie html comment perhaps But don t lookahead on text otherwise |
18,441 | def render ( context , locals ) @context = context @pathname = context . pathname @directory = File . dirname ( @pathname ) @header = data [ HEADER_PATTERN , 0 ] || "" @body = $' || data @body += "\n" if @body != "" && @body !~ / \n \Z /m @included_pathnames = [ ] @result = "" @result . force_encoding ( body . encoding... | Implement render so that it uses our own header pattern . |
18,442 | def cleanup_state delete_if_exists ( state_file_path ) delete_if_exists ( chef_file_path ) delete_if_exists ( past_scripts_path ) delete_if_exists ( log_path ) delete_if_exists ( cook_state_file_path ) end | Cleanup files generated by instance state |
18,443 | def delete_if_exists ( file ) begin File . delete ( file ) if File . file? ( file ) rescue Exception => e puts "\nWARNING: #{e.message}" end end | Test and delete if exists |
18,444 | def setup_script_execution Dir . glob ( File . join ( RIGHT_LINK_SPEC_HELPER_TEMP_PATH , '__TestScript*' ) ) . should be_empty Dir . glob ( File . join ( RIGHT_LINK_SPEC_HELPER_TEMP_PATH , '[0-9]*' ) ) . should be_empty AgentConfig . cache_dir = File . join ( RIGHT_LINK_SPEC_HELPER_TEMP_PATH , 'cache' ) end | Setup location of files generated by script execution |
18,445 | def verify ( api_key = nil ) raise ConfigurationError , "You must provide an API key to verify" if api_key . nil? && self . api_key . nil? perform ( :verify , { :providerkey => provider_key , :apikey => api_key || self . api_key } , :get , Success ) end | Verify the configured API key is valid |
18,446 | def tables_with_comments ( stream ) tables_without_comments ( stream ) @connection . tables . sort . each do | table_name | dump_comments ( table_name , stream ) end unless ( index_comments = @connection . index_comments ) . empty? index_comments . each_pair do | index_name , comment | stream . puts " set_index_commen... | Support for dumping comments |
18,447 | def dump_comments ( table_name , stream ) unless ( comments = @connection . comments ( table_name ) ) . empty? comment_statements = comments . map do | row | column_name = row [ 0 ] comment = format_comment ( row [ 1 ] ) if column_name " set_column_comment '#{table_name}', '#{column_name}', '#{comment}'" else " set_t... | Dumps the comments on a particular table to the stream . |
18,448 | def send_command ( cmd , verbose , timeout = 20 ) config_options = :: RightScale :: AgentConfig . agent_options ( 'instance' ) listen_port = config_options [ :listen_port ] raise :: ArgumentError . new ( 'Could not retrieve agent listen port' ) unless listen_port client = :: RightScale :: CommandClient . new ( listen_p... | Creates a command client and sends the given payload . |
18,449 | def default_logger ( verbose = false ) if verbose logger = Logger . new ( STDOUT ) logger . level = Logger :: DEBUG logger . formatter = PlainLoggerFormatter . new else logger = RightScale :: Log end return logger end | Default logger for printing to console |
18,450 | def run $0 = "rs_ohai" Log . program_name = 'RightLink' init_logger RightScale :: OhaiSetup . configure_ohai Ohai :: Application . new . run true end | Activates RightScale environment before running ohai |
18,451 | def manage_planned_volumes ( & block ) return if InstanceState . value == 'stranded' last_mappings = InstanceState . planned_volume_state . mappings || [ ] payload = { :agent_identity => @agent_identity } req = RetryableRequest . new ( "/storage_valet/get_planned_volumes" , payload , :retry_delay => VolumeManagement ::... | Manages planned volumes by caching planned volume state and then ensuring volumes have been reattached in a predictable order for proper assignment of local drives . |
18,452 | def detach_planned_volume ( mapping ) payload = { :agent_identity => @agent_identity , :device_name => mapping [ :device_name ] } Log . info ( "Detaching volume #{mapping[:volume_id]} for management purposes." ) req = RetryableRequest . new ( "/storage_valet/detach_volume" , payload , :retry_delay => VolumeManagement :... | Detaches the planned volume given by its mapping . |
18,453 | def attach_planned_volume ( mapping ) vm = RightScale :: Platform . volume_manager InstanceState . planned_volume_state . disks ||= vm . disks InstanceState . planned_volume_state . volumes ||= vm . volumes payload = { :agent_identity => @agent_identity , :volume_id => mapping [ :volume_id ] , :device_name => mapping [... | Attaches the planned volume given by its mapping . |
18,454 | def manage_volume_device_assignment ( mapping ) unless 'attached' == mapping [ :management_status ] raise VolumeManagement :: UnexpectedState . new ( "The volume #{mapping[:volume_id]} was in an unexpected managed state: #{mapping.inspect}" ) end last_disks = InstanceState . planned_volume_state . disks last_volumes = ... | Manages device assignment for volumes with considerations for formatting blank attached volumes . |
18,455 | def merge_planned_volume_mappings ( last_mappings , current_planned_volumes ) results = [ ] vm = RightScale :: Platform . volume_manager current_planned_volumes . each do | planned_volume | raise VolumeManagement :: InvalidResponse . new ( "Reponse for volume mapping was invalid: #{mapping.inspect}" ) unless planned_vo... | Merges mappings from query with any last known mappings which may have a locally persisted state which needs to be evaluated . |
18,456 | def supported_by_platform? right_platform = RightScale :: Platform . linux? right_platform && LoginUserManager . user_exists? ( 'rightscale' ) && FeatureConfigManager . feature_enabled? ( 'managed_login_enable' ) end | Can the login manager function on this platform? |
18,457 | def update_policy ( new_policy , agent_identity ) return false unless supported_by_platform? update_users ( new_policy . users , agent_identity , new_policy ) do | audit_content | yield audit_content if block_given? end true end | Enact the login policy specified in new_policy for this system . The policy becomes effective immediately and controls which public keys are trusted for SSH access to the superuser account . |
18,458 | def get_key_prefix ( username , email , uuid , superuser , profile_data = nil ) if profile_data profile = " --profile #{Shellwords.escape(profile_data).gsub('"', '\\"')}" else profile = "" end superuser = superuser ? " --superuser" : "" %Q{command="rs_thunk --username #{username} --uuid #{uuid}#{superuser} --email #{em... | Returns prefix command for public key record |
18,459 | def get_ssh_host_keys ( ) keys = File . readlines ( File . join ( RightScale :: Platform . filesystem . ssh_cfg_dir , 'sshd_config' ) ) . map do | l | key = nil / \s \s / . match ( l ) { | m | key = m . captures [ 0 ] } key end . compact keys = keys . empty? ? SSH_DEFAULT_KEYS : keys keys . map { | k | k = "#{k}.pub" ;... | Returns current SSH host keys |
18,460 | def update_users ( users , agent_identity , new_policy ) public_keys_cache = { } if old_policy = InstanceState . login_policy public_keys_cache = old_policy . users . inject ( { } ) do | keys , user | user . public_key_fingerprints ||= user . public_keys . map { | key | fingerprint ( key , user . username ) } user . pu... | For any user with a public key fingerprint but no public key obtain the public key from the old policy or by querying RightScale using the fingerprints Remove a user if no public keys are available for it |
18,461 | def finalize_policy ( new_policy , agent_identity , new_policy_users , missing ) manage_existing_users ( new_policy_users ) user_lines = login_users_to_authorized_keys ( new_policy_users ) InstanceState . login_policy = new_policy write_keys_file ( user_lines , RIGHTSCALE_KEYS_FILE , { :user => 'rightscale' , :group =>... | Manipulates the authorized_keys file to match the given login policy Schedules expiration of users from policy and audits the policy in a human - readable format |
18,462 | def populate_public_keys ( users , public_keys_cache , remove_if_missing = false ) missing = [ ] users . reject! do | user | reject = false user . public_key_fingerprints ||= user . public_keys . map { | key | fingerprint ( key , user . username ) } user . public_key_fingerprints = user . public_keys . zip ( user . pub... | Populate missing public keys from old public keys using associated fingerprints Also populate any missing fingerprints where possible |
18,463 | def fingerprint ( public_key , username ) LoginUser . fingerprint ( public_key ) if public_key rescue Exception => e Log . error ( "Failed to create public key fingerprint for user #{username}" , e ) nil end | Create fingerprint for public key |
18,464 | def load_keys ( path ) file_lines = read_keys_file ( path ) keys = [ ] file_lines . map do | l | components = LoginPolicy . parse_public_key ( l ) if components keys << [ components [ 1 ] , components [ 2 ] , components [ 3 ] ] elsif l =~ COMMENT next else RightScale :: Log . error ( "Malformed (or not SSH2) entry in a... | Returns array of public keys of specified authorized_keys file |
18,465 | def describe_policy ( users , superusers , missing = [ ] ) normal_users = users - superusers audit = "#{users.size} authorized users (#{normal_users.size} normal, #{superusers.size} superuser).\n" audit << "Public key missing for #{missing.map { |u| u.username }.join(", ") }.\n" if missing . size > 0 return audit end | Return a verbose human - readable description of the login policy suitable for appending to an audit entry . Contains formatting such as newlines and tabs . |
18,466 | def login_users_to_authorized_keys ( new_users ) now = Time . now user_lines = [ ] new_users . each do | u | if u . expires_at . nil? || u . expires_at > now u . public_keys . each do | k | user_lines << "#{get_key_prefix(u.username, u.common_name, u.uuid, u.superuser, u.profile_data)} #{k}" end end end return user_lin... | Given a list of LoginUsers compute an authorized_keys file that encompasses all of the users and has a suitable options field that invokes rs_thunk with the right command - line params for that user . Omit any users who are expired . |
18,467 | def manage_existing_users ( new_policy_users ) now = Time . now previous = { } if InstanceState . login_policy InstanceState . login_policy . users . each do | user | previous [ user . uuid ] = user end end current = { } new_policy_users . each do | user | current [ user . uuid ] = user end added = current . keys - pre... | Schedules expiration of new users from policy and existing ones |
18,468 | def write_keys_file ( keys , keys_file , chown_params = nil ) dir = File . dirname ( keys_file ) FileUtils . mkdir_p ( dir ) FileUtils . chmod ( 0700 , dir ) File . open ( keys_file , 'w' ) do | f | f . puts "#" * 78 f . puts "# USE CAUTION WHEN EDITING THIS FILE BY HAND" f . puts "# This file is generated based on the... | Replace the contents of specified keys file |
18,469 | def frequencies_for ( words ) word_frequencies = { } words . each { | word | word_frequencies [ word ] = words . count ( word ) } word_frequencies end | Returns a Hash of frequencies of each uniq word in the text |
18,470 | def stems_for ( words ) stemmer = Lingua :: Stemmer . new ( language : 'en' ) words . map! { | word | stemmer . stem ( word ) } end | Converts all the words to its stem form |
18,471 | def emojies_in ( text ) ( sad_emojies + happy_emojies ) . map do | emoji | text . scan ( emoji ) end . flatten end | Captures and returns emojies in the text |
18,472 | def sanitize ( text ) text . gsub! ( / /i , '' ) text . gsub! ( / \/ \/ \+ \$ \w \+ \$ \w \/ \+ \/ \w \? \+ \w \w / , '' ) text . gsub! ( / \w \w \w \w \w / , '' ) text . gsub! ( / \s \s / , ' ' ) text . downcase end | Removing non ASCII characters from text |
18,473 | def call ( severity , time , progname , msg ) sprintf ( "%s: %s\n" , time . strftime ( "%H:%M:%S" ) , hide_inputs ( msg2str ( msg ) ) ) end | Generate log line from given input |
18,474 | def is_filtered? ( severity , message ) if filters = MESSAGE_FILTERS [ severity ] filters . each do | filter | return true if filter =~ message end end return false end | Filters any message which should not appear in audits . |
18,475 | def configure_root_access ( options = { } ) public_key = ENV [ 'VS_SSH_PUBLIC_KEY' ] . to_s . strip if public_key . nil? || public_key . empty? puts "No public SSH key found in metadata" return end update_authorized_keys ( public_key ) end | Configure root access for vSphere cloud |
18,476 | def update_authorized_keys ( public_key ) auth_key_file = "/root/.ssh/authorized_keys" FileUtils . mkdir_p ( File . dirname ( auth_key_file ) ) key_exists = false File . open ( auth_key_file , "r" ) do | file | file . each_line { | line | key_exists = true if line == public_key } end if File . exists? ( auth_key_file )... | Add public key to ssh authorized_keys file |
18,477 | def run_command ( message , command ) puts message begin send_command ( { :name => command } , verbose = false , timeout = 100 ) { | r | puts r } rescue SystemExit => e raise e rescue Exception => e $stderr . puts Log . format ( "Failed or else time limit was exceeded, confirm that local instance is still running" , e ... | Trigger execution of given command in instance agent and wait for it to be done |
18,478 | def can_contact_metadata_server? ( addr , port , timeout = 2 ) t = Socket . new ( Socket :: Constants :: AF_INET , Socket :: Constants :: SOCK_STREAM , 0 ) saddr = Socket . pack_sockaddr_in ( port , addr ) connected = false begin t . connect_nonblock ( saddr ) rescue Errno :: EINPROGRESS r , w , e = IO :: select ( nil ... | Attempt to connect to the given address on the given port as a quick verification that the metadata service is available . |
18,479 | def split_metadata ( data , splitter , name_value_delimiter = '=' ) hash = { } data . to_s . split ( splitter ) . each do | pair | name , value = pair . split ( name_value_delimiter , 2 ) hash [ name . strip ] = value . strip if name && value end hash end | Splits data on the given splitter character and returns hash . |
18,480 | def success_results ( content = nil , reply_to = '*test*1' ) Result . new ( AgentIdentity . generate , reply_to , { @agent_id => OperationResult . success ( content ) } , @agent_id ) end | Build a valid request results with given content |
18,481 | def perform unless @threads . any? { | t | t . alive? } @values . start! @size . times do @threads << Thread . new do while job = @queue . pop if job == :END_OF_WORK break else @values . push * job [ 1 ] , & job [ 0 ] end end end end end end | Starts execution of the thread pool . |
18,482 | def parse ( filename , linenum ) @filename , @linenum = filename , linenum buf = [ ] File . open ( filename , "rb" ) . each_with_index do | line , index | next if index < linenum - 1 buf << line begin return do_parse ( buf . join ) rescue :: Parser :: SyntaxError node = trim_and_retry ( buf ) return node if node end en... | Read file and try parsing if success parse find proc AST |
18,483 | def trim_and_retry ( buf ) * lines , last = buf lines << last . gsub ( / \s / , "" ) do_parse ( "a(#{lines.join})" ) rescue :: Parser :: SyntaxError end | Remove tail comma and wrap dummy method and retry parsing For proc inner Array or Hash |
18,484 | def errors errs = [ ] self . class . fields . except ( :project_id ) . each_with_object ( { } ) do | ( field_name , field_options ) , h | if options [ field_name ] . blank? errs << "#{field_options[:label]} must be present" end end return { :base => errs . to_sentence } unless errs . size . zero? unless gitlab_endpoint... | Called to validate user input . Just return a hash of errors if there are any |
18,485 | def gitlab_endpoint_exists? ( gitlab_url ) with_gitlab ( gitlab_url , 'Iamsecret' ) do | g | g . user end rescue Gitlab :: Error :: Unauthorized true rescue Exception false end | Checks whether there is a gitlab installation at the given + gitlab_url + |
18,486 | def gitlab_user_exists? ( gitlab_url , private_token ) with_gitlab ( gitlab_url , private_token ) do | g | g . user end true rescue Gitlab :: Error :: Unauthorized false end | Checks whether a user with the given + token + exists in the gitlab installation located at + gitlab_url + |
18,487 | def with_gitlab ( gitlab_url = options [ :endpoint ] , private_token = options [ :api_token ] ) yield Gitlab . client ( endpoint : gitlab_endpoint ( gitlab_url ) , private_token : private_token , user_agent : 'Errbit User Agent' ) end | Connects to the gitlab installation at + gitlab_url + using the given + private_token + and executes the given block |
18,488 | def create_full_path ( file_name ) path = full_path ( file_name ) FileUtils . mkdir_p ( File . dirname ( path ) ) path end | Creates the parent directory for the full path of generated file . |
18,489 | def write_file ( metadata ) File . open ( create_full_path ( @file_name_prefix ) , "w" , DEFAULT_FILE_MODE ) { | f | f . write ( metadata . to_s ) } end | Writes given metadata to file . |
18,490 | def write_metadata ( kind = WILDCARD ) options = @options . dup kind = kind . to_sym if kind == WILDCARD || kind == :user_metadata api_source = RightScale :: MetadataSources :: RightScaleApiMetadataSource . new ( options ) cloud_userdata_raw = "" if api_source . source_exists? extra_userdata_raw = api_source . get ( ) ... | Queries and writes current metadata to file . |
18,491 | def clear_state output_dir_paths = [ ] [ :user_metadata , :cloud_metadata ] . each do | kind | output_dir_paths |= metadata_writers ( kind ) . map { | w | w . output_dir_path } end last_exception = nil output_dir_paths . each do | output_dir_path | begin FileUtils . rm_rf ( output_dir_path ) if File . directory? ( outp... | Attempts to clear any files generated by writers . |
18,492 | def metadata_writers ( kind ) return @metadata_writers [ kind ] if @metadata_writers && @metadata_writers [ kind ] @metadata_writers ||= { } @metadata_writers [ kind ] ||= [ ] options = @options . dup options [ :kind ] = kind if kind == :user_metadata options [ :formatted_path_prefix ] = "RS_" options [ :output_dir_pat... | Gets the option given by path if it exists . |
18,493 | def cloud_metadata_generation_command ruby_path = File . normalize_path ( AgentConfig . ruby_cmd ) rs_cloud_path = File . normalize_path ( Gem . bin_path ( 'right_link' , 'cloud' ) ) return "#{ruby_path} #{rs_cloud_path} --action write_cloud_metadata" end | Assembles the command line needed to regenerate cloud metadata on demand . |
18,494 | def relative_to_script_path ( path ) path = path . gsub ( "\\" , '/' ) unless path == File . expand_path ( path ) path = File . normalize_path ( File . join ( File . dirname ( @script_path ) , path ) ) end path end | make the given path relative to this cloud s DSL script path only if the path is not already absolute . |
18,495 | def dev_log_level if value = tag_value ( LOG_LEVEL_TAG ) value = value . downcase . to_sym value = nil unless [ :debug , :info , :warn , :error , :fatal ] . include? ( value ) end value end | Determines the developer log level if any which forces and supercedes all other log level configurations . |
18,496 | def use_cookbooks_path? res = ! ! ( paths = cookbooks_path ) return false unless res paths . each do | path | res = path && File . directory? ( path ) && Dir . entries ( path ) != [ '.' , '..' ] break unless res end res end | Whether dev cookbooks path should be used instead of standard cookbooks repositories location True if in dev mode and all dev cookbooks repos directories are not empty |
18,497 | def update ( state_to_merge , overrides = { } ) @startup_tags = state_to_merge . startup_tags if state_to_merge . respond_to? ( :startup_tags ) @reboot = state_to_merge . reboot? if state_to_merge . respond_to? ( :reboot? ) @log_level = state_to_merge . log_level if state_to_merge . respond_to? ( :log_level ) if state_... | Re - initialize then merge given state |
18,498 | def save_state state_to_save = { 'startup_tags' => startup_tags , 'reboot' => reboot? , 'log_level' => log_level } if log_file state_to_save [ 'log_file' ] = log_file end if download_once? state_to_save [ 'has_downloaded_cookbooks' ] = has_downloaded_cookbooks? end RightScale :: JsonUtilities :: write_json ( RightScale... | Save dev state to file |
18,499 | def load_state if File . file? ( STATE_FILE ) state = RightScale :: JsonUtilities :: read_json ( STATE_FILE ) @log_level = state [ 'log_level' ] || Logger :: INFO Log . info ( "Initializing CookState from #{STATE_FILE} with #{state.inspect}" ) if @log_level == Logger :: DEBUG @has_downloaded_cookbooks = state [ 'has_d... | load dev state from disk |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.