_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3
values | text stringlengths 66 10.5k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q3800 | RightScale.VolumeManagementHelper.attach_planned_volume | train | def attach_planned_volume(mapping)
# preserve the initial list of disks/volumes before attachment for comparison later.
vm = RightScale::Platform.volume_manager
InstanceState.planned_volume_state.disks ||= vm.disks
InstanceState.planned_volume_state.volumes ||= vm.volumes
# attach.
... | ruby | {
"resource": ""
} |
q3801 | RightScale.VolumeManagementHelper.manage_volume_device_assignment | train | def manage_volume_device_assignment(mapping)
# only managed volumes should be in an attached state ready for assignment.
unless 'attached' == mapping[:management_status]
raise VolumeManagement::UnexpectedState.new("The volume #{mapping[:volume_id]} was in an unexpected managed state: #{mapping.insp... | ruby | {
"resource": ""
} |
q3802 | RightScale.VolumeManagementHelper.merge_planned_volume_mappings | train | def merge_planned_volume_mappings(last_mappings, current_planned_volumes)
results = []
vm = RightScale::Platform.volume_manager
# merge latest mappings with last mappings, if any.
current_planned_volumes.each do |planned_volume|
raise VolumeManagement::InvalidResponse.new("Reponse for v... | ruby | {
"resource": ""
} |
q3803 | RightScale.LoginManager.supported_by_platform? | train | def supported_by_platform?
right_platform = RightScale::Platform.linux?
# avoid calling user_exists? on unsupported platform(s)
right_platform && LoginUserManager.user_exists?('rightscale') && FeatureConfigManager.feature_enabled?('managed_login_enable')
end | ruby | {
"resource": ""
} |
q3804 | RightScale.LoginManager.update_policy | train | 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 | ruby | {
"resource": ""
} |
q3805 | RightScale.LoginManager.get_key_prefix | train | 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... | ruby | {
"resource": ""
} |
q3806 | RightScale.LoginManager.get_ssh_host_keys | train | def get_ssh_host_keys()
# Try to read the sshd_config file first
keys = File.readlines(
File.join(RightScale::Platform.filesystem.ssh_cfg_dir, 'sshd_config')).map do |l|
key = nil
/^\s*HostKey\s+([^ ].*)/.match(l) { |m| key = m.captures[0] }
key
end.compact
... | ruby | {
"resource": ""
} |
q3807 | RightScale.LoginManager.update_users | train | def update_users(users, agent_identity, new_policy)
# Create cache of public keys from stored instance state
# but there won't be any on initial launch
public_keys_cache = {}
if old_policy = InstanceState.login_policy
public_keys_cache = old_policy.users.inject({}) do |keys, user|
... | ruby | {
"resource": ""
} |
q3808 | RightScale.LoginManager.finalize_policy | train | 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', :... | ruby | {
"resource": ""
} |
q3809 | RightScale.LoginManager.populate_public_keys | train | def populate_public_keys(users, public_keys_cache, remove_if_missing = false)
missing = []
users.reject! do |user|
reject = false
# Create any missing fingerprints from the public keys so that fingerprints
# are as populated as possible
user.public_key_fingerprints ||= user.... | ruby | {
"resource": ""
} |
q3810 | RightScale.LoginManager.fingerprint | train | 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 | ruby | {
"resource": ""
} |
q3811 | RightScale.LoginManager.load_keys | train | def load_keys(path)
file_lines = read_keys_file(path)
keys = []
file_lines.map do |l|
components = LoginPolicy.parse_public_key(l)
if components
#preserve algorithm, key and comments; discard options (the 0th element)
keys << [ components[1], components[2], compon... | ruby | {
"resource": ""
} |
q3812 | RightScale.LoginManager.describe_policy | train | 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
... | ruby | {
"resource": ""
} |
q3813 | RightScale.LoginManager.login_users_to_authorized_keys | train | 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}"... | ruby | {
"resource": ""
} |
q3814 | RightScale.LoginManager.manage_existing_users | train | 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... | ruby | {
"resource": ""
} |
q3815 | RightScale.LoginManager.write_keys_file | train | 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 generate... | ruby | {
"resource": ""
} |
q3816 | SadPanda.Helpers.frequencies_for | train | def frequencies_for(words)
word_frequencies = {}
words.each { |word| word_frequencies[word] = words.count(word) }
word_frequencies
end | ruby | {
"resource": ""
} |
q3817 | SadPanda.Helpers.stems_for | train | def stems_for(words)
stemmer = Lingua::Stemmer.new(language: 'en')
words.map! { |word| stemmer.stem(word) }
end | ruby | {
"resource": ""
} |
q3818 | SadPanda.Helpers.emojies_in | train | def emojies_in(text)
(sad_emojies + happy_emojies).map do |emoji|
text.scan(emoji)
end.flatten
end | ruby | {
"resource": ""
} |
q3819 | SadPanda.Helpers.sanitize | train | def sanitize(text)
text.gsub!(/[^a-z ]/i, '')
text.gsub!(/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/, '')
text.gsub!(/(?=\w*h)(?=\w*t)(?=\w*t)(?=\w*p)\w*/, '')
text.gsub!(/\s\s... | ruby | {
"resource": ""
} |
q3820 | RightScale.AuditLogFormatter.call | train | def call(severity, time, progname, msg)
sprintf("%s: %s\n", time.strftime("%H:%M:%S"), hide_inputs(msg2str(msg)))
end | ruby | {
"resource": ""
} |
q3821 | RightScale.AuditLogger.is_filtered? | train | def is_filtered?(severity, message)
if filters = MESSAGE_FILTERS[severity]
filters.each do |filter|
return true if filter =~ message
end
end
return false
end | ruby | {
"resource": ""
} |
q3822 | RightScale.SystemConfigurator.configure_root_access | train | def configure_root_access(options = {})
public_key = ENV['VS_SSH_PUBLIC_KEY'].to_s.strip
# was there a key found?
if public_key.nil? || public_key.empty?
puts "No public SSH key found in metadata"
return
end
update_authorized_keys(public_key)
end | ruby | {
"resource": ""
} |
q3823 | RightScale.SystemConfigurator.update_authorized_keys | train | def update_authorized_keys(public_key)
auth_key_file = "/root/.ssh/authorized_keys"
FileUtils.mkdir_p(File.dirname(auth_key_file)) # make sure the directory exists
key_exists = false
File.open(auth_key_file, "r") do |file|
file.each_line { |line| key_exists = true if line == public_ke... | ruby | {
"resource": ""
} |
q3824 | RightScale.RightLinkAgentController.run_command | train | 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 ... | ruby | {
"resource": ""
} |
q3825 | RightScale.CloudUtilities.can_contact_metadata_server? | train | 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::selec... | ruby | {
"resource": ""
} |
q3826 | RightScale.CloudUtilities.split_metadata | train | 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 | ruby | {
"resource": ""
} |
q3827 | RightScale.ResultsMock.success_results | train | def success_results(content = nil, reply_to = '*test*1')
Result.new(AgentIdentity.generate, reply_to,
{ @agent_id => OperationResult.success(content) }, @agent_id)
end | ruby | {
"resource": ""
} |
q3828 | FutureProof.ThreadPool.perform | train | 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
... | ruby | {
"resource": ""
} |
q3829 | ProcToAst.Parser.parse | train | 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_... | ruby | {
"resource": ""
} |
q3830 | ProcToAst.Parser.trim_and_retry | train | def trim_and_retry(buf)
*lines, last = buf
# For inner Array or Hash or Arguments list.
lines << last.gsub(/,\s*$/, "")
do_parse("a(#{lines.join})") # wrap dummy method
rescue ::Parser::SyntaxError
end | ruby | {
"resource": ""
} |
q3831 | ErrbitGitlabPlugin.IssueTracker.errors | train | def errors
errs = []
# Make sure that every field is filled out
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
# We can only ... | ruby | {
"resource": ""
} |
q3832 | ErrbitGitlabPlugin.IssueTracker.gitlab_endpoint_exists? | train | 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 | ruby | {
"resource": ""
} |
q3833 | ErrbitGitlabPlugin.IssueTracker.gitlab_user_exists? | train | 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 | ruby | {
"resource": ""
} |
q3834 | ErrbitGitlabPlugin.IssueTracker.with_gitlab | train | 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 | ruby | {
"resource": ""
} |
q3835 | RightScale.MetadataWriter.create_full_path | train | def create_full_path(file_name)
path = full_path(file_name)
FileUtils.mkdir_p(File.dirname(path))
path
end | ruby | {
"resource": ""
} |
q3836 | RightScale.MetadataWriter.write_file | train | def write_file(metadata)
File.open(create_full_path(@file_name_prefix), "w", DEFAULT_FILE_MODE) { |f| f.write(metadata.to_s) }
end | ruby | {
"resource": ""
} |
q3837 | RightScale.Cloud.write_metadata | train | def write_metadata(kind = WILDCARD)
options = @options.dup
kind = kind.to_sym
if kind == WILDCARD || kind == :user_metadata
# Both "blue-skies" cloud and "wrap instance" behave the same way, they lay down a
# file in a predefined location (/var/spool/rightscale/user-data.txt on linux,... | ruby | {
"resource": ""
} |
q3838 | RightScale.Cloud.clear_state | train | 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_pa... | ruby | {
"resource": ""
} |
q3839 | RightScale.Cloud.metadata_writers | train | 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_"
... | ruby | {
"resource": ""
} |
q3840 | RightScale.Cloud.cloud_metadata_generation_command | train | 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 | ruby | {
"resource": ""
} |
q3841 | RightScale.Cloud.relative_to_script_path | train | 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 | ruby | {
"resource": ""
} |
q3842 | RightScale.CookState.dev_log_level | train | 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 | ruby | {
"resource": ""
} |
q3843 | RightScale.CookState.use_cookbooks_path? | train | 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 | ruby | {
"resource": ""
} |
q3844 | RightScale.CookState.update | train | def update(state_to_merge, overrides = {})
# only merge state if state to be merged has values
@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_mer... | ruby | {
"resource": ""
} |
q3845 | RightScale.CookState.save_state | train | def save_state
# start will al state to be saved
state_to_save = { 'startup_tags' => startup_tags,
'reboot' => reboot?,
'log_level' => log_level }
# only save a log file one is defined
if log_file
state_to_save['log_file'] = log_file
end... | ruby | {
"resource": ""
} |
q3846 | RightScale.CookState.load_state | train | 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 =... | ruby | {
"resource": ""
} |
q3847 | RightScale.CloudFactory.register | train | 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 | ruby | {
"resource": ""
} |
q3848 | RightScale.CloudFactory.registered_script_path | train | 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 | ruby | {
"resource": ""
} |
q3849 | RightScale.CloudFactory.create | train | 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_name ... | ruby | {
"resource": ""
} |
q3850 | RightScale.CloudFactory.default_cloud_name | train | 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 | ruby | {
"resource": ""
} |
q3851 | RightScale.MultiThreadBundleQueue.busy? | train | def busy?
busy = false
@mutex.synchronize { busy = @thread_name_to_queue.any? { |_, q| q.busy? } }
busy
end | ruby | {
"resource": ""
} |
q3852 | RightScale.MultiThreadBundleQueue.push_to_thread_queue | train | 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
# continuation for when thread-nam... | ruby | {
"resource": ""
} |
q3853 | RightScale.MultiThreadBundleQueue.groom_thread_queues | train | 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 | ruby | {
"resource": ""
} |
q3854 | RightScale.MultiThreadBundleQueue.close_thread_queues | train | 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 | ruby | {
"resource": ""
} |
q3855 | RightScale.InstanceAuthClient.create_http_client | train | 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 = @... | ruby | {
"resource": ""
} |
q3856 | RightScale.InstanceAuthClient.get_authorized | train | 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_li... | ruby | {
"resource": ""
} |
q3857 | RightScale.InstanceAuthClient.renew_authorization | train | 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_... | ruby | {
"resource": ""
} |
q3858 | RightScale.InstanceAuthClient.update_urls | train | 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]) != @route... | ruby | {
"resource": ""
} |
q3859 | RightScale.InstanceAuthClient.redirected | train | 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 !~ /http/ |... | ruby | {
"resource": ""
} |
q3860 | RightScale.InstanceAuthClient.reconnect | train | 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")
@r... | ruby | {
"resource": ""
} |
q3861 | FutureProof.FutureQueue.push | train | 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 | ruby | {
"resource": ""
} |
q3862 | RightScale.WindowsNetworkConfigurator.get_device_ip | train | def get_device_ip(device)
ip_addr = device_config_show(device).lines("\n").grep(/IP Address/).shift
return nil unless ip_addr
ip_addr.strip.split.last
end | ruby | {
"resource": ""
} |
q3863 | RightScale.Thunker.run | train | 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 = optio... | ruby | {
"resource": ""
} |
q3864 | RightScale.Thunker.create_audit_entry | train | def create_audit_entry(email, username, access, command, client_ip=nil)
begin
hostname = `hostname`.strip
rescue Exception => e
hostname = 'localhost'
end
case access
when :scp then
summary = 'SSH file copy'
detail = "User copied files copied (scp)... | ruby | {
"resource": ""
} |
q3865 | RightScale.Thunker.display_motd | train | def display_motd
if ::File.exists?("/var/run/motd.dynamic")
# Ubuntu 14.04+ motd location
puts ::File.read("/var/run/motd.dynamic")
elsif ::File.exists?("/var/run/motd")
# Ubuntu 12.04 motd location
puts ::File.read("/var/run/motd")
elsif ::File.exists?("/etc/motd")
... | ruby | {
"resource": ""
} |
q3866 | BEL.Quoting.quote | train | def quote(value)
string = value.to_s
unquoted = unquote(string)
escaped = unquoted.gsub(QuoteNotEscapedMatcher, "\\\"")
%Q{"#{escaped}"}
end | ruby | {
"resource": ""
} |
q3867 | RightScale.CloudController.control | train | 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]
# support either single or a com... | ruby | {
"resource": ""
} |
q3868 | Nguyen.Fdf.to_fdf | train | 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
... | ruby | {
"resource": ""
} |
q3869 | Nguyen.Xfdf.to_xfdf | train | 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]
xml... | ruby | {
"resource": ""
} |
q3870 | RightScale.NetworkConfigurator.configure_routes | train | def configure_routes
# required metadata values
routes = ENV.keys.select { |k| k =~ /^RS_ROUTE(\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[ci... | ruby | {
"resource": ""
} |
q3871 | RightScale.NetworkConfigurator.network_route_add | train | 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 | ruby | {
"resource": ""
} |
q3872 | RightScale.NetworkConfigurator.network_route_exists? | train | def network_route_exists?(network, nat_server_ip)
routes = routes_show()
matchdata = routes.match(route_regex(network, nat_server_ip))
matchdata != nil
end | ruby | {
"resource": ""
} |
q3873 | RightScale.NetworkConfigurator.add_static_ip | train | def add_static_ip(n_ip=0)
begin
# required metadata values
ipaddr = ENV["RS_IP#{n_ip}_ADDR"]
netmask = ENV["RS_IP#{n_ip}_NETMASK"]
# optional
gateway = ENV["RS_IP#{n_ip}_GATEWAY"]
device = shell_escape_if_necessary(device_name_from_mac(ENV["RS_IP#{n_ip}_MAC"]))
... | ruby | {
"resource": ""
} |
q3874 | RightScale.NetworkConfigurator.configure_network_adaptor | train | 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)
# gateway is optional
if gateway
raise "ERROR: invalid gateway IP address: ... | ruby | {
"resource": ""
} |
q3875 | RightScale.NetworkConfigurator.nameservers_for_device | train | 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
# Non-fatal error, we only need one working
... | ruby | {
"resource": ""
} |
q3876 | RightScale.Tagger.run | train | def run(options)
fail_if_right_agent_is_not_running
check_privileges
set_logger(options)
missing_argument unless options.include?(:action)
# Don't use send_command callback as it swallows exceptions by design
res = send_command(build_cmd(options), options[:verbose], options[:timeout]... | ruby | {
"resource": ""
} |
q3877 | RightScale.Tagger.format_output | train | 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... | ruby | {
"resource": ""
} |
q3878 | RightScale.AuditCookStub.forward_audit | train | 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 | ruby | {
"resource": ""
} |
q3879 | RightScale.AuditCookStub.close | train | 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 | ruby | {
"resource": ""
} |
q3880 | RightScale.ReposeDownloader.download | train | 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|
... | ruby | {
"resource": ""
} |
q3881 | RightScale.ReposeDownloader.resolve | train | 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
... | ruby | {
"resource": ""
} |
q3882 | RightScale.ReposeDownloader.parse_exception_message | train | def parse_exception_message(e)
if e.kind_of?(RightSupport::Net::NoResult)
# Expected format of exception message: "... endpoints: ('<ip address>' => <exception class name array>, ...)""
i = 0
e.message.split(/\[|\]/).select {((i += 1) % 2) == 0 }.map { |s| s.split(/,\s*/) }.flatten
e... | ruby | {
"resource": ""
} |
q3883 | RightScale.ReposeDownloader.hostnames_ips | train | def hostnames_ips
@hostnames.map do |hostname|
ips.select { |ip, host| host == hostname }.keys
end.flatten
end | ruby | {
"resource": ""
} |
q3884 | RightScale.ReposeDownloader.balancer | train | 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) }
... | ruby | {
"resource": ""
} |
q3885 | Verse.Padding.pad | train | 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_wi... | ruby | {
"resource": ""
} |
q3886 | RightScale.SingleThreadBundleQueue.create_sequence | train | 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 | ruby | {
"resource": ""
} |
q3887 | RightScale.SingleThreadBundleQueue.audit_status | train | 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("SingleThread... | ruby | {
"resource": ""
} |
q3888 | RightScale.FetchRunner.setup_log | train | 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')}... | ruby | {
"resource": ""
} |
q3889 | RightScale.FetchRunner.run_fetcher | train | 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 << sour... | ruby | {
"resource": ""
} |
q3890 | Mago.SexpProcessor.process_lit | train | 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 | ruby | {
"resource": ""
} |
q3891 | BEL::JSON.Implementation.write | train | def write(data, output_io, options = {})
options = {
:mode => :compat
}.merge!(options)
if output_io
# write json and return IO
Oj.to_stream(output_io, data, options)
output_io
else
# return json string
string_io = StringIO.new
Oj.to_strea... | ruby | {
"resource": ""
} |
q3892 | RightScale.ExecutableSequence.sensitive_inputs | train | 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) }
... | ruby | {
"resource": ""
} |
q3893 | RightScale.ExecutableSequence.configure_logging | train | def configure_logging
Chef::Log.logger = AuditLogger.new(sensitive_inputs)
Chef::Log.logger.level = Log.level_from_sym(Log.level)
end | ruby | {
"resource": ""
} |
q3894 | RightScale.ExecutableSequence.configure_chef | train | def configure_chef
# setup logger for mixlib-shellout gem to consume instead of the chef
# v0.10.10 behavior of not logging ShellOut calls by default. also setup
# command failure exception and callback for legacy reasons.
::Mixlib::ShellOut.default_logger = ::Chef::Log
::Mixlib::ShellOut.... | ruby | {
"resource": ""
} |
q3895 | RightScale.ExecutableSequence.update_cookbook_path | train | def update_cookbook_path
# both cookbook sequences and paths are listed in same order as
# presented in repo UI. previous to RL v5.7 we received cookbook sequences
# in an arbitrary order, but this has been fixed as of the release of v5.8
# (we will not change the order for v5.7-).
# for c... | ruby | {
"resource": ""
} |
q3896 | RightScale.ExecutableSequence.checkout_cookbook_repos | train | 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
# only c... | ruby | {
"resource": ""
} |
q3897 | RightScale.ExecutableSequence.check_ohai | train | 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...")
# Need to execute on defer thread consistent with where ExecutableSequence is running
# othe... | ruby | {
"resource": ""
} |
q3898 | RightScale.ExecutableSequence.create_ohai | train | def create_ohai
ohai = Ohai::System.new
ohai.require_plugin('os')
ohai.require_plugin('hostname')
return ohai
end | ruby | {
"resource": ""
} |
q3899 | RightScale.ExecutableSequence.report_success | train | 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)
# We don't want to send back new attributes (ohai etc.)
patch[:right_only] = { ... | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.