repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
sequence | docstring
stringlengths 8
16k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
kontena/kontena | cli/lib/kontena/cli/helpers/exec_helper.rb | Kontena::Cli::Helpers.ExecHelper.websocket_exec | def websocket_exec(path, cmd, interactive: false, shell: false, tty: false)
exit_status = nil
write_thread = nil
query = {}
query[:interactive] = interactive if interactive
query[:shell] = shell if shell
query[:tty] = tty if tty
server = require_current_master
url = websocket_url(path, query)
token = require_token
options = WEBSOCKET_CLIENT_OPTIONS.dup
options[:headers] = {
'Authorization' => "Bearer #{token.access_token}"
}
options[:ssl_params] = {
verify_mode: ENV['SSL_IGNORE_ERRORS'].to_s == 'true' ? OpenSSL::SSL::VERIFY_NONE : OpenSSL::SSL::VERIFY_PEER,
ca_file: server.ssl_cert_path,
}
options[:ssl_hostname] = server.ssl_subject_cn
logger.debug { "websocket exec connect... #{url}" }
# we do not expect CloseError, because the server will send an 'exit' message first,
# and we return before seeing the close frame
# TODO: handle HTTP 404 errors
Kontena::Websocket::Client.connect(url, **options) do |ws|
logger.debug { "websocket exec open" }
# first frame contains exec command
websocket_exec_write(ws, 'cmd' => cmd)
if interactive
# start new thread to write from stdin to websocket
write_thread = websocket_exec_write_thread(ws, tty: tty)
end
# blocks reading from websocket, returns with exec exit code
exit_status = websocket_exec_read(ws)
fail ws.close_reason unless exit_status
end
rescue Kontena::Websocket::Error => exc
exit_with_error(exc)
rescue => exc
logger.error { "websocket exec error: #{exc}" }
raise
else
logger.debug { "websocket exec exit: #{exit_status}"}
return exit_status
ensure
if write_thread
write_thread.kill
write_thread.join
end
end | ruby | def websocket_exec(path, cmd, interactive: false, shell: false, tty: false)
exit_status = nil
write_thread = nil
query = {}
query[:interactive] = interactive if interactive
query[:shell] = shell if shell
query[:tty] = tty if tty
server = require_current_master
url = websocket_url(path, query)
token = require_token
options = WEBSOCKET_CLIENT_OPTIONS.dup
options[:headers] = {
'Authorization' => "Bearer #{token.access_token}"
}
options[:ssl_params] = {
verify_mode: ENV['SSL_IGNORE_ERRORS'].to_s == 'true' ? OpenSSL::SSL::VERIFY_NONE : OpenSSL::SSL::VERIFY_PEER,
ca_file: server.ssl_cert_path,
}
options[:ssl_hostname] = server.ssl_subject_cn
logger.debug { "websocket exec connect... #{url}" }
# we do not expect CloseError, because the server will send an 'exit' message first,
# and we return before seeing the close frame
# TODO: handle HTTP 404 errors
Kontena::Websocket::Client.connect(url, **options) do |ws|
logger.debug { "websocket exec open" }
# first frame contains exec command
websocket_exec_write(ws, 'cmd' => cmd)
if interactive
# start new thread to write from stdin to websocket
write_thread = websocket_exec_write_thread(ws, tty: tty)
end
# blocks reading from websocket, returns with exec exit code
exit_status = websocket_exec_read(ws)
fail ws.close_reason unless exit_status
end
rescue Kontena::Websocket::Error => exc
exit_with_error(exc)
rescue => exc
logger.error { "websocket exec error: #{exc}" }
raise
else
logger.debug { "websocket exec exit: #{exit_status}"}
return exit_status
ensure
if write_thread
write_thread.kill
write_thread.join
end
end | [
"def",
"websocket_exec",
"(",
"path",
",",
"cmd",
",",
"interactive",
":",
"false",
",",
"shell",
":",
"false",
",",
"tty",
":",
"false",
")",
"exit_status",
"=",
"nil",
"write_thread",
"=",
"nil",
"query",
"=",
"{",
"}",
"query",
"[",
":interactive",
"]",
"=",
"interactive",
"if",
"interactive",
"query",
"[",
":shell",
"]",
"=",
"shell",
"if",
"shell",
"query",
"[",
":tty",
"]",
"=",
"tty",
"if",
"tty",
"server",
"=",
"require_current_master",
"url",
"=",
"websocket_url",
"(",
"path",
",",
"query",
")",
"token",
"=",
"require_token",
"options",
"=",
"WEBSOCKET_CLIENT_OPTIONS",
".",
"dup",
"options",
"[",
":headers",
"]",
"=",
"{",
"'Authorization'",
"=>",
"\"Bearer #{token.access_token}\"",
"}",
"options",
"[",
":ssl_params",
"]",
"=",
"{",
"verify_mode",
":",
"ENV",
"[",
"'SSL_IGNORE_ERRORS'",
"]",
".",
"to_s",
"==",
"'true'",
"?",
"OpenSSL",
"::",
"SSL",
"::",
"VERIFY_NONE",
":",
"OpenSSL",
"::",
"SSL",
"::",
"VERIFY_PEER",
",",
"ca_file",
":",
"server",
".",
"ssl_cert_path",
",",
"}",
"options",
"[",
":ssl_hostname",
"]",
"=",
"server",
".",
"ssl_subject_cn",
"logger",
".",
"debug",
"{",
"\"websocket exec connect... #{url}\"",
"}",
"# we do not expect CloseError, because the server will send an 'exit' message first,",
"# and we return before seeing the close frame",
"# TODO: handle HTTP 404 errors",
"Kontena",
"::",
"Websocket",
"::",
"Client",
".",
"connect",
"(",
"url",
",",
"**",
"options",
")",
"do",
"|",
"ws",
"|",
"logger",
".",
"debug",
"{",
"\"websocket exec open\"",
"}",
"# first frame contains exec command",
"websocket_exec_write",
"(",
"ws",
",",
"'cmd'",
"=>",
"cmd",
")",
"if",
"interactive",
"# start new thread to write from stdin to websocket",
"write_thread",
"=",
"websocket_exec_write_thread",
"(",
"ws",
",",
"tty",
":",
"tty",
")",
"end",
"# blocks reading from websocket, returns with exec exit code",
"exit_status",
"=",
"websocket_exec_read",
"(",
"ws",
")",
"fail",
"ws",
".",
"close_reason",
"unless",
"exit_status",
"end",
"rescue",
"Kontena",
"::",
"Websocket",
"::",
"Error",
"=>",
"exc",
"exit_with_error",
"(",
"exc",
")",
"rescue",
"=>",
"exc",
"logger",
".",
"error",
"{",
"\"websocket exec error: #{exc}\"",
"}",
"raise",
"else",
"logger",
".",
"debug",
"{",
"\"websocket exec exit: #{exit_status}\"",
"}",
"return",
"exit_status",
"ensure",
"if",
"write_thread",
"write_thread",
".",
"kill",
"write_thread",
".",
"join",
"end",
"end"
] | Connect to server websocket, send from stdin, and write out messages
@param paths [String]
@param options [Hash] @see Kontena::Websocket::Client
@param cmd [Array<String>] command to execute
@param interactive [Boolean] Interactive TTY on/off
@param shell [Boolean] Shell on/of
@param tty [Boolean] TTY on/of
@return [Integer] exit code | [
"Connect",
"to",
"server",
"websocket",
"send",
"from",
"stdin",
"and",
"write",
"out",
"messages"
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/cli/helpers/exec_helper.rb#L137-L197 | train |
kontena/kontena | agent/lib/kontena/launchers/etcd.rb | Kontena::Launchers.Etcd.update_membership | def update_membership(node)
info 'checking if etcd previous membership needs to be updated'
etcd_connection = find_etcd_node(node)
return 'new' unless etcd_connection # No etcd hosts available, bootstrapping first node --> new cluster
weave_ip = node.overlay_ip
peer_url = "http://#{weave_ip}:2380"
client_url = "http://#{weave_ip}:2379"
members = JSON.parse(etcd_connection.get.body)
members['members'].each do |member|
if member['peerURLs'].include?(peer_url) && member['clientURLs'].include?(client_url)
# When there's both peer and client URLs, the given peer has been a member of the cluster
# and needs to be replaced
delete_membership(etcd_connection, member['id'])
sleep 1 # There seems to be some race condition with etcd member API, thus some sleeping required
add_membership(etcd_connection, peer_url)
sleep 1
return 'existing'
elsif member['peerURLs'].include?(peer_url) && !member['clientURLs'].include?(client_url)
# Peer found but not been part of the cluster yet, no modification needed and it can join as new member
return 'new'
end
end
info 'previous member info not found at all, adding'
add_membership(etcd_connection, peer_url)
'new' # Newly added member will join as new member
end | ruby | def update_membership(node)
info 'checking if etcd previous membership needs to be updated'
etcd_connection = find_etcd_node(node)
return 'new' unless etcd_connection # No etcd hosts available, bootstrapping first node --> new cluster
weave_ip = node.overlay_ip
peer_url = "http://#{weave_ip}:2380"
client_url = "http://#{weave_ip}:2379"
members = JSON.parse(etcd_connection.get.body)
members['members'].each do |member|
if member['peerURLs'].include?(peer_url) && member['clientURLs'].include?(client_url)
# When there's both peer and client URLs, the given peer has been a member of the cluster
# and needs to be replaced
delete_membership(etcd_connection, member['id'])
sleep 1 # There seems to be some race condition with etcd member API, thus some sleeping required
add_membership(etcd_connection, peer_url)
sleep 1
return 'existing'
elsif member['peerURLs'].include?(peer_url) && !member['clientURLs'].include?(client_url)
# Peer found but not been part of the cluster yet, no modification needed and it can join as new member
return 'new'
end
end
info 'previous member info not found at all, adding'
add_membership(etcd_connection, peer_url)
'new' # Newly added member will join as new member
end | [
"def",
"update_membership",
"(",
"node",
")",
"info",
"'checking if etcd previous membership needs to be updated'",
"etcd_connection",
"=",
"find_etcd_node",
"(",
"node",
")",
"return",
"'new'",
"unless",
"etcd_connection",
"# No etcd hosts available, bootstrapping first node --> new cluster",
"weave_ip",
"=",
"node",
".",
"overlay_ip",
"peer_url",
"=",
"\"http://#{weave_ip}:2380\"",
"client_url",
"=",
"\"http://#{weave_ip}:2379\"",
"members",
"=",
"JSON",
".",
"parse",
"(",
"etcd_connection",
".",
"get",
".",
"body",
")",
"members",
"[",
"'members'",
"]",
".",
"each",
"do",
"|",
"member",
"|",
"if",
"member",
"[",
"'peerURLs'",
"]",
".",
"include?",
"(",
"peer_url",
")",
"&&",
"member",
"[",
"'clientURLs'",
"]",
".",
"include?",
"(",
"client_url",
")",
"# When there's both peer and client URLs, the given peer has been a member of the cluster",
"# and needs to be replaced",
"delete_membership",
"(",
"etcd_connection",
",",
"member",
"[",
"'id'",
"]",
")",
"sleep",
"1",
"# There seems to be some race condition with etcd member API, thus some sleeping required",
"add_membership",
"(",
"etcd_connection",
",",
"peer_url",
")",
"sleep",
"1",
"return",
"'existing'",
"elsif",
"member",
"[",
"'peerURLs'",
"]",
".",
"include?",
"(",
"peer_url",
")",
"&&",
"!",
"member",
"[",
"'clientURLs'",
"]",
".",
"include?",
"(",
"client_url",
")",
"# Peer found but not been part of the cluster yet, no modification needed and it can join as new member",
"return",
"'new'",
"end",
"end",
"info",
"'previous member info not found at all, adding'",
"add_membership",
"(",
"etcd_connection",
",",
"peer_url",
")",
"'new'",
"# Newly added member will join as new member",
"end"
] | Removes possible previous member with the same IP
@param [Node] node
@return [String] the state of the cluster member | [
"Removes",
"possible",
"previous",
"member",
"with",
"the",
"same",
"IP"
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/launchers/etcd.rb#L173-L203 | train |
kontena/kontena | agent/lib/kontena/launchers/etcd.rb | Kontena::Launchers.Etcd.find_etcd_node | def find_etcd_node(node)
grid_subnet = IPAddr.new(node.grid['subnet'])
tries = node.grid['initial_size']
begin
etcd_host = "http://#{grid_subnet[tries]}:2379/v2/members"
info "connecting to existing etcd at #{etcd_host}"
connection = Excon.new(etcd_host)
members = JSON.parse(connection.get.body)
return connection
rescue Excon::Errors::Error => exc
tries -= 1
if tries > 0
info 'retrying next etcd host'
retry
else
info 'no online etcd host found, we\'re probably bootstrapping first node'
end
end
nil
end | ruby | def find_etcd_node(node)
grid_subnet = IPAddr.new(node.grid['subnet'])
tries = node.grid['initial_size']
begin
etcd_host = "http://#{grid_subnet[tries]}:2379/v2/members"
info "connecting to existing etcd at #{etcd_host}"
connection = Excon.new(etcd_host)
members = JSON.parse(connection.get.body)
return connection
rescue Excon::Errors::Error => exc
tries -= 1
if tries > 0
info 'retrying next etcd host'
retry
else
info 'no online etcd host found, we\'re probably bootstrapping first node'
end
end
nil
end | [
"def",
"find_etcd_node",
"(",
"node",
")",
"grid_subnet",
"=",
"IPAddr",
".",
"new",
"(",
"node",
".",
"grid",
"[",
"'subnet'",
"]",
")",
"tries",
"=",
"node",
".",
"grid",
"[",
"'initial_size'",
"]",
"begin",
"etcd_host",
"=",
"\"http://#{grid_subnet[tries]}:2379/v2/members\"",
"info",
"\"connecting to existing etcd at #{etcd_host}\"",
"connection",
"=",
"Excon",
".",
"new",
"(",
"etcd_host",
")",
"members",
"=",
"JSON",
".",
"parse",
"(",
"connection",
".",
"get",
".",
"body",
")",
"return",
"connection",
"rescue",
"Excon",
"::",
"Errors",
"::",
"Error",
"=>",
"exc",
"tries",
"-=",
"1",
"if",
"tries",
">",
"0",
"info",
"'retrying next etcd host'",
"retry",
"else",
"info",
"'no online etcd host found, we\\'re probably bootstrapping first node'",
"end",
"end",
"nil",
"end"
] | Finds a working etcd node from set of initial nodes
@param [Node] node
@return [Hash] The cluster members as given by etcd API | [
"Finds",
"a",
"working",
"etcd",
"node",
"from",
"set",
"of",
"initial",
"nodes"
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/launchers/etcd.rb#L210-L231 | train |
kontena/kontena | agent/lib/kontena/launchers/etcd.rb | Kontena::Launchers.Etcd.add_membership | def add_membership(connection, peer_url)
info "Adding new etcd membership info with peer URL #{peer_url}"
connection.post(:body => JSON.generate(peerURLs: [peer_url]),
:headers => { 'Content-Type' => 'application/json' })
end | ruby | def add_membership(connection, peer_url)
info "Adding new etcd membership info with peer URL #{peer_url}"
connection.post(:body => JSON.generate(peerURLs: [peer_url]),
:headers => { 'Content-Type' => 'application/json' })
end | [
"def",
"add_membership",
"(",
"connection",
",",
"peer_url",
")",
"info",
"\"Adding new etcd membership info with peer URL #{peer_url}\"",
"connection",
".",
"post",
"(",
":body",
"=>",
"JSON",
".",
"generate",
"(",
"peerURLs",
":",
"[",
"peer_url",
"]",
")",
",",
":headers",
"=>",
"{",
"'Content-Type'",
"=>",
"'application/json'",
"}",
")",
"end"
] | Add new peer membership
@param [Excon::Connection] etcd HTTP members API connection
@param [String] The peer URL of the new peer to be added to the cluster | [
"Add",
"new",
"peer",
"membership"
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/launchers/etcd.rb#L247-L251 | train |
kontena/kontena | agent/lib/kontena/observable.rb | Kontena.Observable.update | def update(value)
raise RuntimeError, "Observable crashed: #{@value}" if crashed?
raise ArgumentError, "Update with nil value" if value.nil?
debug { "update: #{value}" }
set_and_notify(value)
end | ruby | def update(value)
raise RuntimeError, "Observable crashed: #{@value}" if crashed?
raise ArgumentError, "Update with nil value" if value.nil?
debug { "update: #{value}" }
set_and_notify(value)
end | [
"def",
"update",
"(",
"value",
")",
"raise",
"RuntimeError",
",",
"\"Observable crashed: #{@value}\"",
"if",
"crashed?",
"raise",
"ArgumentError",
",",
"\"Update with nil value\"",
"if",
"value",
".",
"nil?",
"debug",
"{",
"\"update: #{value}\"",
"}",
"set_and_notify",
"(",
"value",
")",
"end"
] | The Observable has a value. Propagate it to any observers.
This will notify any Observers, causing them to yield/return if ready.
The value must be immutable and threadsafe: it must remain valid for use by other threads
both after this update, and after any other future updates. Do not send a mutable object
that gets invalidated in between updates.
TODO: automatically freeze the value?
@param value [Object]
@raise [RuntimeError] Observable crashed
@raise [ArgumentError] Update with nil value | [
"The",
"Observable",
"has",
"a",
"value",
".",
"Propagate",
"it",
"to",
"any",
"observers",
"."
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/observable.rb#L118-L125 | train |
kontena/kontena | agent/lib/kontena/workers/volumes/volume_manager.rb | Kontena::Workers::Volumes.VolumeManager.volume_exist? | def volume_exist?(volume_name, driver)
begin
debug "volume #{volume_name} exists"
volume = Docker::Volume.get(volume_name)
if volume && volume.info['Driver'] == driver
return true
elsif volume && volume.info['Driver'] != driver
raise DriverMismatchError.new("Volume driver not as expected. Expected #{driver}, existing volume has #{volume.info['Driver']}")
end
rescue Docker::Error::NotFoundError
debug "volume #{volume_name} does NOT exist"
false
rescue => error
abort error
end
end | ruby | def volume_exist?(volume_name, driver)
begin
debug "volume #{volume_name} exists"
volume = Docker::Volume.get(volume_name)
if volume && volume.info['Driver'] == driver
return true
elsif volume && volume.info['Driver'] != driver
raise DriverMismatchError.new("Volume driver not as expected. Expected #{driver}, existing volume has #{volume.info['Driver']}")
end
rescue Docker::Error::NotFoundError
debug "volume #{volume_name} does NOT exist"
false
rescue => error
abort error
end
end | [
"def",
"volume_exist?",
"(",
"volume_name",
",",
"driver",
")",
"begin",
"debug",
"\"volume #{volume_name} exists\"",
"volume",
"=",
"Docker",
"::",
"Volume",
".",
"get",
"(",
"volume_name",
")",
"if",
"volume",
"&&",
"volume",
".",
"info",
"[",
"'Driver'",
"]",
"==",
"driver",
"return",
"true",
"elsif",
"volume",
"&&",
"volume",
".",
"info",
"[",
"'Driver'",
"]",
"!=",
"driver",
"raise",
"DriverMismatchError",
".",
"new",
"(",
"\"Volume driver not as expected. Expected #{driver}, existing volume has #{volume.info['Driver']}\"",
")",
"end",
"rescue",
"Docker",
"::",
"Error",
"::",
"NotFoundError",
"debug",
"\"volume #{volume_name} does NOT exist\"",
"false",
"rescue",
"=>",
"error",
"abort",
"error",
"end",
"end"
] | Checks if given volume exists with the expected driver
@param [String] name of the volume
@param [String] driver to expect on the volume if already existing
@raise [DriverMismatchError] If the volume is found but using a different driver than expected | [
"Checks",
"if",
"given",
"volume",
"exists",
"with",
"the",
"expected",
"driver"
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/workers/volumes/volume_manager.rb#L106-L121 | train |
kontena/kontena | agent/lib/kontena/workers/service_pod_worker.rb | Kontena::Workers.ServicePodWorker.on_container_die | def on_container_die(exit_code: )
cancel_restart_timers
return unless @service_pod.running?
# backoff restarts
backoff = @restarts ** 2
backoff = max_restart_backoff if backoff > max_restart_backoff
info "#{@service_pod} exited with code #{exit_code}, restarting (delay: #{backoff}s)"
log_service_pod_event("service:instance_crash",
"service #{@service_pod} instance exited with code #{exit_code}, restarting (delay: #{backoff}s)",
Logger::WARN
)
ts = Time.now.utc
@restarts += 1
@restart_backoff_timer = after(backoff) {
debug "restart triggered (from #{ts})"
apply
}
end | ruby | def on_container_die(exit_code: )
cancel_restart_timers
return unless @service_pod.running?
# backoff restarts
backoff = @restarts ** 2
backoff = max_restart_backoff if backoff > max_restart_backoff
info "#{@service_pod} exited with code #{exit_code}, restarting (delay: #{backoff}s)"
log_service_pod_event("service:instance_crash",
"service #{@service_pod} instance exited with code #{exit_code}, restarting (delay: #{backoff}s)",
Logger::WARN
)
ts = Time.now.utc
@restarts += 1
@restart_backoff_timer = after(backoff) {
debug "restart triggered (from #{ts})"
apply
}
end | [
"def",
"on_container_die",
"(",
"exit_code",
":",
")",
"cancel_restart_timers",
"return",
"unless",
"@service_pod",
".",
"running?",
"# backoff restarts",
"backoff",
"=",
"@restarts",
"**",
"2",
"backoff",
"=",
"max_restart_backoff",
"if",
"backoff",
">",
"max_restart_backoff",
"info",
"\"#{@service_pod} exited with code #{exit_code}, restarting (delay: #{backoff}s)\"",
"log_service_pod_event",
"(",
"\"service:instance_crash\"",
",",
"\"service #{@service_pod} instance exited with code #{exit_code}, restarting (delay: #{backoff}s)\"",
",",
"Logger",
"::",
"WARN",
")",
"ts",
"=",
"Time",
".",
"now",
".",
"utc",
"@restarts",
"+=",
"1",
"@restart_backoff_timer",
"=",
"after",
"(",
"backoff",
")",
"{",
"debug",
"\"restart triggered (from #{ts})\"",
"apply",
"}",
"end"
] | Handles events when container has died | [
"Handles",
"events",
"when",
"container",
"has",
"died"
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/workers/service_pod_worker.rb#L103-L123 | train |
kontena/kontena | agent/lib/kontena/workers/service_pod_worker.rb | Kontena::Workers.ServicePodWorker.restart | def restart(at = Time.now, container_id: nil, started_at: nil)
if container_id && @container.id != container_id
debug "stale #{@service_pod} restart for container id=#{container_id}"
return
end
if started_at && @container.started_at != started_at
debug "stale #{@service_pod} restart for container started_at=#{started_at}"
return
end
debug "mark #{@service_pod} for restart at #{at}"
@restarting_at = at
apply
end | ruby | def restart(at = Time.now, container_id: nil, started_at: nil)
if container_id && @container.id != container_id
debug "stale #{@service_pod} restart for container id=#{container_id}"
return
end
if started_at && @container.started_at != started_at
debug "stale #{@service_pod} restart for container started_at=#{started_at}"
return
end
debug "mark #{@service_pod} for restart at #{at}"
@restarting_at = at
apply
end | [
"def",
"restart",
"(",
"at",
"=",
"Time",
".",
"now",
",",
"container_id",
":",
"nil",
",",
"started_at",
":",
"nil",
")",
"if",
"container_id",
"&&",
"@container",
".",
"id",
"!=",
"container_id",
"debug",
"\"stale #{@service_pod} restart for container id=#{container_id}\"",
"return",
"end",
"if",
"started_at",
"&&",
"@container",
".",
"started_at",
"!=",
"started_at",
"debug",
"\"stale #{@service_pod} restart for container started_at=#{started_at}\"",
"return",
"end",
"debug",
"\"mark #{@service_pod} for restart at #{at}\"",
"@restarting_at",
"=",
"at",
"apply",
"end"
] | User requested service restart | [
"User",
"requested",
"service",
"restart"
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/workers/service_pod_worker.rb#L141-L154 | train |
kontena/kontena | agent/lib/kontena/workers/service_pod_worker.rb | Kontena::Workers.ServicePodWorker.check_starting! | def check_starting!(service_pod, container)
raise "service stopped" if !@service_pod.running?
raise "service redeployed" if @service_pod.deploy_rev != service_pod.deploy_rev
raise "container recreated" if @container.id != container.id
raise "container restarted" if @container.started_at != container.started_at
end | ruby | def check_starting!(service_pod, container)
raise "service stopped" if !@service_pod.running?
raise "service redeployed" if @service_pod.deploy_rev != service_pod.deploy_rev
raise "container recreated" if @container.id != container.id
raise "container restarted" if @container.started_at != container.started_at
end | [
"def",
"check_starting!",
"(",
"service_pod",
",",
"container",
")",
"raise",
"\"service stopped\"",
"if",
"!",
"@service_pod",
".",
"running?",
"raise",
"\"service redeployed\"",
"if",
"@service_pod",
".",
"deploy_rev",
"!=",
"service_pod",
".",
"deploy_rev",
"raise",
"\"container recreated\"",
"if",
"@container",
".",
"id",
"!=",
"container",
".",
"id",
"raise",
"\"container restarted\"",
"if",
"@container",
".",
"started_at",
"!=",
"container",
".",
"started_at",
"end"
] | Check that the given container is still running for the given service pod revision.
@raise [RuntimeError] service stopped
@raise [RuntimeError] service redeployed
@raise [RuntimeError] container recreated
@raise [RuntimeError] container restarted | [
"Check",
"that",
"the",
"given",
"container",
"is",
"still",
"running",
"for",
"the",
"given",
"service",
"pod",
"revision",
"."
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/workers/service_pod_worker.rb#L208-L213 | train |
kontena/kontena | server/app/mutations/grid_services/helpers.rb | GridServices.Helpers.document_changes | def document_changes(document)
(document.changed + document._children.select{|child| child.changed? }.map { |child|
"#{child.metadata_name.to_s}{#{child.changed.join(", ")}}"
}).join(", ")
end | ruby | def document_changes(document)
(document.changed + document._children.select{|child| child.changed? }.map { |child|
"#{child.metadata_name.to_s}{#{child.changed.join(", ")}}"
}).join(", ")
end | [
"def",
"document_changes",
"(",
"document",
")",
"(",
"document",
".",
"changed",
"+",
"document",
".",
"_children",
".",
"select",
"{",
"|",
"child",
"|",
"child",
".",
"changed?",
"}",
".",
"map",
"{",
"|",
"child",
"|",
"\"#{child.metadata_name.to_s}{#{child.changed.join(\", \")}}\"",
"}",
")",
".",
"join",
"(",
"\", \"",
")",
"end"
] | List changed fields of model
@param document [Mongoid::Document]
@return [String] field, embedded{field} | [
"List",
"changed",
"fields",
"of",
"model"
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/server/app/mutations/grid_services/helpers.rb#L8-L12 | train |
kontena/kontena | server/app/mutations/grid_services/helpers.rb | GridServices.Helpers.save_grid_service | def save_grid_service(grid_service)
if grid_service.save
return grid_service
else
grid_service.errors.each do |key, message|
add_error(key, :invalid, message)
end
return nil
end
end | ruby | def save_grid_service(grid_service)
if grid_service.save
return grid_service
else
grid_service.errors.each do |key, message|
add_error(key, :invalid, message)
end
return nil
end
end | [
"def",
"save_grid_service",
"(",
"grid_service",
")",
"if",
"grid_service",
".",
"save",
"return",
"grid_service",
"else",
"grid_service",
".",
"errors",
".",
"each",
"do",
"|",
"key",
",",
"message",
"|",
"add_error",
"(",
"key",
",",
":invalid",
",",
"message",
")",
"end",
"return",
"nil",
"end",
"end"
] | Adds errors if save fails
@param grid_service [GridService]
@return [GridService] nil if error | [
"Adds",
"errors",
"if",
"save",
"fails"
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/server/app/mutations/grid_services/helpers.rb#L18-L27 | train |
kontena/kontena | server/app/mutations/grid_services/helpers.rb | GridServices.Helpers.update_grid_service | def update_grid_service(grid_service, force: false)
if grid_service.changed? || force
grid_service.revision += 1
info "updating service #{grid_service.to_path} revision #{grid_service.revision} with changes: #{document_changes(grid_service)}"
else
debug "not updating service #{grid_service.to_path} revision #{grid_service.revision} without changes"
end
save_grid_service(grid_service)
end | ruby | def update_grid_service(grid_service, force: false)
if grid_service.changed? || force
grid_service.revision += 1
info "updating service #{grid_service.to_path} revision #{grid_service.revision} with changes: #{document_changes(grid_service)}"
else
debug "not updating service #{grid_service.to_path} revision #{grid_service.revision} without changes"
end
save_grid_service(grid_service)
end | [
"def",
"update_grid_service",
"(",
"grid_service",
",",
"force",
":",
"false",
")",
"if",
"grid_service",
".",
"changed?",
"||",
"force",
"grid_service",
".",
"revision",
"+=",
"1",
"info",
"\"updating service #{grid_service.to_path} revision #{grid_service.revision} with changes: #{document_changes(grid_service)}\"",
"else",
"debug",
"\"not updating service #{grid_service.to_path} revision #{grid_service.revision} without changes\"",
"end",
"save_grid_service",
"(",
"grid_service",
")",
"end"
] | Bump grid_service.revision if changed or force, and save
Adds errors if save fails
@param grid_service [GridService]
@param force [Boolean] force-update revision
@return [GridService] nil if error | [
"Bump",
"grid_service",
".",
"revision",
"if",
"changed",
"or",
"force",
"and",
"save",
"Adds",
"errors",
"if",
"save",
"fails"
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/server/app/mutations/grid_services/helpers.rb#L35-L44 | train |
kontena/kontena | agent/lib/kontena/observer.rb | Kontena.Observer.error | def error
@values.each_pair{|observable, value|
return Error.new(observable, value) if Exception === value
}
return nil
end | ruby | def error
@values.each_pair{|observable, value|
return Error.new(observable, value) if Exception === value
}
return nil
end | [
"def",
"error",
"@values",
".",
"each_pair",
"{",
"|",
"observable",
",",
"value",
"|",
"return",
"Error",
".",
"new",
"(",
"observable",
",",
"value",
")",
"if",
"Exception",
"===",
"value",
"}",
"return",
"nil",
"end"
] | Return Error for first crashed observable.
Should only be used if error?
@return [Exception, nil] | [
"Return",
"Error",
"for",
"first",
"crashed",
"observable",
"."
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/observer.rb#L290-L295 | train |
kontena/kontena | agent/lib/kontena/observer.rb | Kontena.Observer.each | def each(timeout: nil)
@deadline = Time.now + timeout if timeout
while true
# prevent any intervening messages from being processed and discarded before we're back in Celluloid.receive()
Celluloid.exclusive {
if error?
debug { "raise: #{self.describe_observables}" }
raise self.error
elsif ready?
yield *self.values
@deadline = Time.now + timeout if timeout
end
}
# must be atomic!
debug { "wait: #{self.describe_observables}" }
update(receive())
end
end | ruby | def each(timeout: nil)
@deadline = Time.now + timeout if timeout
while true
# prevent any intervening messages from being processed and discarded before we're back in Celluloid.receive()
Celluloid.exclusive {
if error?
debug { "raise: #{self.describe_observables}" }
raise self.error
elsif ready?
yield *self.values
@deadline = Time.now + timeout if timeout
end
}
# must be atomic!
debug { "wait: #{self.describe_observables}" }
update(receive())
end
end | [
"def",
"each",
"(",
"timeout",
":",
"nil",
")",
"@deadline",
"=",
"Time",
".",
"now",
"+",
"timeout",
"if",
"timeout",
"while",
"true",
"# prevent any intervening messages from being processed and discarded before we're back in Celluloid.receive()",
"Celluloid",
".",
"exclusive",
"{",
"if",
"error?",
"debug",
"{",
"\"raise: #{self.describe_observables}\"",
"}",
"raise",
"self",
".",
"error",
"elsif",
"ready?",
"yield",
"self",
".",
"values",
"@deadline",
"=",
"Time",
".",
"now",
"+",
"timeout",
"if",
"timeout",
"end",
"}",
"# must be atomic!",
"debug",
"{",
"\"wait: #{self.describe_observables}\"",
"}",
"update",
"(",
"receive",
"(",
")",
")",
"end",
"end"
] | Yield each set of ready? observed values while alive, or raise on error?
The yield is exclusive, because suspending the observing task would mean that
any observable messages would get discarded.
@param timeout [Float] timeout between each yield | [
"Yield",
"each",
"set",
"of",
"ready?",
"observed",
"values",
"while",
"alive",
"or",
"raise",
"on",
"error?"
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/observer.rb#L303-L325 | train |
kontena/kontena | server/app/mutations/grid_services/common.rb | GridServices.Common.validate_secrets | def validate_secrets
validate_each :secrets do |s|
secret = self.grid.grid_secrets.find_by(name: s[:secret])
unless secret
[:not_found, "Secret #{s[:secret]} does not exist"]
else
nil
end
end
end | ruby | def validate_secrets
validate_each :secrets do |s|
secret = self.grid.grid_secrets.find_by(name: s[:secret])
unless secret
[:not_found, "Secret #{s[:secret]} does not exist"]
else
nil
end
end
end | [
"def",
"validate_secrets",
"validate_each",
":secrets",
"do",
"|",
"s",
"|",
"secret",
"=",
"self",
".",
"grid",
".",
"grid_secrets",
".",
"find_by",
"(",
"name",
":",
"s",
"[",
":secret",
"]",
")",
"unless",
"secret",
"[",
":not_found",
",",
"\"Secret #{s[:secret]} does not exist\"",
"]",
"else",
"nil",
"end",
"end",
"end"
] | Validates that the defined secrets exist | [
"Validates",
"that",
"the",
"defined",
"secrets",
"exist"
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/server/app/mutations/grid_services/common.rb#L173-L182 | train |
kontena/kontena | server/app/mutations/grid_services/common.rb | GridServices.Common.validate_certificates | def validate_certificates
validate_each :certificates do |c|
cert = self.grid.certificates.find_by(subject: c[:subject])
unless cert
[:not_found, "Certificate #{c[:subject]} does not exist"]
else
nil
end
end
end | ruby | def validate_certificates
validate_each :certificates do |c|
cert = self.grid.certificates.find_by(subject: c[:subject])
unless cert
[:not_found, "Certificate #{c[:subject]} does not exist"]
else
nil
end
end
end | [
"def",
"validate_certificates",
"validate_each",
":certificates",
"do",
"|",
"c",
"|",
"cert",
"=",
"self",
".",
"grid",
".",
"certificates",
".",
"find_by",
"(",
"subject",
":",
"c",
"[",
":subject",
"]",
")",
"unless",
"cert",
"[",
":not_found",
",",
"\"Certificate #{c[:subject]} does not exist\"",
"]",
"else",
"nil",
"end",
"end",
"end"
] | Validates that the defined certificates exist | [
"Validates",
"that",
"the",
"defined",
"certificates",
"exist"
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/server/app/mutations/grid_services/common.rb#L185-L194 | train |
kontena/kontena | server/app/services/docker/streaming_executor.rb | Docker.StreamingExecutor.start | def start(ws)
@ws = ws
@ws.on(:message) do |event|
on_websocket_message(event.data)
end
@ws.on(:error) do |exc|
warn exc
end
@ws.on(:close) do |event|
on_websocket_close(event.code, event.reason)
end
started!
end | ruby | def start(ws)
@ws = ws
@ws.on(:message) do |event|
on_websocket_message(event.data)
end
@ws.on(:error) do |exc|
warn exc
end
@ws.on(:close) do |event|
on_websocket_close(event.code, event.reason)
end
started!
end | [
"def",
"start",
"(",
"ws",
")",
"@ws",
"=",
"ws",
"@ws",
".",
"on",
"(",
":message",
")",
"do",
"|",
"event",
"|",
"on_websocket_message",
"(",
"event",
".",
"data",
")",
"end",
"@ws",
".",
"on",
"(",
":error",
")",
"do",
"|",
"exc",
"|",
"warn",
"exc",
"end",
"@ws",
".",
"on",
"(",
":close",
")",
"do",
"|",
"event",
"|",
"on_websocket_close",
"(",
"event",
".",
"code",
",",
"event",
".",
"reason",
")",
"end",
"started!",
"end"
] | Does not raise.
@param ws [Faye::Websocket] | [
"Does",
"not",
"raise",
"."
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/server/app/services/docker/streaming_executor.rb#L137-L153 | train |
kontena/kontena | cli/lib/kontena/cli/services/update_command.rb | Kontena::Cli::Services.UpdateCommand.parse_service_data_from_options | def parse_service_data_from_options
data = {}
data[:strategy] = deploy_strategy if deploy_strategy
data[:ports] = parse_ports(ports_list) unless ports_list.empty?
data[:links] = parse_links(link_list) unless link_list.empty?
data[:memory] = parse_memory(memory) if memory
data[:memory_swap] = parse_memory(memory_swap) if memory_swap
data[:shm_size] = parse_memory(shm_size) if shm_size
data[:cpus] = cpus if cpus
data[:cpu_shares] = cpu_shares if cpu_shares
data[:affinity] = affinity_list unless affinity_list.empty?
data[:env] = env_list unless env_list.empty?
data[:secrets] = parse_secrets(secret_list) unless secret_list.empty?
data[:container_count] = instances if instances
data[:cmd] = Shellwords.split(cmd) if cmd
data[:user] = user if user
data[:image] = parse_image(image) if image
data[:privileged] = privileged?
data[:cap_add] = cap_add_list if cap_add_list
data[:cap_drop] = cap_drop_list if cap_drop_list
data[:net] = net if net
data[:log_driver] = log_driver if log_driver
data[:log_opts] = parse_log_opts(log_opt_list) if log_opt_list
deploy_opts = parse_deploy_opts
data[:deploy_opts] = deploy_opts unless deploy_opts.empty?
health_check = parse_health_check
data[:health_check] = health_check unless health_check.empty?
data[:pid] = pid if pid
data[:stop_signal] = stop_signal if stop_signal
data[:stop_grace_period] = stop_timeout if stop_timeout
data
end | ruby | def parse_service_data_from_options
data = {}
data[:strategy] = deploy_strategy if deploy_strategy
data[:ports] = parse_ports(ports_list) unless ports_list.empty?
data[:links] = parse_links(link_list) unless link_list.empty?
data[:memory] = parse_memory(memory) if memory
data[:memory_swap] = parse_memory(memory_swap) if memory_swap
data[:shm_size] = parse_memory(shm_size) if shm_size
data[:cpus] = cpus if cpus
data[:cpu_shares] = cpu_shares if cpu_shares
data[:affinity] = affinity_list unless affinity_list.empty?
data[:env] = env_list unless env_list.empty?
data[:secrets] = parse_secrets(secret_list) unless secret_list.empty?
data[:container_count] = instances if instances
data[:cmd] = Shellwords.split(cmd) if cmd
data[:user] = user if user
data[:image] = parse_image(image) if image
data[:privileged] = privileged?
data[:cap_add] = cap_add_list if cap_add_list
data[:cap_drop] = cap_drop_list if cap_drop_list
data[:net] = net if net
data[:log_driver] = log_driver if log_driver
data[:log_opts] = parse_log_opts(log_opt_list) if log_opt_list
deploy_opts = parse_deploy_opts
data[:deploy_opts] = deploy_opts unless deploy_opts.empty?
health_check = parse_health_check
data[:health_check] = health_check unless health_check.empty?
data[:pid] = pid if pid
data[:stop_signal] = stop_signal if stop_signal
data[:stop_grace_period] = stop_timeout if stop_timeout
data
end | [
"def",
"parse_service_data_from_options",
"data",
"=",
"{",
"}",
"data",
"[",
":strategy",
"]",
"=",
"deploy_strategy",
"if",
"deploy_strategy",
"data",
"[",
":ports",
"]",
"=",
"parse_ports",
"(",
"ports_list",
")",
"unless",
"ports_list",
".",
"empty?",
"data",
"[",
":links",
"]",
"=",
"parse_links",
"(",
"link_list",
")",
"unless",
"link_list",
".",
"empty?",
"data",
"[",
":memory",
"]",
"=",
"parse_memory",
"(",
"memory",
")",
"if",
"memory",
"data",
"[",
":memory_swap",
"]",
"=",
"parse_memory",
"(",
"memory_swap",
")",
"if",
"memory_swap",
"data",
"[",
":shm_size",
"]",
"=",
"parse_memory",
"(",
"shm_size",
")",
"if",
"shm_size",
"data",
"[",
":cpus",
"]",
"=",
"cpus",
"if",
"cpus",
"data",
"[",
":cpu_shares",
"]",
"=",
"cpu_shares",
"if",
"cpu_shares",
"data",
"[",
":affinity",
"]",
"=",
"affinity_list",
"unless",
"affinity_list",
".",
"empty?",
"data",
"[",
":env",
"]",
"=",
"env_list",
"unless",
"env_list",
".",
"empty?",
"data",
"[",
":secrets",
"]",
"=",
"parse_secrets",
"(",
"secret_list",
")",
"unless",
"secret_list",
".",
"empty?",
"data",
"[",
":container_count",
"]",
"=",
"instances",
"if",
"instances",
"data",
"[",
":cmd",
"]",
"=",
"Shellwords",
".",
"split",
"(",
"cmd",
")",
"if",
"cmd",
"data",
"[",
":user",
"]",
"=",
"user",
"if",
"user",
"data",
"[",
":image",
"]",
"=",
"parse_image",
"(",
"image",
")",
"if",
"image",
"data",
"[",
":privileged",
"]",
"=",
"privileged?",
"data",
"[",
":cap_add",
"]",
"=",
"cap_add_list",
"if",
"cap_add_list",
"data",
"[",
":cap_drop",
"]",
"=",
"cap_drop_list",
"if",
"cap_drop_list",
"data",
"[",
":net",
"]",
"=",
"net",
"if",
"net",
"data",
"[",
":log_driver",
"]",
"=",
"log_driver",
"if",
"log_driver",
"data",
"[",
":log_opts",
"]",
"=",
"parse_log_opts",
"(",
"log_opt_list",
")",
"if",
"log_opt_list",
"deploy_opts",
"=",
"parse_deploy_opts",
"data",
"[",
":deploy_opts",
"]",
"=",
"deploy_opts",
"unless",
"deploy_opts",
".",
"empty?",
"health_check",
"=",
"parse_health_check",
"data",
"[",
":health_check",
"]",
"=",
"health_check",
"unless",
"health_check",
".",
"empty?",
"data",
"[",
":pid",
"]",
"=",
"pid",
"if",
"pid",
"data",
"[",
":stop_signal",
"]",
"=",
"stop_signal",
"if",
"stop_signal",
"data",
"[",
":stop_grace_period",
"]",
"=",
"stop_timeout",
"if",
"stop_timeout",
"data",
"end"
] | parse given options to hash
@return [Hash] | [
"parse",
"given",
"options",
"to",
"hash"
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/cli/services/update_command.rb#L61-L92 | train |
kontena/kontena | cli/lib/kontena/cli/helpers/time_helper.rb | Kontena::Cli::Helpers.TimeHelper.time_since | def time_since(time, terse: false)
return '' if time.nil? || time.empty?
dt = Time.now - Time.parse(time)
dt_s = dt.to_i
dt_m, dt_s = dt_s / 60, dt_s % 60
dt_h, dt_m = dt_m / 60, dt_m % 60
dt_d, dt_h = dt_h / 60, dt_h % 60
parts = []
parts << "%dd" % dt_d if dt_d > 0
parts << "%dh" % dt_h if dt_h > 0
parts << "%dm" % dt_m if dt_m > 0
parts << "%ds" % dt_s
if terse
return parts.first
else
return parts.join('')
end
end | ruby | def time_since(time, terse: false)
return '' if time.nil? || time.empty?
dt = Time.now - Time.parse(time)
dt_s = dt.to_i
dt_m, dt_s = dt_s / 60, dt_s % 60
dt_h, dt_m = dt_m / 60, dt_m % 60
dt_d, dt_h = dt_h / 60, dt_h % 60
parts = []
parts << "%dd" % dt_d if dt_d > 0
parts << "%dh" % dt_h if dt_h > 0
parts << "%dm" % dt_m if dt_m > 0
parts << "%ds" % dt_s
if terse
return parts.first
else
return parts.join('')
end
end | [
"def",
"time_since",
"(",
"time",
",",
"terse",
":",
"false",
")",
"return",
"''",
"if",
"time",
".",
"nil?",
"||",
"time",
".",
"empty?",
"dt",
"=",
"Time",
".",
"now",
"-",
"Time",
".",
"parse",
"(",
"time",
")",
"dt_s",
"=",
"dt",
".",
"to_i",
"dt_m",
",",
"dt_s",
"=",
"dt_s",
"/",
"60",
",",
"dt_s",
"%",
"60",
"dt_h",
",",
"dt_m",
"=",
"dt_m",
"/",
"60",
",",
"dt_m",
"%",
"60",
"dt_d",
",",
"dt_h",
"=",
"dt_h",
"/",
"60",
",",
"dt_h",
"%",
"60",
"parts",
"=",
"[",
"]",
"parts",
"<<",
"\"%dd\"",
"%",
"dt_d",
"if",
"dt_d",
">",
"0",
"parts",
"<<",
"\"%dh\"",
"%",
"dt_h",
"if",
"dt_h",
">",
"0",
"parts",
"<<",
"\"%dm\"",
"%",
"dt_m",
"if",
"dt_m",
">",
"0",
"parts",
"<<",
"\"%ds\"",
"%",
"dt_s",
"if",
"terse",
"return",
"parts",
".",
"first",
"else",
"return",
"parts",
".",
"join",
"(",
"''",
")",
"end",
"end"
] | Return an approximation of how long ago the given time was.
@param time [String]
@param terse [Boolean] very terse output (2-3 chars wide) | [
"Return",
"an",
"approximation",
"of",
"how",
"long",
"ago",
"the",
"given",
"time",
"was",
"."
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/cli/helpers/time_helper.rb#L6-L27 | train |
kontena/kontena | agent/lib/kontena/websocket_client.rb | Kontena.WebsocketClient.connect! | def connect!
info "connecting to master at #{@api_uri}"
headers = {
'Kontena-Node-Id' => @node_id.to_s,
'Kontena-Node-Name' => @node_name,
'Kontena-Version' => Kontena::Agent::VERSION,
'Kontena-Node-Labels' => @node_labels.join(','),
'Kontena-Connected-At' => Time.now.utc.strftime(STRFTIME),
}
if @node_token
headers['Kontena-Node-Token'] = @node_token.to_s
elsif @grid_token
headers['Kontena-Grid-Token'] = @grid_token.to_s
else
fail "Missing grid, node token"
end
@ws = Kontena::Websocket::Client.new(@api_uri,
headers: headers,
ssl_params: @ssl_params,
ssl_hostname: @ssl_hostname,
connect_timeout: CONNECT_TIMEOUT,
open_timeout: OPEN_TIMEOUT,
ping_interval: PING_INTERVAL,
ping_timeout: PING_TIMEOUT,
close_timeout: CLOSE_TIMEOUT,
)
async.connect_client @ws
publish('websocket:connect', nil)
rescue => exc
error exc
reconnect!
end | ruby | def connect!
info "connecting to master at #{@api_uri}"
headers = {
'Kontena-Node-Id' => @node_id.to_s,
'Kontena-Node-Name' => @node_name,
'Kontena-Version' => Kontena::Agent::VERSION,
'Kontena-Node-Labels' => @node_labels.join(','),
'Kontena-Connected-At' => Time.now.utc.strftime(STRFTIME),
}
if @node_token
headers['Kontena-Node-Token'] = @node_token.to_s
elsif @grid_token
headers['Kontena-Grid-Token'] = @grid_token.to_s
else
fail "Missing grid, node token"
end
@ws = Kontena::Websocket::Client.new(@api_uri,
headers: headers,
ssl_params: @ssl_params,
ssl_hostname: @ssl_hostname,
connect_timeout: CONNECT_TIMEOUT,
open_timeout: OPEN_TIMEOUT,
ping_interval: PING_INTERVAL,
ping_timeout: PING_TIMEOUT,
close_timeout: CLOSE_TIMEOUT,
)
async.connect_client @ws
publish('websocket:connect', nil)
rescue => exc
error exc
reconnect!
end | [
"def",
"connect!",
"info",
"\"connecting to master at #{@api_uri}\"",
"headers",
"=",
"{",
"'Kontena-Node-Id'",
"=>",
"@node_id",
".",
"to_s",
",",
"'Kontena-Node-Name'",
"=>",
"@node_name",
",",
"'Kontena-Version'",
"=>",
"Kontena",
"::",
"Agent",
"::",
"VERSION",
",",
"'Kontena-Node-Labels'",
"=>",
"@node_labels",
".",
"join",
"(",
"','",
")",
",",
"'Kontena-Connected-At'",
"=>",
"Time",
".",
"now",
".",
"utc",
".",
"strftime",
"(",
"STRFTIME",
")",
",",
"}",
"if",
"@node_token",
"headers",
"[",
"'Kontena-Node-Token'",
"]",
"=",
"@node_token",
".",
"to_s",
"elsif",
"@grid_token",
"headers",
"[",
"'Kontena-Grid-Token'",
"]",
"=",
"@grid_token",
".",
"to_s",
"else",
"fail",
"\"Missing grid, node token\"",
"end",
"@ws",
"=",
"Kontena",
"::",
"Websocket",
"::",
"Client",
".",
"new",
"(",
"@api_uri",
",",
"headers",
":",
"headers",
",",
"ssl_params",
":",
"@ssl_params",
",",
"ssl_hostname",
":",
"@ssl_hostname",
",",
"connect_timeout",
":",
"CONNECT_TIMEOUT",
",",
"open_timeout",
":",
"OPEN_TIMEOUT",
",",
"ping_interval",
":",
"PING_INTERVAL",
",",
"ping_timeout",
":",
"PING_TIMEOUT",
",",
"close_timeout",
":",
"CLOSE_TIMEOUT",
",",
")",
"async",
".",
"connect_client",
"@ws",
"publish",
"(",
"'websocket:connect'",
",",
"nil",
")",
"rescue",
"=>",
"exc",
"error",
"exc",
"reconnect!",
"end"
] | Connect to server, and start connect_client task
Calls reconnect! on errors | [
"Connect",
"to",
"server",
"and",
"start",
"connect_client",
"task"
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/websocket_client.rb#L113-L149 | train |
kontena/kontena | agent/lib/kontena/websocket_client.rb | Kontena.WebsocketClient.send_message | def send_message(msg)
ws.send(msg)
rescue => exc
warn exc
abort exc
end | ruby | def send_message(msg)
ws.send(msg)
rescue => exc
warn exc
abort exc
end | [
"def",
"send_message",
"(",
"msg",
")",
"ws",
".",
"send",
"(",
"msg",
")",
"rescue",
"=>",
"exc",
"warn",
"exc",
"abort",
"exc",
"end"
] | Called from RpcServer, does not crash the Actor on errors.
@param [String, Array] msg
@raise [RuntimeError] not connected | [
"Called",
"from",
"RpcServer",
"does",
"not",
"crash",
"the",
"Actor",
"on",
"errors",
"."
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/websocket_client.rb#L265-L270 | train |
kontena/kontena | agent/lib/kontena/websocket_client.rb | Kontena.WebsocketClient.on_error | def on_error(exc)
case exc
when Kontena::Websocket::SSLVerifyError
if exc.cert
error "unable to connect to SSL server with KONTENA_SSL_VERIFY=true: #{exc} (subject #{exc.subject}, issuer #{exc.issuer})"
else
error "unable to connect to SSL server with KONTENA_SSL_VERIFY=true: #{exc}"
end
when Kontena::Websocket::SSLConnectError
error "unable to connect to SSL server: #{exc}"
when Kontena::Websocket::ConnectError
error "unable to connect to server: #{exc}"
when Kontena::Websocket::ProtocolError
error "unexpected response from server, check url: #{exc}"
else
error "websocket error: #{exc}"
end
end | ruby | def on_error(exc)
case exc
when Kontena::Websocket::SSLVerifyError
if exc.cert
error "unable to connect to SSL server with KONTENA_SSL_VERIFY=true: #{exc} (subject #{exc.subject}, issuer #{exc.issuer})"
else
error "unable to connect to SSL server with KONTENA_SSL_VERIFY=true: #{exc}"
end
when Kontena::Websocket::SSLConnectError
error "unable to connect to SSL server: #{exc}"
when Kontena::Websocket::ConnectError
error "unable to connect to server: #{exc}"
when Kontena::Websocket::ProtocolError
error "unexpected response from server, check url: #{exc}"
else
error "websocket error: #{exc}"
end
end | [
"def",
"on_error",
"(",
"exc",
")",
"case",
"exc",
"when",
"Kontena",
"::",
"Websocket",
"::",
"SSLVerifyError",
"if",
"exc",
".",
"cert",
"error",
"\"unable to connect to SSL server with KONTENA_SSL_VERIFY=true: #{exc} (subject #{exc.subject}, issuer #{exc.issuer})\"",
"else",
"error",
"\"unable to connect to SSL server with KONTENA_SSL_VERIFY=true: #{exc}\"",
"end",
"when",
"Kontena",
"::",
"Websocket",
"::",
"SSLConnectError",
"error",
"\"unable to connect to SSL server: #{exc}\"",
"when",
"Kontena",
"::",
"Websocket",
"::",
"ConnectError",
"error",
"\"unable to connect to server: #{exc}\"",
"when",
"Kontena",
"::",
"Websocket",
"::",
"ProtocolError",
"error",
"\"unexpected response from server, check url: #{exc}\"",
"else",
"error",
"\"websocket error: #{exc}\"",
"end",
"end"
] | Websocket connection failed
@param exc [Kontena::Websocket::Error] | [
"Websocket",
"connection",
"failed"
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/websocket_client.rb#L314-L335 | train |
kontena/kontena | agent/lib/kontena/websocket_client.rb | Kontena.WebsocketClient.on_close | def on_close(code, reason)
debug "Server closed connection with code #{code}: #{reason}"
case code
when 4001
handle_invalid_token
when 4010
handle_invalid_version(reason)
when 4040, 4041
handle_invalid_connection(reason)
else
warn "connection closed with code #{code}: #{reason}"
end
end | ruby | def on_close(code, reason)
debug "Server closed connection with code #{code}: #{reason}"
case code
when 4001
handle_invalid_token
when 4010
handle_invalid_version(reason)
when 4040, 4041
handle_invalid_connection(reason)
else
warn "connection closed with code #{code}: #{reason}"
end
end | [
"def",
"on_close",
"(",
"code",
",",
"reason",
")",
"debug",
"\"Server closed connection with code #{code}: #{reason}\"",
"case",
"code",
"when",
"4001",
"handle_invalid_token",
"when",
"4010",
"handle_invalid_version",
"(",
"reason",
")",
"when",
"4040",
",",
"4041",
"handle_invalid_connection",
"(",
"reason",
")",
"else",
"warn",
"\"connection closed with code #{code}: #{reason}\"",
"end",
"end"
] | Server closed websocket connection
@param code [Integer]
@param reason [String] | [
"Server",
"closed",
"websocket",
"connection"
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/websocket_client.rb#L341-L354 | train |
kontena/kontena | cli/lib/kontena/cli/subcommand_loader.rb | Kontena::Cli.SubcommandLoader.symbolize_path | def symbolize_path(path)
path.gsub(/.*\/cli\//, '').split('/').map do |path_part|
path_part.split('_').map{ |e| e.capitalize }.join
end.map(&:to_sym)
end | ruby | def symbolize_path(path)
path.gsub(/.*\/cli\//, '').split('/').map do |path_part|
path_part.split('_').map{ |e| e.capitalize }.join
end.map(&:to_sym)
end | [
"def",
"symbolize_path",
"(",
"path",
")",
"path",
".",
"gsub",
"(",
"/",
"\\/",
"\\/",
"/",
",",
"''",
")",
".",
"split",
"(",
"'/'",
")",
".",
"map",
"do",
"|",
"path_part",
"|",
"path_part",
".",
"split",
"(",
"'_'",
")",
".",
"map",
"{",
"|",
"e",
"|",
"e",
".",
"capitalize",
"}",
".",
"join",
"end",
".",
"map",
"(",
":to_sym",
")",
"end"
] | Create a subcommand loader instance
@param [String] path path to command definition
Takes something like /foo/bar/cli/master/foo_coimmand and returns [:Master, :FooCommand]
@param path [String]
@return [Array<Symbol>] | [
"Create",
"a",
"subcommand",
"loader",
"instance"
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/cli/subcommand_loader.rb#L17-L21 | train |
kontena/kontena | cli/lib/kontena/client.rb | Kontena.Client.authentication_ok? | def authentication_ok?(token_verify_path)
return false unless token
return false unless token['access_token']
return false unless token_verify_path
final_path = token_verify_path.gsub(/\:access\_token/, token['access_token'])
debug { "Requesting user info from #{final_path}" }
request(path: final_path)
true
rescue => ex
error { "Authentication verification exception" }
error { ex }
false
end | ruby | def authentication_ok?(token_verify_path)
return false unless token
return false unless token['access_token']
return false unless token_verify_path
final_path = token_verify_path.gsub(/\:access\_token/, token['access_token'])
debug { "Requesting user info from #{final_path}" }
request(path: final_path)
true
rescue => ex
error { "Authentication verification exception" }
error { ex }
false
end | [
"def",
"authentication_ok?",
"(",
"token_verify_path",
")",
"return",
"false",
"unless",
"token",
"return",
"false",
"unless",
"token",
"[",
"'access_token'",
"]",
"return",
"false",
"unless",
"token_verify_path",
"final_path",
"=",
"token_verify_path",
".",
"gsub",
"(",
"/",
"\\:",
"\\_",
"/",
",",
"token",
"[",
"'access_token'",
"]",
")",
"debug",
"{",
"\"Requesting user info from #{final_path}\"",
"}",
"request",
"(",
"path",
":",
"final_path",
")",
"true",
"rescue",
"=>",
"ex",
"error",
"{",
"\"Authentication verification exception\"",
"}",
"error",
"{",
"ex",
"}",
"false",
"end"
] | Requests path supplied as argument and returns true if the request was a success.
For checking if the current authentication is valid.
@param [String] token_verify_path a path that requires authentication
@return [Boolean] | [
"Requests",
"path",
"supplied",
"as",
"argument",
"and",
"returns",
"true",
"if",
"the",
"request",
"was",
"a",
"success",
".",
"For",
"checking",
"if",
"the",
"current",
"authentication",
"is",
"valid",
"."
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/client.rb#L130-L143 | train |
kontena/kontena | cli/lib/kontena/client.rb | Kontena.Client.exchange_code | def exchange_code(code)
return nil unless token_account
return nil unless token_account['token_endpoint']
response = request(
http_method: token_account['token_method'].downcase.to_sym,
path: token_account['token_endpoint'],
headers: { CONTENT_TYPE => token_account['token_post_content_type'] },
body: {
'grant_type' => 'authorization_code',
'code' => code,
'client_id' => Kontena::Client::CLIENT_ID,
'client_secret' => Kontena::Client::CLIENT_SECRET
},
expects: [200,201],
auth: false
)
response['expires_at'] ||= in_to_at(response['expires_in'])
response
end | ruby | def exchange_code(code)
return nil unless token_account
return nil unless token_account['token_endpoint']
response = request(
http_method: token_account['token_method'].downcase.to_sym,
path: token_account['token_endpoint'],
headers: { CONTENT_TYPE => token_account['token_post_content_type'] },
body: {
'grant_type' => 'authorization_code',
'code' => code,
'client_id' => Kontena::Client::CLIENT_ID,
'client_secret' => Kontena::Client::CLIENT_SECRET
},
expects: [200,201],
auth: false
)
response['expires_at'] ||= in_to_at(response['expires_in'])
response
end | [
"def",
"exchange_code",
"(",
"code",
")",
"return",
"nil",
"unless",
"token_account",
"return",
"nil",
"unless",
"token_account",
"[",
"'token_endpoint'",
"]",
"response",
"=",
"request",
"(",
"http_method",
":",
"token_account",
"[",
"'token_method'",
"]",
".",
"downcase",
".",
"to_sym",
",",
"path",
":",
"token_account",
"[",
"'token_endpoint'",
"]",
",",
"headers",
":",
"{",
"CONTENT_TYPE",
"=>",
"token_account",
"[",
"'token_post_content_type'",
"]",
"}",
",",
"body",
":",
"{",
"'grant_type'",
"=>",
"'authorization_code'",
",",
"'code'",
"=>",
"code",
",",
"'client_id'",
"=>",
"Kontena",
"::",
"Client",
"::",
"CLIENT_ID",
",",
"'client_secret'",
"=>",
"Kontena",
"::",
"Client",
"::",
"CLIENT_SECRET",
"}",
",",
"expects",
":",
"[",
"200",
",",
"201",
"]",
",",
"auth",
":",
"false",
")",
"response",
"[",
"'expires_at'",
"]",
"||=",
"in_to_at",
"(",
"response",
"[",
"'expires_in'",
"]",
")",
"response",
"end"
] | Calls the code exchange endpoint in token's config to exchange an authorization_code
to a access_token | [
"Calls",
"the",
"code",
"exchange",
"endpoint",
"in",
"token",
"s",
"config",
"to",
"exchange",
"an",
"authorization_code",
"to",
"a",
"access_token"
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/client.rb#L147-L166 | train |
kontena/kontena | cli/lib/kontena/client.rb | Kontena.Client.get_stream | def get_stream(path, response_block, params = nil, headers = {}, auth = true)
request(path: path, query: params, headers: headers, response_block: response_block, auth: auth, gzip: false)
end | ruby | def get_stream(path, response_block, params = nil, headers = {}, auth = true)
request(path: path, query: params, headers: headers, response_block: response_block, auth: auth, gzip: false)
end | [
"def",
"get_stream",
"(",
"path",
",",
"response_block",
",",
"params",
"=",
"nil",
",",
"headers",
"=",
"{",
"}",
",",
"auth",
"=",
"true",
")",
"request",
"(",
"path",
":",
"path",
",",
"query",
":",
"params",
",",
"headers",
":",
"headers",
",",
"response_block",
":",
"response_block",
",",
"auth",
":",
"auth",
",",
"gzip",
":",
"false",
")",
"end"
] | Get stream request
@param [String] path
@param [Lambda] response_block
@param [Hash,NilClass] params
@param [Hash] headers | [
"Get",
"stream",
"request"
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/client.rb#L253-L255 | train |
kontena/kontena | cli/lib/kontena/client.rb | Kontena.Client.request | def request(http_method: :get, path:'/', body: nil, query: {}, headers: {}, response_block: nil, expects: [200, 201, 204], host: nil, port: nil, auth: true, gzip: true)
retried ||= false
if auth && token_expired?
raise Excon::Error::Unauthorized, "Token expired or not valid, you need to login again, use: kontena #{token_is_for_master? ? "master" : "cloud"} login"
end
request_headers = request_headers(headers, auth: auth, gzip: gzip)
if body.nil?
body_content = ''
request_headers.delete(CONTENT_TYPE)
else
body_content = encode_body(body, request_headers[CONTENT_TYPE])
request_headers.merge!('Content-Length' => body_content.bytesize)
end
uri = URI.parse(path)
host_options = {}
if uri.host
host_options[:host] = uri.host
host_options[:port] = uri.port
host_options[:scheme] = uri.scheme
path = uri.request_uri
else
host_options[:host] = host if host
host_options[:port] = port if port
end
request_options = {
method: http_method,
expects: Array(expects),
path: path_with_prefix(path),
headers: request_headers,
body: body_content,
query: query
}.merge(host_options)
request_options.merge!(response_block: response_block) if response_block
# Store the response into client.last_response
@last_response = http_client.request(request_options)
parse_response(@last_response)
rescue Excon::Error::Unauthorized
if token
debug { 'Server reports access token expired' }
if retried || !token || !token['refresh_token']
raise Kontena::Errors::StandardError.new(401, 'The access token has expired and needs to be refreshed')
end
retried = true
retry if refresh_token
end
raise Kontena::Errors::StandardError.new(401, 'Unauthorized')
rescue Excon::Error::HTTPStatus => error
if error.response.headers['Content-Encoding'] == 'gzip'
error.response.body = Zlib::GzipReader.new(StringIO.new(error.response.body)).read
end
debug { "Request #{error.request[:method].upcase} #{error.request[:path]}: #{error.response.status} #{error.response.reason_phrase}: #{error.response.body}" }
handle_error_response(error.response)
end | ruby | def request(http_method: :get, path:'/', body: nil, query: {}, headers: {}, response_block: nil, expects: [200, 201, 204], host: nil, port: nil, auth: true, gzip: true)
retried ||= false
if auth && token_expired?
raise Excon::Error::Unauthorized, "Token expired or not valid, you need to login again, use: kontena #{token_is_for_master? ? "master" : "cloud"} login"
end
request_headers = request_headers(headers, auth: auth, gzip: gzip)
if body.nil?
body_content = ''
request_headers.delete(CONTENT_TYPE)
else
body_content = encode_body(body, request_headers[CONTENT_TYPE])
request_headers.merge!('Content-Length' => body_content.bytesize)
end
uri = URI.parse(path)
host_options = {}
if uri.host
host_options[:host] = uri.host
host_options[:port] = uri.port
host_options[:scheme] = uri.scheme
path = uri.request_uri
else
host_options[:host] = host if host
host_options[:port] = port if port
end
request_options = {
method: http_method,
expects: Array(expects),
path: path_with_prefix(path),
headers: request_headers,
body: body_content,
query: query
}.merge(host_options)
request_options.merge!(response_block: response_block) if response_block
# Store the response into client.last_response
@last_response = http_client.request(request_options)
parse_response(@last_response)
rescue Excon::Error::Unauthorized
if token
debug { 'Server reports access token expired' }
if retried || !token || !token['refresh_token']
raise Kontena::Errors::StandardError.new(401, 'The access token has expired and needs to be refreshed')
end
retried = true
retry if refresh_token
end
raise Kontena::Errors::StandardError.new(401, 'Unauthorized')
rescue Excon::Error::HTTPStatus => error
if error.response.headers['Content-Encoding'] == 'gzip'
error.response.body = Zlib::GzipReader.new(StringIO.new(error.response.body)).read
end
debug { "Request #{error.request[:method].upcase} #{error.request[:path]}: #{error.response.status} #{error.response.reason_phrase}: #{error.response.body}" }
handle_error_response(error.response)
end | [
"def",
"request",
"(",
"http_method",
":",
":get",
",",
"path",
":",
"'/'",
",",
"body",
":",
"nil",
",",
"query",
":",
"{",
"}",
",",
"headers",
":",
"{",
"}",
",",
"response_block",
":",
"nil",
",",
"expects",
":",
"[",
"200",
",",
"201",
",",
"204",
"]",
",",
"host",
":",
"nil",
",",
"port",
":",
"nil",
",",
"auth",
":",
"true",
",",
"gzip",
":",
"true",
")",
"retried",
"||=",
"false",
"if",
"auth",
"&&",
"token_expired?",
"raise",
"Excon",
"::",
"Error",
"::",
"Unauthorized",
",",
"\"Token expired or not valid, you need to login again, use: kontena #{token_is_for_master? ? \"master\" : \"cloud\"} login\"",
"end",
"request_headers",
"=",
"request_headers",
"(",
"headers",
",",
"auth",
":",
"auth",
",",
"gzip",
":",
"gzip",
")",
"if",
"body",
".",
"nil?",
"body_content",
"=",
"''",
"request_headers",
".",
"delete",
"(",
"CONTENT_TYPE",
")",
"else",
"body_content",
"=",
"encode_body",
"(",
"body",
",",
"request_headers",
"[",
"CONTENT_TYPE",
"]",
")",
"request_headers",
".",
"merge!",
"(",
"'Content-Length'",
"=>",
"body_content",
".",
"bytesize",
")",
"end",
"uri",
"=",
"URI",
".",
"parse",
"(",
"path",
")",
"host_options",
"=",
"{",
"}",
"if",
"uri",
".",
"host",
"host_options",
"[",
":host",
"]",
"=",
"uri",
".",
"host",
"host_options",
"[",
":port",
"]",
"=",
"uri",
".",
"port",
"host_options",
"[",
":scheme",
"]",
"=",
"uri",
".",
"scheme",
"path",
"=",
"uri",
".",
"request_uri",
"else",
"host_options",
"[",
":host",
"]",
"=",
"host",
"if",
"host",
"host_options",
"[",
":port",
"]",
"=",
"port",
"if",
"port",
"end",
"request_options",
"=",
"{",
"method",
":",
"http_method",
",",
"expects",
":",
"Array",
"(",
"expects",
")",
",",
"path",
":",
"path_with_prefix",
"(",
"path",
")",
",",
"headers",
":",
"request_headers",
",",
"body",
":",
"body_content",
",",
"query",
":",
"query",
"}",
".",
"merge",
"(",
"host_options",
")",
"request_options",
".",
"merge!",
"(",
"response_block",
":",
"response_block",
")",
"if",
"response_block",
"# Store the response into client.last_response",
"@last_response",
"=",
"http_client",
".",
"request",
"(",
"request_options",
")",
"parse_response",
"(",
"@last_response",
")",
"rescue",
"Excon",
"::",
"Error",
"::",
"Unauthorized",
"if",
"token",
"debug",
"{",
"'Server reports access token expired'",
"}",
"if",
"retried",
"||",
"!",
"token",
"||",
"!",
"token",
"[",
"'refresh_token'",
"]",
"raise",
"Kontena",
"::",
"Errors",
"::",
"StandardError",
".",
"new",
"(",
"401",
",",
"'The access token has expired and needs to be refreshed'",
")",
"end",
"retried",
"=",
"true",
"retry",
"if",
"refresh_token",
"end",
"raise",
"Kontena",
"::",
"Errors",
"::",
"StandardError",
".",
"new",
"(",
"401",
",",
"'Unauthorized'",
")",
"rescue",
"Excon",
"::",
"Error",
"::",
"HTTPStatus",
"=>",
"error",
"if",
"error",
".",
"response",
".",
"headers",
"[",
"'Content-Encoding'",
"]",
"==",
"'gzip'",
"error",
".",
"response",
".",
"body",
"=",
"Zlib",
"::",
"GzipReader",
".",
"new",
"(",
"StringIO",
".",
"new",
"(",
"error",
".",
"response",
".",
"body",
")",
")",
".",
"read",
"end",
"debug",
"{",
"\"Request #{error.request[:method].upcase} #{error.request[:path]}: #{error.response.status} #{error.response.reason_phrase}: #{error.response.body}\"",
"}",
"handle_error_response",
"(",
"error",
".",
"response",
")",
"end"
] | Perform a HTTP request. Will try to refresh the access token and retry if it's
expired or if the server responds with HTTP 401.
Automatically parses a JSON response into a hash.
After the request has been performed, the response can be inspected using
client.last_response.
@param http_method [Symbol] :get, :post, etc
@param path [String] if it starts with / then prefix won't be used.
@param body [Hash, String] will be encoded using #encode_body
@param query [Hash] url query parameters
@param headers [Hash] extra headers for request.
@param response_block [Proc] for streaming requests, must respond to #call
@param expects [Array] raises unless response status code matches this list.
@param auth [Boolean] use token authentication default = true
@return [Hash, String] response parsed response object | [
"Perform",
"a",
"HTTP",
"request",
".",
"Will",
"try",
"to",
"refresh",
"the",
"access",
"token",
"and",
"retry",
"if",
"it",
"s",
"expired",
"or",
"if",
"the",
"server",
"responds",
"with",
"HTTP",
"401",
"."
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/client.rb#L285-L351 | train |
kontena/kontena | cli/lib/kontena/client.rb | Kontena.Client.token_account | def token_account
return {} unless token
if token.respond_to?(:account)
token.account
elsif token.kind_of?(Hash) && token['account'].kind_of?(String)
config.find_account(token['account'])
else
{}
end
rescue => ex
error { "Access token refresh exception" }
error { ex }
false
end | ruby | def token_account
return {} unless token
if token.respond_to?(:account)
token.account
elsif token.kind_of?(Hash) && token['account'].kind_of?(String)
config.find_account(token['account'])
else
{}
end
rescue => ex
error { "Access token refresh exception" }
error { ex }
false
end | [
"def",
"token_account",
"return",
"{",
"}",
"unless",
"token",
"if",
"token",
".",
"respond_to?",
"(",
":account",
")",
"token",
".",
"account",
"elsif",
"token",
".",
"kind_of?",
"(",
"Hash",
")",
"&&",
"token",
"[",
"'account'",
"]",
".",
"kind_of?",
"(",
"String",
")",
"config",
".",
"find_account",
"(",
"token",
"[",
"'account'",
"]",
")",
"else",
"{",
"}",
"end",
"rescue",
"=>",
"ex",
"error",
"{",
"\"Access token refresh exception\"",
"}",
"error",
"{",
"ex",
"}",
"false",
"end"
] | Accessor to token's account settings | [
"Accessor",
"to",
"token",
"s",
"account",
"settings"
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/client.rb#L366-L379 | train |
kontena/kontena | cli/lib/kontena/client.rb | Kontena.Client.refresh_token | def refresh_token
debug { "Performing token refresh" }
return false if token.nil?
return false if token['refresh_token'].nil?
uri = URI.parse(token_account['token_endpoint'])
endpoint_data = { path: uri.path }
endpoint_data[:host] = uri.host if uri.host
endpoint_data[:port] = uri.port if uri.port
debug { "Token refresh endpoint: #{endpoint_data.inspect}" }
return false unless endpoint_data[:path]
response = request(
{
http_method: token_account['token_method'].downcase.to_sym,
body: refresh_request_params,
headers: {
CONTENT_TYPE => token_account['token_post_content_type']
}.merge(
token_account['code_requires_basic_auth'] ? basic_auth_header : {}
),
expects: [200, 201, 400, 401, 403],
auth: false
}.merge(endpoint_data)
)
if response && response['access_token']
debug { "Got response to refresh request" }
token['access_token'] = response['access_token']
token['refresh_token'] = response['refresh_token']
token['expires_at'] = in_to_at(response['expires_in'])
token.config.write if token.respond_to?(:config)
true
else
debug { "Got null or bad response to refresh request: #{last_response.inspect}" }
false
end
rescue => ex
error { "Access token refresh exception" }
error { ex }
false
end | ruby | def refresh_token
debug { "Performing token refresh" }
return false if token.nil?
return false if token['refresh_token'].nil?
uri = URI.parse(token_account['token_endpoint'])
endpoint_data = { path: uri.path }
endpoint_data[:host] = uri.host if uri.host
endpoint_data[:port] = uri.port if uri.port
debug { "Token refresh endpoint: #{endpoint_data.inspect}" }
return false unless endpoint_data[:path]
response = request(
{
http_method: token_account['token_method'].downcase.to_sym,
body: refresh_request_params,
headers: {
CONTENT_TYPE => token_account['token_post_content_type']
}.merge(
token_account['code_requires_basic_auth'] ? basic_auth_header : {}
),
expects: [200, 201, 400, 401, 403],
auth: false
}.merge(endpoint_data)
)
if response && response['access_token']
debug { "Got response to refresh request" }
token['access_token'] = response['access_token']
token['refresh_token'] = response['refresh_token']
token['expires_at'] = in_to_at(response['expires_in'])
token.config.write if token.respond_to?(:config)
true
else
debug { "Got null or bad response to refresh request: #{last_response.inspect}" }
false
end
rescue => ex
error { "Access token refresh exception" }
error { ex }
false
end | [
"def",
"refresh_token",
"debug",
"{",
"\"Performing token refresh\"",
"}",
"return",
"false",
"if",
"token",
".",
"nil?",
"return",
"false",
"if",
"token",
"[",
"'refresh_token'",
"]",
".",
"nil?",
"uri",
"=",
"URI",
".",
"parse",
"(",
"token_account",
"[",
"'token_endpoint'",
"]",
")",
"endpoint_data",
"=",
"{",
"path",
":",
"uri",
".",
"path",
"}",
"endpoint_data",
"[",
":host",
"]",
"=",
"uri",
".",
"host",
"if",
"uri",
".",
"host",
"endpoint_data",
"[",
":port",
"]",
"=",
"uri",
".",
"port",
"if",
"uri",
".",
"port",
"debug",
"{",
"\"Token refresh endpoint: #{endpoint_data.inspect}\"",
"}",
"return",
"false",
"unless",
"endpoint_data",
"[",
":path",
"]",
"response",
"=",
"request",
"(",
"{",
"http_method",
":",
"token_account",
"[",
"'token_method'",
"]",
".",
"downcase",
".",
"to_sym",
",",
"body",
":",
"refresh_request_params",
",",
"headers",
":",
"{",
"CONTENT_TYPE",
"=>",
"token_account",
"[",
"'token_post_content_type'",
"]",
"}",
".",
"merge",
"(",
"token_account",
"[",
"'code_requires_basic_auth'",
"]",
"?",
"basic_auth_header",
":",
"{",
"}",
")",
",",
"expects",
":",
"[",
"200",
",",
"201",
",",
"400",
",",
"401",
",",
"403",
"]",
",",
"auth",
":",
"false",
"}",
".",
"merge",
"(",
"endpoint_data",
")",
")",
"if",
"response",
"&&",
"response",
"[",
"'access_token'",
"]",
"debug",
"{",
"\"Got response to refresh request\"",
"}",
"token",
"[",
"'access_token'",
"]",
"=",
"response",
"[",
"'access_token'",
"]",
"token",
"[",
"'refresh_token'",
"]",
"=",
"response",
"[",
"'refresh_token'",
"]",
"token",
"[",
"'expires_at'",
"]",
"=",
"in_to_at",
"(",
"response",
"[",
"'expires_in'",
"]",
")",
"token",
".",
"config",
".",
"write",
"if",
"token",
".",
"respond_to?",
"(",
":config",
")",
"true",
"else",
"debug",
"{",
"\"Got null or bad response to refresh request: #{last_response.inspect}\"",
"}",
"false",
"end",
"rescue",
"=>",
"ex",
"error",
"{",
"\"Access token refresh exception\"",
"}",
"error",
"{",
"ex",
"}",
"false",
"end"
] | Perform refresh token request to auth provider.
Updates the client's Token object and writes changes to
configuration.
@param [Boolean] use_basic_auth? When true, use basic auth authentication header
@return [Boolean] success? | [
"Perform",
"refresh",
"token",
"request",
"to",
"auth",
"provider",
".",
"Updates",
"the",
"client",
"s",
"Token",
"object",
"and",
"writes",
"changes",
"to",
"configuration",
"."
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/client.rb#L387-L429 | train |
kontena/kontena | cli/lib/kontena/client.rb | Kontena.Client.encode_body | def encode_body(body, content_type)
if content_type =~ JSON_REGEX # vnd.api+json should pass as json
dump_json(body)
elsif content_type == CONTENT_URLENCODED && body.kind_of?(Hash)
URI.encode_www_form(body)
else
body
end
end | ruby | def encode_body(body, content_type)
if content_type =~ JSON_REGEX # vnd.api+json should pass as json
dump_json(body)
elsif content_type == CONTENT_URLENCODED && body.kind_of?(Hash)
URI.encode_www_form(body)
else
body
end
end | [
"def",
"encode_body",
"(",
"body",
",",
"content_type",
")",
"if",
"content_type",
"=~",
"JSON_REGEX",
"# vnd.api+json should pass as json",
"dump_json",
"(",
"body",
")",
"elsif",
"content_type",
"==",
"CONTENT_URLENCODED",
"&&",
"body",
".",
"kind_of?",
"(",
"Hash",
")",
"URI",
".",
"encode_www_form",
"(",
"body",
")",
"else",
"body",
"end",
"end"
] | Encode body based on content type.
@param [Object] body
@param [String] content_type
@return [String] encoded_content | [
"Encode",
"body",
"based",
"on",
"content",
"type",
"."
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/client.rb#L470-L478 | train |
kontena/kontena | cli/lib/kontena/client.rb | Kontena.Client.in_to_at | def in_to_at(expires_in)
if expires_in.to_i < 1
0
else
Time.now.utc.to_i + expires_in.to_i
end
end | ruby | def in_to_at(expires_in)
if expires_in.to_i < 1
0
else
Time.now.utc.to_i + expires_in.to_i
end
end | [
"def",
"in_to_at",
"(",
"expires_in",
")",
"if",
"expires_in",
".",
"to_i",
"<",
"1",
"0",
"else",
"Time",
".",
"now",
".",
"utc",
".",
"to_i",
"+",
"expires_in",
".",
"to_i",
"end",
"end"
] | Convert expires_in into expires_at
@param [Fixnum] seconds_till_expiration
@return [Fixnum] expires_at_unix_timestamp | [
"Convert",
"expires_in",
"into",
"expires_at"
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/client.rb#L566-L572 | train |
kontena/kontena | agent/lib/kontena/rpc_client.rb | Kontena.RpcClient.request | def request(method, params, timeout: 30)
if !wait_until("websocket client is connected", timeout: timeout, threshold: 10.0, interval: 0.1) { connected? }
raise TimeoutError.new(500, 'WebsocketClient is not connected')
end
id = request_id
observable = @requests[id] = RequestObservable.new(method, id)
websocket_client.send_request(id, method, params)
begin
result, error = observe(observable, timeout: timeout)
rescue Timeout::Error => exc
raise TimeoutError.new(500, exc.message)
end
@requests.delete(id)
if error
raise Error.new(error['code'], error['message'])
else
return result
end
rescue => exc
warn exc
abort exc
end | ruby | def request(method, params, timeout: 30)
if !wait_until("websocket client is connected", timeout: timeout, threshold: 10.0, interval: 0.1) { connected? }
raise TimeoutError.new(500, 'WebsocketClient is not connected')
end
id = request_id
observable = @requests[id] = RequestObservable.new(method, id)
websocket_client.send_request(id, method, params)
begin
result, error = observe(observable, timeout: timeout)
rescue Timeout::Error => exc
raise TimeoutError.new(500, exc.message)
end
@requests.delete(id)
if error
raise Error.new(error['code'], error['message'])
else
return result
end
rescue => exc
warn exc
abort exc
end | [
"def",
"request",
"(",
"method",
",",
"params",
",",
"timeout",
":",
"30",
")",
"if",
"!",
"wait_until",
"(",
"\"websocket client is connected\"",
",",
"timeout",
":",
"timeout",
",",
"threshold",
":",
"10.0",
",",
"interval",
":",
"0.1",
")",
"{",
"connected?",
"}",
"raise",
"TimeoutError",
".",
"new",
"(",
"500",
",",
"'WebsocketClient is not connected'",
")",
"end",
"id",
"=",
"request_id",
"observable",
"=",
"@requests",
"[",
"id",
"]",
"=",
"RequestObservable",
".",
"new",
"(",
"method",
",",
"id",
")",
"websocket_client",
".",
"send_request",
"(",
"id",
",",
"method",
",",
"params",
")",
"begin",
"result",
",",
"error",
"=",
"observe",
"(",
"observable",
",",
"timeout",
":",
"timeout",
")",
"rescue",
"Timeout",
"::",
"Error",
"=>",
"exc",
"raise",
"TimeoutError",
".",
"new",
"(",
"500",
",",
"exc",
".",
"message",
")",
"end",
"@requests",
".",
"delete",
"(",
"id",
")",
"if",
"error",
"raise",
"Error",
".",
"new",
"(",
"error",
"[",
"'code'",
"]",
",",
"error",
"[",
"'message'",
"]",
")",
"else",
"return",
"result",
"end",
"rescue",
"=>",
"exc",
"warn",
"exc",
"abort",
"exc",
"end"
] | Aborts caller on errors.
@param [String] method
@param [Array] params
@param [Float] timeout seconds
@raise abort
@return [Object] | [
"Aborts",
"caller",
"on",
"errors",
"."
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/rpc_client.rb#L64-L90 | train |
kontena/kontena | server/app/services/agent/node_plugger.rb | Agent.NodePlugger.reject! | def reject!(connected_at, code, reason)
self.update_node!(connected_at,
connected: false,
updated: false,
websocket_connection: {
opened: false,
close_code: code,
close_reason: reason,
},
)
info "Rejected connection for node #{@node.to_path} at #{connected_at} with code #{code}: #{reason}"
rescue => exc
error exc
end | ruby | def reject!(connected_at, code, reason)
self.update_node!(connected_at,
connected: false,
updated: false,
websocket_connection: {
opened: false,
close_code: code,
close_reason: reason,
},
)
info "Rejected connection for node #{@node.to_path} at #{connected_at} with code #{code}: #{reason}"
rescue => exc
error exc
end | [
"def",
"reject!",
"(",
"connected_at",
",",
"code",
",",
"reason",
")",
"self",
".",
"update_node!",
"(",
"connected_at",
",",
"connected",
":",
"false",
",",
"updated",
":",
"false",
",",
"websocket_connection",
":",
"{",
"opened",
":",
"false",
",",
"close_code",
":",
"code",
",",
"close_reason",
":",
"reason",
",",
"}",
",",
")",
"info",
"\"Rejected connection for node #{@node.to_path} at #{connected_at} with code #{code}: #{reason}\"",
"rescue",
"=>",
"exc",
"error",
"exc",
"end"
] | Connection was rejected
@param [Time] connected_at
@param [Integer] code websocket close
@param [String] reason websocket close | [
"Connection",
"was",
"rejected"
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/server/app/services/agent/node_plugger.rb#L36-L49 | train |
kontena/kontena | server/app/mutations/stacks/sort_helper.rb | Stacks.SortHelper.sort_services | def sort_services(services)
# Map of service name to array of deep links, including links of linked services
service_links = {}
# Build hash of service name to shallow array of linked service names
# {service => [linked_service]}
services.each do |service|
service_links[service[:name]] = __links_for_service(service)
end
# Mutate each service's array to add a deep reference to each linked service's own array of linked services
# {service => [linked_service, [linked_service_links, [...]]]}
service_links.each do |service, links|
links.dup.each do |linked_service|
if linked_service_links = service_links[linked_service]
service_links[service] << linked_service_links
else
raise MissingLinkError.new(service, linked_service)
end
end
end
# Flatten the deep array references to a flat array
# In case of recursive references, the Array#flatten! will fail with ArgumentError: tried to flatten recursive array
# {service => [linked_service, linked_service_link, ...]}
service_links.each do |service, links|
begin
service_links[service] = service_links[service].flatten
rescue ArgumentError
raise RecursiveLinkError.new(service, links)
end
end
# Sort using deep service links
services.sort{ |a, b|
a_links = service_links[a[:name]]
b_links = service_links[b[:name]]
if a_links.include? b[:name]
1
elsif b_links.include? a[:name]
-1
else
a_links.size <=> b_links.size
end
}
end | ruby | def sort_services(services)
# Map of service name to array of deep links, including links of linked services
service_links = {}
# Build hash of service name to shallow array of linked service names
# {service => [linked_service]}
services.each do |service|
service_links[service[:name]] = __links_for_service(service)
end
# Mutate each service's array to add a deep reference to each linked service's own array of linked services
# {service => [linked_service, [linked_service_links, [...]]]}
service_links.each do |service, links|
links.dup.each do |linked_service|
if linked_service_links = service_links[linked_service]
service_links[service] << linked_service_links
else
raise MissingLinkError.new(service, linked_service)
end
end
end
# Flatten the deep array references to a flat array
# In case of recursive references, the Array#flatten! will fail with ArgumentError: tried to flatten recursive array
# {service => [linked_service, linked_service_link, ...]}
service_links.each do |service, links|
begin
service_links[service] = service_links[service].flatten
rescue ArgumentError
raise RecursiveLinkError.new(service, links)
end
end
# Sort using deep service links
services.sort{ |a, b|
a_links = service_links[a[:name]]
b_links = service_links[b[:name]]
if a_links.include? b[:name]
1
elsif b_links.include? a[:name]
-1
else
a_links.size <=> b_links.size
end
}
end | [
"def",
"sort_services",
"(",
"services",
")",
"# Map of service name to array of deep links, including links of linked services",
"service_links",
"=",
"{",
"}",
"# Build hash of service name to shallow array of linked service names",
"# {service => [linked_service]}",
"services",
".",
"each",
"do",
"|",
"service",
"|",
"service_links",
"[",
"service",
"[",
":name",
"]",
"]",
"=",
"__links_for_service",
"(",
"service",
")",
"end",
"# Mutate each service's array to add a deep reference to each linked service's own array of linked services",
"# {service => [linked_service, [linked_service_links, [...]]]}",
"service_links",
".",
"each",
"do",
"|",
"service",
",",
"links",
"|",
"links",
".",
"dup",
".",
"each",
"do",
"|",
"linked_service",
"|",
"if",
"linked_service_links",
"=",
"service_links",
"[",
"linked_service",
"]",
"service_links",
"[",
"service",
"]",
"<<",
"linked_service_links",
"else",
"raise",
"MissingLinkError",
".",
"new",
"(",
"service",
",",
"linked_service",
")",
"end",
"end",
"end",
"# Flatten the deep array references to a flat array",
"# In case of recursive references, the Array#flatten! will fail with ArgumentError: tried to flatten recursive array",
"# {service => [linked_service, linked_service_link, ...]}",
"service_links",
".",
"each",
"do",
"|",
"service",
",",
"links",
"|",
"begin",
"service_links",
"[",
"service",
"]",
"=",
"service_links",
"[",
"service",
"]",
".",
"flatten",
"rescue",
"ArgumentError",
"raise",
"RecursiveLinkError",
".",
"new",
"(",
"service",
",",
"links",
")",
"end",
"end",
"# Sort using deep service links",
"services",
".",
"sort",
"{",
"|",
"a",
",",
"b",
"|",
"a_links",
"=",
"service_links",
"[",
"a",
"[",
":name",
"]",
"]",
"b_links",
"=",
"service_links",
"[",
"b",
"[",
":name",
"]",
"]",
"if",
"a_links",
".",
"include?",
"b",
"[",
":name",
"]",
"1",
"elsif",
"b_links",
".",
"include?",
"a",
"[",
":name",
"]",
"-",
"1",
"else",
"a_links",
".",
"size",
"<=>",
"b_links",
".",
"size",
"end",
"}",
"end"
] | Sort services with a stack, such that services come after any services that they link to.
This can only be used to sort services within the same stack. Links to services in other stacks are ignored.
@param [Array<GridService,Hash>]
@raise [MissingLinkError] service ... has missing links: ...
@raise [RecursiveLinkError] service ... has recursive links: ...
@return [Array<GridService,Hash>] | [
"Sort",
"services",
"with",
"a",
"stack",
"such",
"that",
"services",
"come",
"after",
"any",
"services",
"that",
"they",
"link",
"to",
".",
"This",
"can",
"only",
"be",
"used",
"to",
"sort",
"services",
"within",
"the",
"same",
"stack",
".",
"Links",
"to",
"services",
"in",
"other",
"stacks",
"are",
"ignored",
"."
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/server/app/mutations/stacks/sort_helper.rb#L46-L92 | train |
kontena/kontena | cli/lib/kontena/cli/helpers/health_helper.rb | Kontena::Cli::Helpers.HealthHelper.grid_health | def grid_health(grid, nodes)
initial = grid['initial_size']
minimum = grid['initial_size'] / 2 + 1 # a majority is required for etcd quorum
online = nodes.select{|node| node['initial_member'] && node['connected']}
if online.length < minimum
return :error
elsif online.length < initial
return :warning
else
return :ok
end
end | ruby | def grid_health(grid, nodes)
initial = grid['initial_size']
minimum = grid['initial_size'] / 2 + 1 # a majority is required for etcd quorum
online = nodes.select{|node| node['initial_member'] && node['connected']}
if online.length < minimum
return :error
elsif online.length < initial
return :warning
else
return :ok
end
end | [
"def",
"grid_health",
"(",
"grid",
",",
"nodes",
")",
"initial",
"=",
"grid",
"[",
"'initial_size'",
"]",
"minimum",
"=",
"grid",
"[",
"'initial_size'",
"]",
"/",
"2",
"+",
"1",
"# a majority is required for etcd quorum",
"online",
"=",
"nodes",
".",
"select",
"{",
"|",
"node",
"|",
"node",
"[",
"'initial_member'",
"]",
"&&",
"node",
"[",
"'connected'",
"]",
"}",
"if",
"online",
".",
"length",
"<",
"minimum",
"return",
":error",
"elsif",
"online",
".",
"length",
"<",
"initial",
"return",
":warning",
"else",
"return",
":ok",
"end",
"end"
] | Validate grid nodes configuration and status
@param grid [Hash] get(/grids/:grid) => { ... }
@param nodes [Array<Hash>] get(/grids/:grid/nodes)[nodes] => [ { ... } ]
@return [Symbol] health | [
"Validate",
"grid",
"nodes",
"configuration",
"and",
"status"
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/cli/helpers/health_helper.rb#L25-L38 | train |
kontena/kontena | cli/lib/kontena/cli/stacks/common.rb | Kontena::Cli::Stacks.Common.stack | def stack
@stack ||= reader.execute(
name: stack_name,
parent_name: self.respond_to?(:parent_name) ? self.parent_name : nil,
values: (self.respond_to?(:values_from_options) ? self.values_from_options : {})
)
end | ruby | def stack
@stack ||= reader.execute(
name: stack_name,
parent_name: self.respond_to?(:parent_name) ? self.parent_name : nil,
values: (self.respond_to?(:values_from_options) ? self.values_from_options : {})
)
end | [
"def",
"stack",
"@stack",
"||=",
"reader",
".",
"execute",
"(",
"name",
":",
"stack_name",
",",
"parent_name",
":",
"self",
".",
"respond_to?",
"(",
":parent_name",
")",
"?",
"self",
".",
"parent_name",
":",
"nil",
",",
"values",
":",
"(",
"self",
".",
"respond_to?",
"(",
":values_from_options",
")",
"?",
"self",
".",
"values_from_options",
":",
"{",
"}",
")",
")",
"end"
] | An accessor to the YAML Reader outcome. Passes parent name, values from command line and
the stackname to the reader.
@return [Hash] | [
"An",
"accessor",
"to",
"the",
"YAML",
"Reader",
"outcome",
".",
"Passes",
"parent",
"name",
"values",
"from",
"command",
"line",
"and",
"the",
"stackname",
"to",
"the",
"reader",
"."
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/cli/stacks/common.rb#L32-L38 | train |
kontena/kontena | cli/lib/kontena/cli/stacks/common.rb | Kontena::Cli::Stacks.Common.set_env_variables | def set_env_variables(stack, grid, platform = grid)
ENV['STACK'] = stack
ENV['GRID'] = grid
ENV['PLATFORM'] = platform
end | ruby | def set_env_variables(stack, grid, platform = grid)
ENV['STACK'] = stack
ENV['GRID'] = grid
ENV['PLATFORM'] = platform
end | [
"def",
"set_env_variables",
"(",
"stack",
",",
"grid",
",",
"platform",
"=",
"grid",
")",
"ENV",
"[",
"'STACK'",
"]",
"=",
"stack",
"ENV",
"[",
"'GRID'",
"]",
"=",
"grid",
"ENV",
"[",
"'PLATFORM'",
"]",
"=",
"platform",
"end"
] | Sets environment variables from parameters
@param stack [String] current stack name
@param grid [String] current grid name
@param platform [String] current platform name, defaults to param grid value | [
"Sets",
"environment",
"variables",
"from",
"parameters"
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/cli/stacks/common.rb#L175-L179 | train |
kontena/kontena | cli/lib/kontena/cli/stacks/common.rb | Kontena::Cli::Stacks.Common.stacks_client | def stacks_client
@stacks_client ||= Kontena::StacksClient.new(current_account.stacks_url, current_account.token, read_requires_token: current_account.stacks_read_authentication)
end | ruby | def stacks_client
@stacks_client ||= Kontena::StacksClient.new(current_account.stacks_url, current_account.token, read_requires_token: current_account.stacks_read_authentication)
end | [
"def",
"stacks_client",
"@stacks_client",
"||=",
"Kontena",
"::",
"StacksClient",
".",
"new",
"(",
"current_account",
".",
"stacks_url",
",",
"current_account",
".",
"token",
",",
"read_requires_token",
":",
"current_account",
".",
"stacks_read_authentication",
")",
"end"
] | An accessor to stack registry client
@return [Kontena::StacksClient] | [
"An",
"accessor",
"to",
"stack",
"registry",
"client"
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/cli/stacks/common.rb#L205-L207 | train |
kontena/kontena | cli/lib/kontena/stacks/change_resolver.rb | Kontena::Stacks.ChangeResolver.stack_upgraded? | def stack_upgraded?(name)
old_stack = old_data.stack(name)
new_stack = new_data.stack(name)
return true if new_stack.root?
return true if old_stack.version != new_stack.version
return true if old_stack.stack_name != new_stack.stack_name
return true if old_stack.variables != new_stack.variables
false
end | ruby | def stack_upgraded?(name)
old_stack = old_data.stack(name)
new_stack = new_data.stack(name)
return true if new_stack.root?
return true if old_stack.version != new_stack.version
return true if old_stack.stack_name != new_stack.stack_name
return true if old_stack.variables != new_stack.variables
false
end | [
"def",
"stack_upgraded?",
"(",
"name",
")",
"old_stack",
"=",
"old_data",
".",
"stack",
"(",
"name",
")",
"new_stack",
"=",
"new_data",
".",
"stack",
"(",
"name",
")",
"return",
"true",
"if",
"new_stack",
".",
"root?",
"return",
"true",
"if",
"old_stack",
".",
"version",
"!=",
"new_stack",
".",
"version",
"return",
"true",
"if",
"old_stack",
".",
"stack_name",
"!=",
"new_stack",
".",
"stack_name",
"return",
"true",
"if",
"old_stack",
".",
"variables",
"!=",
"new_stack",
".",
"variables",
"false",
"end"
] | Stack is upgraded if version, stack name, variables change or stack is root
@param name [String]
@return [Boolean] | [
"Stack",
"is",
"upgraded",
"if",
"version",
"stack",
"name",
"variables",
"change",
"or",
"stack",
"is",
"root"
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/stacks/change_resolver.rb#L107-L116 | train |
kontena/kontena | agent/lib/kontena/workers/log_worker.rb | Kontena::Workers.LogWorker.process_queue | def process_queue
loop do
sleep 1 until processing?
buffer = @queue.shift(BATCH_SIZE)
if buffer.size > 0
rpc_client.notification('/containers/log_batch', [buffer])
sleep 0.01
else
sleep 1
end
end
end | ruby | def process_queue
loop do
sleep 1 until processing?
buffer = @queue.shift(BATCH_SIZE)
if buffer.size > 0
rpc_client.notification('/containers/log_batch', [buffer])
sleep 0.01
else
sleep 1
end
end
end | [
"def",
"process_queue",
"loop",
"do",
"sleep",
"1",
"until",
"processing?",
"buffer",
"=",
"@queue",
".",
"shift",
"(",
"BATCH_SIZE",
")",
"if",
"buffer",
".",
"size",
">",
"0",
"rpc_client",
".",
"notification",
"(",
"'/containers/log_batch'",
",",
"[",
"buffer",
"]",
")",
"sleep",
"0.01",
"else",
"sleep",
"1",
"end",
"end",
"end"
] | Process items from @queue | [
"Process",
"items",
"from"
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/workers/log_worker.rb#L62-L73 | train |
kontena/kontena | agent/lib/kontena/workers/log_worker.rb | Kontena::Workers.LogWorker.start_streaming | def start_streaming
info 'start streaming logs from containers'
Docker::Container.all.each do |container|
begin
self.stream_container_logs(container) unless container.skip_logs?
rescue Docker::Error::NotFoundError => exc
# Could be thrown since container.skip_logs? actually loads the container details
warn exc.message
rescue => exc
error exc
end
end
@streaming = true
end | ruby | def start_streaming
info 'start streaming logs from containers'
Docker::Container.all.each do |container|
begin
self.stream_container_logs(container) unless container.skip_logs?
rescue Docker::Error::NotFoundError => exc
# Could be thrown since container.skip_logs? actually loads the container details
warn exc.message
rescue => exc
error exc
end
end
@streaming = true
end | [
"def",
"start_streaming",
"info",
"'start streaming logs from containers'",
"Docker",
"::",
"Container",
".",
"all",
".",
"each",
"do",
"|",
"container",
"|",
"begin",
"self",
".",
"stream_container_logs",
"(",
"container",
")",
"unless",
"container",
".",
"skip_logs?",
"rescue",
"Docker",
"::",
"Error",
"::",
"NotFoundError",
"=>",
"exc",
"# Could be thrown since container.skip_logs? actually loads the container details",
"warn",
"exc",
".",
"message",
"rescue",
"=>",
"exc",
"error",
"exc",
"end",
"end",
"@streaming",
"=",
"true",
"end"
] | requires etcd to be available to read log timestamps | [
"requires",
"etcd",
"to",
"be",
"available",
"to",
"read",
"log",
"timestamps"
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/workers/log_worker.rb#L126-L141 | train |
kontena/kontena | agent/lib/kontena/workers/log_worker.rb | Kontena::Workers.LogWorker.stop_streaming | def stop_streaming
@streaming = false
info 'stop log streaming'
@workers.keys.dup.each do |id|
queued_item = @queue.find { |i| i[:id] == id }
time = queued_item.nil? ? Time.now.to_i : Time.parse(queued_item[:time]).to_i
self.stop_streaming_container_logs(id)
self.mark_timestamp(id, time)
end
end | ruby | def stop_streaming
@streaming = false
info 'stop log streaming'
@workers.keys.dup.each do |id|
queued_item = @queue.find { |i| i[:id] == id }
time = queued_item.nil? ? Time.now.to_i : Time.parse(queued_item[:time]).to_i
self.stop_streaming_container_logs(id)
self.mark_timestamp(id, time)
end
end | [
"def",
"stop_streaming",
"@streaming",
"=",
"false",
"info",
"'stop log streaming'",
"@workers",
".",
"keys",
".",
"dup",
".",
"each",
"do",
"|",
"id",
"|",
"queued_item",
"=",
"@queue",
".",
"find",
"{",
"|",
"i",
"|",
"i",
"[",
":id",
"]",
"==",
"id",
"}",
"time",
"=",
"queued_item",
".",
"nil?",
"?",
"Time",
".",
"now",
".",
"to_i",
":",
"Time",
".",
"parse",
"(",
"queued_item",
"[",
":time",
"]",
")",
".",
"to_i",
"self",
".",
"stop_streaming_container_logs",
"(",
"id",
")",
"self",
".",
"mark_timestamp",
"(",
"id",
",",
"time",
")",
"end",
"end"
] | best-effort attempt to write etcd timestamps; may not be possible | [
"best",
"-",
"effort",
"attempt",
"to",
"write",
"etcd",
"timestamps",
";",
"may",
"not",
"be",
"possible"
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/workers/log_worker.rb#L169-L180 | train |
kontena/kontena | cli/lib/kontena/cli/stacks/upgrade_command.rb | Kontena::Cli::Stacks.UpgradeCommand.process_data | def process_data(old_data, new_data)
logger.debug { "Master stacks: #{old_data.keys.join(",")} YAML stacks: #{new_data.keys.join(",")}" }
new_data.reverse_each do |stackname, data|
spinner "Processing stack #{pastel.cyan(stackname)}"
process_stack_data(stackname, data, old_data)
hint_on_validation_notifications(reader.notifications, reader.loader.source)
abort_on_validation_errors(reader.errors, reader.loader.source)
end
old_set = Kontena::Stacks::StackDataSet.new(old_data)
new_set = Kontena::Stacks::StackDataSet.new(new_data)
if skip_dependencies?
[old_set, new_set].each(&:remove_dependencies)
end
spinner "Analyzing upgrade" do
Kontena::Stacks::ChangeResolver.new(old_set, new_set)
end
end | ruby | def process_data(old_data, new_data)
logger.debug { "Master stacks: #{old_data.keys.join(",")} YAML stacks: #{new_data.keys.join(",")}" }
new_data.reverse_each do |stackname, data|
spinner "Processing stack #{pastel.cyan(stackname)}"
process_stack_data(stackname, data, old_data)
hint_on_validation_notifications(reader.notifications, reader.loader.source)
abort_on_validation_errors(reader.errors, reader.loader.source)
end
old_set = Kontena::Stacks::StackDataSet.new(old_data)
new_set = Kontena::Stacks::StackDataSet.new(new_data)
if skip_dependencies?
[old_set, new_set].each(&:remove_dependencies)
end
spinner "Analyzing upgrade" do
Kontena::Stacks::ChangeResolver.new(old_set, new_set)
end
end | [
"def",
"process_data",
"(",
"old_data",
",",
"new_data",
")",
"logger",
".",
"debug",
"{",
"\"Master stacks: #{old_data.keys.join(\",\")} YAML stacks: #{new_data.keys.join(\",\")}\"",
"}",
"new_data",
".",
"reverse_each",
"do",
"|",
"stackname",
",",
"data",
"|",
"spinner",
"\"Processing stack #{pastel.cyan(stackname)}\"",
"process_stack_data",
"(",
"stackname",
",",
"data",
",",
"old_data",
")",
"hint_on_validation_notifications",
"(",
"reader",
".",
"notifications",
",",
"reader",
".",
"loader",
".",
"source",
")",
"abort_on_validation_errors",
"(",
"reader",
".",
"errors",
",",
"reader",
".",
"loader",
".",
"source",
")",
"end",
"old_set",
"=",
"Kontena",
"::",
"Stacks",
"::",
"StackDataSet",
".",
"new",
"(",
"old_data",
")",
"new_set",
"=",
"Kontena",
"::",
"Stacks",
"::",
"StackDataSet",
".",
"new",
"(",
"new_data",
")",
"if",
"skip_dependencies?",
"[",
"old_set",
",",
"new_set",
"]",
".",
"each",
"(",
":remove_dependencies",
")",
"end",
"spinner",
"\"Analyzing upgrade\"",
"do",
"Kontena",
"::",
"Stacks",
"::",
"ChangeResolver",
".",
"new",
"(",
"old_set",
",",
"new_set",
")",
"end",
"end"
] | Preprocess data and return a ChangeResolver
@param old_data [Hash] data from master
@param new_data [Hash] data from files
@return [Kontena::Cli::Stacks::ChangeRsolver] | [
"Preprocess",
"data",
"and",
"return",
"a",
"ChangeResolver"
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/cli/stacks/upgrade_command.rb#L89-L107 | train |
kontena/kontena | cli/lib/kontena/cli/localhost_web_server.rb | Kontena.LocalhostWebServer.serve_one | def serve_one
Kontena.logger.debug("LHWS") { "Waiting for connection on port #{port}.." }
socket = server.accept
content = socket.recvfrom(2048).first.split(/(?:\r)?\n/)
request = content.shift
headers = {}
while line = content.shift
break if line.nil?
break if line == ''
header, value = line.chomp.split(/:\s{0,}/, 2)
headers[header] = value
end
body = content.join("\n")
Kontena.logger.debug("LHWS") { "Got request: \"#{request.inspect}\n Headers: #{headers.inspect}\n Body: #{body}\"" }
get_request = request[/GET (\/cb.+?) HTTP/, 1]
if get_request
if success_response
socket.print [
'HTTP/1.1 200 OK',
'Content-Type: text/html',
"Content-Length: #{success_response.bytesize}",
"Connection: close",
'',
success_response
].join("\r\n")
else
socket.print [
'HTTP/1.1 302 Found',
"Location: #{SUCCESS_URL}",
"Referrer-Policy: no-referrer",
"Connection: close",
''
].join("\r\n")
end
socket.close
server.close
uri = URI.parse("http://localhost#{get_request}")
Kontena.logger.debug("LHWS") { " * Parsing params: \"#{uri.query}\"" }
params = {}
URI.decode_www_form(uri.query).each do |key, value|
if value.to_s == ''
next
elsif value.to_s =~ /\A\d+\z/
params[key] = value.to_i
else
params[key] = value
end
end
params
else
# Unless it's a query to /cb, send an error message and keep listening,
# it might have been something funny like fetching favicon.ico
socket.print [
'HTTP/1.1 400 Bad request',
'Content-Type: text/plain',
"Content-Length: #{error_response.bytesize}",
'Connection: close',
'',
error_response
].join("\r\n")
socket.close
serve_one # serve more, this one was not proper.
end
end | ruby | def serve_one
Kontena.logger.debug("LHWS") { "Waiting for connection on port #{port}.." }
socket = server.accept
content = socket.recvfrom(2048).first.split(/(?:\r)?\n/)
request = content.shift
headers = {}
while line = content.shift
break if line.nil?
break if line == ''
header, value = line.chomp.split(/:\s{0,}/, 2)
headers[header] = value
end
body = content.join("\n")
Kontena.logger.debug("LHWS") { "Got request: \"#{request.inspect}\n Headers: #{headers.inspect}\n Body: #{body}\"" }
get_request = request[/GET (\/cb.+?) HTTP/, 1]
if get_request
if success_response
socket.print [
'HTTP/1.1 200 OK',
'Content-Type: text/html',
"Content-Length: #{success_response.bytesize}",
"Connection: close",
'',
success_response
].join("\r\n")
else
socket.print [
'HTTP/1.1 302 Found',
"Location: #{SUCCESS_URL}",
"Referrer-Policy: no-referrer",
"Connection: close",
''
].join("\r\n")
end
socket.close
server.close
uri = URI.parse("http://localhost#{get_request}")
Kontena.logger.debug("LHWS") { " * Parsing params: \"#{uri.query}\"" }
params = {}
URI.decode_www_form(uri.query).each do |key, value|
if value.to_s == ''
next
elsif value.to_s =~ /\A\d+\z/
params[key] = value.to_i
else
params[key] = value
end
end
params
else
# Unless it's a query to /cb, send an error message and keep listening,
# it might have been something funny like fetching favicon.ico
socket.print [
'HTTP/1.1 400 Bad request',
'Content-Type: text/plain',
"Content-Length: #{error_response.bytesize}",
'Connection: close',
'',
error_response
].join("\r\n")
socket.close
serve_one # serve more, this one was not proper.
end
end | [
"def",
"serve_one",
"Kontena",
".",
"logger",
".",
"debug",
"(",
"\"LHWS\"",
")",
"{",
"\"Waiting for connection on port #{port}..\"",
"}",
"socket",
"=",
"server",
".",
"accept",
"content",
"=",
"socket",
".",
"recvfrom",
"(",
"2048",
")",
".",
"first",
".",
"split",
"(",
"/",
"\\r",
"\\n",
"/",
")",
"request",
"=",
"content",
".",
"shift",
"headers",
"=",
"{",
"}",
"while",
"line",
"=",
"content",
".",
"shift",
"break",
"if",
"line",
".",
"nil?",
"break",
"if",
"line",
"==",
"''",
"header",
",",
"value",
"=",
"line",
".",
"chomp",
".",
"split",
"(",
"/",
"\\s",
"/",
",",
"2",
")",
"headers",
"[",
"header",
"]",
"=",
"value",
"end",
"body",
"=",
"content",
".",
"join",
"(",
"\"\\n\"",
")",
"Kontena",
".",
"logger",
".",
"debug",
"(",
"\"LHWS\"",
")",
"{",
"\"Got request: \\\"#{request.inspect}\\n Headers: #{headers.inspect}\\n Body: #{body}\\\"\"",
"}",
"get_request",
"=",
"request",
"[",
"/",
"\\/",
"/",
",",
"1",
"]",
"if",
"get_request",
"if",
"success_response",
"socket",
".",
"print",
"[",
"'HTTP/1.1 200 OK'",
",",
"'Content-Type: text/html'",
",",
"\"Content-Length: #{success_response.bytesize}\"",
",",
"\"Connection: close\"",
",",
"''",
",",
"success_response",
"]",
".",
"join",
"(",
"\"\\r\\n\"",
")",
"else",
"socket",
".",
"print",
"[",
"'HTTP/1.1 302 Found'",
",",
"\"Location: #{SUCCESS_URL}\"",
",",
"\"Referrer-Policy: no-referrer\"",
",",
"\"Connection: close\"",
",",
"''",
"]",
".",
"join",
"(",
"\"\\r\\n\"",
")",
"end",
"socket",
".",
"close",
"server",
".",
"close",
"uri",
"=",
"URI",
".",
"parse",
"(",
"\"http://localhost#{get_request}\"",
")",
"Kontena",
".",
"logger",
".",
"debug",
"(",
"\"LHWS\"",
")",
"{",
"\" * Parsing params: \\\"#{uri.query}\\\"\"",
"}",
"params",
"=",
"{",
"}",
"URI",
".",
"decode_www_form",
"(",
"uri",
".",
"query",
")",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"if",
"value",
".",
"to_s",
"==",
"''",
"next",
"elsif",
"value",
".",
"to_s",
"=~",
"/",
"\\A",
"\\d",
"\\z",
"/",
"params",
"[",
"key",
"]",
"=",
"value",
".",
"to_i",
"else",
"params",
"[",
"key",
"]",
"=",
"value",
"end",
"end",
"params",
"else",
"# Unless it's a query to /cb, send an error message and keep listening,",
"# it might have been something funny like fetching favicon.ico",
"socket",
".",
"print",
"[",
"'HTTP/1.1 400 Bad request'",
",",
"'Content-Type: text/plain'",
",",
"\"Content-Length: #{error_response.bytesize}\"",
",",
"'Connection: close'",
",",
"''",
",",
"error_response",
"]",
".",
"join",
"(",
"\"\\r\\n\"",
")",
"socket",
".",
"close",
"serve_one",
"# serve more, this one was not proper.",
"end",
"end"
] | Serve one request and return query params.
@return [Hash] query_params | [
"Serve",
"one",
"request",
"and",
"return",
"query",
"params",
"."
] | 5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7 | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/cli/localhost_web_server.rb#L41-L111 | train |
egonSchiele/contracts.ruby | lib/contracts/method_handler.rb | Contracts.MethodHandler.handle | def handle
return unless engine?
return if decorators.empty?
validate_decorators!
validate_pattern_matching!
engine.add_method_decorator(method_type, method_name, decorator)
mark_pattern_matching_decorators
method_reference.make_alias(target)
redefine_method
end | ruby | def handle
return unless engine?
return if decorators.empty?
validate_decorators!
validate_pattern_matching!
engine.add_method_decorator(method_type, method_name, decorator)
mark_pattern_matching_decorators
method_reference.make_alias(target)
redefine_method
end | [
"def",
"handle",
"return",
"unless",
"engine?",
"return",
"if",
"decorators",
".",
"empty?",
"validate_decorators!",
"validate_pattern_matching!",
"engine",
".",
"add_method_decorator",
"(",
"method_type",
",",
"method_name",
",",
"decorator",
")",
"mark_pattern_matching_decorators",
"method_reference",
".",
"make_alias",
"(",
"target",
")",
"redefine_method",
"end"
] | Creates new instance of MethodHandler
@param [Symbol] method_name
@param [Bool] is_class_method
@param [Class] target - class that method got added to
Handles method addition | [
"Creates",
"new",
"instance",
"of",
"MethodHandler"
] | 141dfb71c2dfb3fe10bda05cdd9f45b96eeb4716 | https://github.com/egonSchiele/contracts.ruby/blob/141dfb71c2dfb3fe10bda05cdd9f45b96eeb4716/lib/contracts/method_handler.rb#L27-L38 | train |
egonSchiele/contracts.ruby | lib/contracts/method_reference.rb | Contracts.MethodReference.make_definition | def make_definition(this, &blk)
is_private = private?(this)
is_protected = protected?(this)
alias_target(this).send(:define_method, name, &blk)
make_private(this) if is_private
make_protected(this) if is_protected
end | ruby | def make_definition(this, &blk)
is_private = private?(this)
is_protected = protected?(this)
alias_target(this).send(:define_method, name, &blk)
make_private(this) if is_private
make_protected(this) if is_protected
end | [
"def",
"make_definition",
"(",
"this",
",",
"&",
"blk",
")",
"is_private",
"=",
"private?",
"(",
"this",
")",
"is_protected",
"=",
"protected?",
"(",
"this",
")",
"alias_target",
"(",
"this",
")",
".",
"send",
"(",
":define_method",
",",
"name",
",",
"blk",
")",
"make_private",
"(",
"this",
")",
"if",
"is_private",
"make_protected",
"(",
"this",
")",
"if",
"is_protected",
"end"
] | Makes a method re-definition in proper way | [
"Makes",
"a",
"method",
"re",
"-",
"definition",
"in",
"proper",
"way"
] | 141dfb71c2dfb3fe10bda05cdd9f45b96eeb4716 | https://github.com/egonSchiele/contracts.ruby/blob/141dfb71c2dfb3fe10bda05cdd9f45b96eeb4716/lib/contracts/method_reference.rb#L20-L26 | train |
egonSchiele/contracts.ruby | lib/contracts/method_reference.rb | Contracts.MethodReference.make_alias | def make_alias(this)
_aliased_name = aliased_name
original_name = name
alias_target(this).class_eval do
alias_method _aliased_name, original_name
end
end | ruby | def make_alias(this)
_aliased_name = aliased_name
original_name = name
alias_target(this).class_eval do
alias_method _aliased_name, original_name
end
end | [
"def",
"make_alias",
"(",
"this",
")",
"_aliased_name",
"=",
"aliased_name",
"original_name",
"=",
"name",
"alias_target",
"(",
"this",
")",
".",
"class_eval",
"do",
"alias_method",
"_aliased_name",
",",
"original_name",
"end",
"end"
] | Aliases original method to a special unique name, which is known
only to this class. Usually done right before re-defining the
method. | [
"Aliases",
"original",
"method",
"to",
"a",
"special",
"unique",
"name",
"which",
"is",
"known",
"only",
"to",
"this",
"class",
".",
"Usually",
"done",
"right",
"before",
"re",
"-",
"defining",
"the",
"method",
"."
] | 141dfb71c2dfb3fe10bda05cdd9f45b96eeb4716 | https://github.com/egonSchiele/contracts.ruby/blob/141dfb71c2dfb3fe10bda05cdd9f45b96eeb4716/lib/contracts/method_reference.rb#L31-L38 | train |
kschiess/parslet | lib/parslet/atoms/can_flatten.rb | Parslet::Atoms.CanFlatten.flatten | def flatten(value, named=false)
# Passes through everything that isn't an array of things
return value unless value.instance_of? Array
# Extracts the s-expression tag
tag, *tail = value
# Merges arrays:
result = tail.
map { |e| flatten(e) } # first flatten each element
case tag
when :sequence
return flatten_sequence(result)
when :maybe
return named ? result.first : result.first || ''
when :repetition
return flatten_repetition(result, named)
end
fail "BUG: Unknown tag #{tag.inspect}."
end | ruby | def flatten(value, named=false)
# Passes through everything that isn't an array of things
return value unless value.instance_of? Array
# Extracts the s-expression tag
tag, *tail = value
# Merges arrays:
result = tail.
map { |e| flatten(e) } # first flatten each element
case tag
when :sequence
return flatten_sequence(result)
when :maybe
return named ? result.first : result.first || ''
when :repetition
return flatten_repetition(result, named)
end
fail "BUG: Unknown tag #{tag.inspect}."
end | [
"def",
"flatten",
"(",
"value",
",",
"named",
"=",
"false",
")",
"# Passes through everything that isn't an array of things",
"return",
"value",
"unless",
"value",
".",
"instance_of?",
"Array",
"# Extracts the s-expression tag",
"tag",
",",
"*",
"tail",
"=",
"value",
"# Merges arrays:",
"result",
"=",
"tail",
".",
"map",
"{",
"|",
"e",
"|",
"flatten",
"(",
"e",
")",
"}",
"# first flatten each element",
"case",
"tag",
"when",
":sequence",
"return",
"flatten_sequence",
"(",
"result",
")",
"when",
":maybe",
"return",
"named",
"?",
"result",
".",
"first",
":",
"result",
".",
"first",
"||",
"''",
"when",
":repetition",
"return",
"flatten_repetition",
"(",
"result",
",",
"named",
")",
"end",
"fail",
"\"BUG: Unknown tag #{tag.inspect}.\"",
"end"
] | Takes a mixed value coming out of a parslet and converts it to a return
value for the user by dropping things and merging hashes.
Named is set to true if this result will be embedded in a Hash result from
naming something using <code>.as(...)</code>. It changes the folding
semantics of repetition. | [
"Takes",
"a",
"mixed",
"value",
"coming",
"out",
"of",
"a",
"parslet",
"and",
"converts",
"it",
"to",
"a",
"return",
"value",
"for",
"the",
"user",
"by",
"dropping",
"things",
"and",
"merging",
"hashes",
"."
] | b108758d76c51a1630f3b13c8f47dcd6637c5477 | https://github.com/kschiess/parslet/blob/b108758d76c51a1630f3b13c8f47dcd6637c5477/lib/parslet/atoms/can_flatten.rb#L23-L44 | train |
kschiess/parslet | lib/parslet/atoms/can_flatten.rb | Parslet::Atoms.CanFlatten.foldl | def foldl(list, &block)
return '' if list.empty?
list[1..-1].inject(list.first, &block)
end | ruby | def foldl(list, &block)
return '' if list.empty?
list[1..-1].inject(list.first, &block)
end | [
"def",
"foldl",
"(",
"list",
",",
"&",
"block",
")",
"return",
"''",
"if",
"list",
".",
"empty?",
"list",
"[",
"1",
"..",
"-",
"1",
"]",
".",
"inject",
"(",
"list",
".",
"first",
",",
"block",
")",
"end"
] | Lisp style fold left where the first element builds the basis for
an inject. | [
"Lisp",
"style",
"fold",
"left",
"where",
"the",
"first",
"element",
"builds",
"the",
"basis",
"for",
"an",
"inject",
"."
] | b108758d76c51a1630f3b13c8f47dcd6637c5477 | https://github.com/kschiess/parslet/blob/b108758d76c51a1630f3b13c8f47dcd6637c5477/lib/parslet/atoms/can_flatten.rb#L49-L52 | train |
kschiess/parslet | lib/parslet/atoms/can_flatten.rb | Parslet::Atoms.CanFlatten.flatten_sequence | def flatten_sequence(list)
foldl(list.compact) { |r, e| # and then merge flat elements
merge_fold(r, e)
}
end | ruby | def flatten_sequence(list)
foldl(list.compact) { |r, e| # and then merge flat elements
merge_fold(r, e)
}
end | [
"def",
"flatten_sequence",
"(",
"list",
")",
"foldl",
"(",
"list",
".",
"compact",
")",
"{",
"|",
"r",
",",
"e",
"|",
"# and then merge flat elements",
"merge_fold",
"(",
"r",
",",
"e",
")",
"}",
"end"
] | Flatten results from a sequence of parslets.
@api private | [
"Flatten",
"results",
"from",
"a",
"sequence",
"of",
"parslets",
"."
] | b108758d76c51a1630f3b13c8f47dcd6637c5477 | https://github.com/kschiess/parslet/blob/b108758d76c51a1630f3b13c8f47dcd6637c5477/lib/parslet/atoms/can_flatten.rb#L58-L62 | train |
kschiess/parslet | lib/parslet/atoms/can_flatten.rb | Parslet::Atoms.CanFlatten.flatten_repetition | def flatten_repetition(list, named)
if list.any? { |e| e.instance_of?(Hash) }
# If keyed subtrees are in the array, we'll want to discard all
# strings inbetween. To keep them, name them.
return list.select { |e| e.instance_of?(Hash) }
end
if list.any? { |e| e.instance_of?(Array) }
# If any arrays are nested in this array, flatten all arrays to this
# level.
return list.
select { |e| e.instance_of?(Array) }.
flatten(1)
end
# Consistent handling of empty lists, when we act on a named result
return [] if named && list.empty?
# If there are only strings, concatenate them and return that.
foldl(list.compact) { |s,e| s+e }
end | ruby | def flatten_repetition(list, named)
if list.any? { |e| e.instance_of?(Hash) }
# If keyed subtrees are in the array, we'll want to discard all
# strings inbetween. To keep them, name them.
return list.select { |e| e.instance_of?(Hash) }
end
if list.any? { |e| e.instance_of?(Array) }
# If any arrays are nested in this array, flatten all arrays to this
# level.
return list.
select { |e| e.instance_of?(Array) }.
flatten(1)
end
# Consistent handling of empty lists, when we act on a named result
return [] if named && list.empty?
# If there are only strings, concatenate them and return that.
foldl(list.compact) { |s,e| s+e }
end | [
"def",
"flatten_repetition",
"(",
"list",
",",
"named",
")",
"if",
"list",
".",
"any?",
"{",
"|",
"e",
"|",
"e",
".",
"instance_of?",
"(",
"Hash",
")",
"}",
"# If keyed subtrees are in the array, we'll want to discard all ",
"# strings inbetween. To keep them, name them. ",
"return",
"list",
".",
"select",
"{",
"|",
"e",
"|",
"e",
".",
"instance_of?",
"(",
"Hash",
")",
"}",
"end",
"if",
"list",
".",
"any?",
"{",
"|",
"e",
"|",
"e",
".",
"instance_of?",
"(",
"Array",
")",
"}",
"# If any arrays are nested in this array, flatten all arrays to this",
"# level. ",
"return",
"list",
".",
"select",
"{",
"|",
"e",
"|",
"e",
".",
"instance_of?",
"(",
"Array",
")",
"}",
".",
"flatten",
"(",
"1",
")",
"end",
"# Consistent handling of empty lists, when we act on a named result ",
"return",
"[",
"]",
"if",
"named",
"&&",
"list",
".",
"empty?",
"# If there are only strings, concatenate them and return that. ",
"foldl",
"(",
"list",
".",
"compact",
")",
"{",
"|",
"s",
",",
"e",
"|",
"s",
"+",
"e",
"}",
"end"
] | Flatten results from a repetition of a single parslet. named indicates
whether the user has named the result or not. If the user has named
the results, we want to leave an empty list alone - otherwise it is
turned into an empty string.
@api private | [
"Flatten",
"results",
"from",
"a",
"repetition",
"of",
"a",
"single",
"parslet",
".",
"named",
"indicates",
"whether",
"the",
"user",
"has",
"named",
"the",
"result",
"or",
"not",
".",
"If",
"the",
"user",
"has",
"named",
"the",
"results",
"we",
"want",
"to",
"leave",
"an",
"empty",
"list",
"alone",
"-",
"otherwise",
"it",
"is",
"turned",
"into",
"an",
"empty",
"string",
"."
] | b108758d76c51a1630f3b13c8f47dcd6637c5477 | https://github.com/kschiess/parslet/blob/b108758d76c51a1630f3b13c8f47dcd6637c5477/lib/parslet/atoms/can_flatten.rb#L104-L124 | train |
kschiess/parslet | lib/parslet.rb | Parslet.ClassMethods.rule | def rule(name, opts={}, &definition)
undef_method name if method_defined? name
define_method(name) do
@rules ||= {} # <name, rule> memoization
return @rules[name] if @rules.has_key?(name)
# Capture the self of the parser class along with the definition.
definition_closure = proc {
self.instance_eval(&definition)
}
@rules[name] = Atoms::Entity.new(name, opts[:label], &definition_closure)
end
end | ruby | def rule(name, opts={}, &definition)
undef_method name if method_defined? name
define_method(name) do
@rules ||= {} # <name, rule> memoization
return @rules[name] if @rules.has_key?(name)
# Capture the self of the parser class along with the definition.
definition_closure = proc {
self.instance_eval(&definition)
}
@rules[name] = Atoms::Entity.new(name, opts[:label], &definition_closure)
end
end | [
"def",
"rule",
"(",
"name",
",",
"opts",
"=",
"{",
"}",
",",
"&",
"definition",
")",
"undef_method",
"name",
"if",
"method_defined?",
"name",
"define_method",
"(",
"name",
")",
"do",
"@rules",
"||=",
"{",
"}",
"# <name, rule> memoization",
"return",
"@rules",
"[",
"name",
"]",
"if",
"@rules",
".",
"has_key?",
"(",
"name",
")",
"# Capture the self of the parser class along with the definition.",
"definition_closure",
"=",
"proc",
"{",
"self",
".",
"instance_eval",
"(",
"definition",
")",
"}",
"@rules",
"[",
"name",
"]",
"=",
"Atoms",
"::",
"Entity",
".",
"new",
"(",
"name",
",",
"opts",
"[",
":label",
"]",
",",
"definition_closure",
")",
"end",
"end"
] | Define an entity for the parser. This generates a method of the same
name that can be used as part of other patterns. Those methods can be
freely mixed in your parser class with real ruby methods.
class MyParser
include Parslet
rule(:bar) { str('bar') }
rule(:twobar) do
bar >> bar
end
root :twobar
end | [
"Define",
"an",
"entity",
"for",
"the",
"parser",
".",
"This",
"generates",
"a",
"method",
"of",
"the",
"same",
"name",
"that",
"can",
"be",
"used",
"as",
"part",
"of",
"other",
"patterns",
".",
"Those",
"methods",
"can",
"be",
"freely",
"mixed",
"in",
"your",
"parser",
"class",
"with",
"real",
"ruby",
"methods",
"."
] | b108758d76c51a1630f3b13c8f47dcd6637c5477 | https://github.com/kschiess/parslet/blob/b108758d76c51a1630f3b13c8f47dcd6637c5477/lib/parslet.rb#L102-L115 | train |
kschiess/parslet | lib/parslet/cause.rb | Parslet.Cause.raise | def raise(exception_klass=Parslet::ParseFailed)
exception = exception_klass.new(self.to_s, self)
Kernel.raise exception
end | ruby | def raise(exception_klass=Parslet::ParseFailed)
exception = exception_klass.new(self.to_s, self)
Kernel.raise exception
end | [
"def",
"raise",
"(",
"exception_klass",
"=",
"Parslet",
"::",
"ParseFailed",
")",
"exception",
"=",
"exception_klass",
".",
"new",
"(",
"self",
".",
"to_s",
",",
"self",
")",
"Kernel",
".",
"raise",
"exception",
"end"
] | Signals to the outside that the parse has failed. Use this in
conjunction with .format for nice error messages. | [
"Signals",
"to",
"the",
"outside",
"that",
"the",
"parse",
"has",
"failed",
".",
"Use",
"this",
"in",
"conjunction",
"with",
".",
"format",
"for",
"nice",
"error",
"messages",
"."
] | b108758d76c51a1630f3b13c8f47dcd6637c5477 | https://github.com/kschiess/parslet/blob/b108758d76c51a1630f3b13c8f47dcd6637c5477/lib/parslet/cause.rb#L68-L71 | train |
kschiess/parslet | lib/parslet/source.rb | Parslet.Source.consume | def consume(n)
position = self.pos
slice_str = @str.scan(@re_cache[n])
slice = Parslet::Slice.new(
position,
slice_str,
@line_cache)
return slice
end | ruby | def consume(n)
position = self.pos
slice_str = @str.scan(@re_cache[n])
slice = Parslet::Slice.new(
position,
slice_str,
@line_cache)
return slice
end | [
"def",
"consume",
"(",
"n",
")",
"position",
"=",
"self",
".",
"pos",
"slice_str",
"=",
"@str",
".",
"scan",
"(",
"@re_cache",
"[",
"n",
"]",
")",
"slice",
"=",
"Parslet",
"::",
"Slice",
".",
"new",
"(",
"position",
",",
"slice_str",
",",
"@line_cache",
")",
"return",
"slice",
"end"
] | Consumes n characters from the input, returning them as a slice of the
input. | [
"Consumes",
"n",
"characters",
"from",
"the",
"input",
"returning",
"them",
"as",
"a",
"slice",
"of",
"the",
"input",
"."
] | b108758d76c51a1630f3b13c8f47dcd6637c5477 | https://github.com/kschiess/parslet/blob/b108758d76c51a1630f3b13c8f47dcd6637c5477/lib/parslet/source.rb#L41-L50 | train |
nesaulov/surrealist | lib/surrealist/builder.rb | Surrealist.Builder.construct_collection | def construct_collection(schema, instance, key, value)
schema[key] = instance.send(key).map do |inst|
call(Copier.deep_copy(value), inst)
end
end | ruby | def construct_collection(schema, instance, key, value)
schema[key] = instance.send(key).map do |inst|
call(Copier.deep_copy(value), inst)
end
end | [
"def",
"construct_collection",
"(",
"schema",
",",
"instance",
",",
"key",
",",
"value",
")",
"schema",
"[",
"key",
"]",
"=",
"instance",
".",
"send",
"(",
"key",
")",
".",
"map",
"do",
"|",
"inst",
"|",
"call",
"(",
"Copier",
".",
"deep_copy",
"(",
"value",
")",
",",
"inst",
")",
"end",
"end"
] | Makes the value of appropriate key of the schema an array and pushes in results of iterating through
records and surrealizing them
@param [Hash] schema the schema defined in the object's class.
@param [Object] instance the instance of the object which methods from the schema are called on.
@param [Symbol] key the symbol that represents method on the instance
@param [Any] value returned when key is called on instance
@return [Hash] the schema hash | [
"Makes",
"the",
"value",
"of",
"appropriate",
"key",
"of",
"the",
"schema",
"an",
"array",
"and",
"pushes",
"in",
"results",
"of",
"iterating",
"through",
"records",
"and",
"surrealizing",
"them"
] | 428b44043b879571be03fbab1f3e1800b939fc5e | https://github.com/nesaulov/surrealist/blob/428b44043b879571be03fbab1f3e1800b939fc5e/lib/surrealist/builder.rb#L81-L85 | train |
nesaulov/surrealist | lib/surrealist/instance_methods.rb | Surrealist.InstanceMethods.surrealize | def surrealize(**args)
return args[:serializer].new(self).surrealize(args) if args[:serializer]
if (serializer = find_serializer(args[:for]))
return serializer.new(self).surrealize(args)
end
Oj.dump(Surrealist.build_schema(instance: self, **args), mode: :compat)
end | ruby | def surrealize(**args)
return args[:serializer].new(self).surrealize(args) if args[:serializer]
if (serializer = find_serializer(args[:for]))
return serializer.new(self).surrealize(args)
end
Oj.dump(Surrealist.build_schema(instance: self, **args), mode: :compat)
end | [
"def",
"surrealize",
"(",
"**",
"args",
")",
"return",
"args",
"[",
":serializer",
"]",
".",
"new",
"(",
"self",
")",
".",
"surrealize",
"(",
"args",
")",
"if",
"args",
"[",
":serializer",
"]",
"if",
"(",
"serializer",
"=",
"find_serializer",
"(",
"args",
"[",
":for",
"]",
")",
")",
"return",
"serializer",
".",
"new",
"(",
"self",
")",
".",
"surrealize",
"(",
"args",
")",
"end",
"Oj",
".",
"dump",
"(",
"Surrealist",
".",
"build_schema",
"(",
"instance",
":",
"self",
",",
"**",
"args",
")",
",",
"mode",
":",
":compat",
")",
"end"
] | Dumps the object's methods corresponding to the schema
provided in the object's class and type-checks the values.
@param [Boolean] [optional] camelize optional argument for converting hash to camelBack.
@param [Boolean] [optional] include_root optional argument for having the root key of the resulting hash
as instance's class name.
@param [Boolean] [optional] include_namespaces optional argument for having root key as a nested hash of
instance's namespaces. Animal::Cat.new.surrealize -> (animal: { cat: { weight: '3 kilos' } })
@param [String] [optional] root optional argument for using a specified root key for the hash
@param [Integer] [optional] namespaces_nesting_level level of namespaces nesting.
@return [String] a json-formatted string corresponding to the schema
provided in the object's class. Values will be taken from the return values
of appropriate methods from the object.
@raise +Surrealist::UnknownSchemaError+ if no schema was provided in the object's class.
@raise +Surrealist::InvalidTypeError+ if type-check failed at some point.
@raise +Surrealist::UndefinedMethodError+ if a key defined in the schema
does not have a corresponding method on the object.
@example Define a schema and surrealize the object
class User
include Surrealist
json_schema do
{
name: String,
age: Integer,
}
end
def name
'Nikita'
end
def age
23
end
end
User.new.surrealize
# => "{\"name\":\"Nikita\",\"age\":23}"
# For more examples see README | [
"Dumps",
"the",
"object",
"s",
"methods",
"corresponding",
"to",
"the",
"schema",
"provided",
"in",
"the",
"object",
"s",
"class",
"and",
"type",
"-",
"checks",
"the",
"values",
"."
] | 428b44043b879571be03fbab1f3e1800b939fc5e | https://github.com/nesaulov/surrealist/blob/428b44043b879571be03fbab1f3e1800b939fc5e/lib/surrealist/instance_methods.rb#L51-L59 | train |
nesaulov/surrealist | lib/surrealist/instance_methods.rb | Surrealist.InstanceMethods.build_schema | def build_schema(**args)
return args[:serializer].new(self).build_schema(args) if args[:serializer]
if (serializer = find_serializer(args[:for]))
return serializer.new(self).build_schema(args)
end
Surrealist.build_schema(instance: self, **args)
end | ruby | def build_schema(**args)
return args[:serializer].new(self).build_schema(args) if args[:serializer]
if (serializer = find_serializer(args[:for]))
return serializer.new(self).build_schema(args)
end
Surrealist.build_schema(instance: self, **args)
end | [
"def",
"build_schema",
"(",
"**",
"args",
")",
"return",
"args",
"[",
":serializer",
"]",
".",
"new",
"(",
"self",
")",
".",
"build_schema",
"(",
"args",
")",
"if",
"args",
"[",
":serializer",
"]",
"if",
"(",
"serializer",
"=",
"find_serializer",
"(",
"args",
"[",
":for",
"]",
")",
")",
"return",
"serializer",
".",
"new",
"(",
"self",
")",
".",
"build_schema",
"(",
"args",
")",
"end",
"Surrealist",
".",
"build_schema",
"(",
"instance",
":",
"self",
",",
"**",
"args",
")",
"end"
] | Invokes +Surrealist+'s class method +build_schema+ | [
"Invokes",
"+",
"Surrealist",
"+",
"s",
"class",
"method",
"+",
"build_schema",
"+"
] | 428b44043b879571be03fbab1f3e1800b939fc5e | https://github.com/nesaulov/surrealist/blob/428b44043b879571be03fbab1f3e1800b939fc5e/lib/surrealist/instance_methods.rb#L62-L70 | train |
nesaulov/surrealist | lib/surrealist/serializer.rb | Surrealist.Serializer.build_schema | def build_schema(**args)
if Helper.collection?(object)
build_collection_schema(args)
else
Surrealist.build_schema(instance: self, **args)
end
end | ruby | def build_schema(**args)
if Helper.collection?(object)
build_collection_schema(args)
else
Surrealist.build_schema(instance: self, **args)
end
end | [
"def",
"build_schema",
"(",
"**",
"args",
")",
"if",
"Helper",
".",
"collection?",
"(",
"object",
")",
"build_collection_schema",
"(",
"args",
")",
"else",
"Surrealist",
".",
"build_schema",
"(",
"instance",
":",
"self",
",",
"**",
"args",
")",
"end",
"end"
] | Passes build_schema to Surrealist | [
"Passes",
"build_schema",
"to",
"Surrealist"
] | 428b44043b879571be03fbab1f3e1800b939fc5e | https://github.com/nesaulov/surrealist/blob/428b44043b879571be03fbab1f3e1800b939fc5e/lib/surrealist/serializer.rb#L91-L97 | train |
nesaulov/surrealist | lib/surrealist/serializer.rb | Surrealist.Serializer.build_collection_schema | def build_collection_schema(**args)
object.map { |object| self.class.new(object, context).build_schema(args) }
end | ruby | def build_collection_schema(**args)
object.map { |object| self.class.new(object, context).build_schema(args) }
end | [
"def",
"build_collection_schema",
"(",
"**",
"args",
")",
"object",
".",
"map",
"{",
"|",
"object",
"|",
"self",
".",
"class",
".",
"new",
"(",
"object",
",",
"context",
")",
".",
"build_schema",
"(",
"args",
")",
"}",
"end"
] | Maps collection and builds schema for each instance. | [
"Maps",
"collection",
"and",
"builds",
"schema",
"for",
"each",
"instance",
"."
] | 428b44043b879571be03fbab1f3e1800b939fc5e | https://github.com/nesaulov/surrealist/blob/428b44043b879571be03fbab1f3e1800b939fc5e/lib/surrealist/serializer.rb#L104-L106 | train |
nesaulov/surrealist | lib/surrealist/carrier.rb | Surrealist.Carrier.parameters | def parameters
{ camelize: camelize, include_root: include_root, include_namespaces: include_namespaces,
root: root, namespaces_nesting_level: namespaces_nesting_level }
end | ruby | def parameters
{ camelize: camelize, include_root: include_root, include_namespaces: include_namespaces,
root: root, namespaces_nesting_level: namespaces_nesting_level }
end | [
"def",
"parameters",
"{",
"camelize",
":",
"camelize",
",",
"include_root",
":",
"include_root",
",",
"include_namespaces",
":",
"include_namespaces",
",",
"root",
":",
"root",
",",
"namespaces_nesting_level",
":",
"namespaces_nesting_level",
"}",
"end"
] | Returns all arguments
@return [Hash] | [
"Returns",
"all",
"arguments"
] | 428b44043b879571be03fbab1f3e1800b939fc5e | https://github.com/nesaulov/surrealist/blob/428b44043b879571be03fbab1f3e1800b939fc5e/lib/surrealist/carrier.rb#L55-L58 | train |
nesaulov/surrealist | lib/surrealist/carrier.rb | Surrealist.Carrier.check_booleans! | def check_booleans!
booleans_hash.each do |key, value|
unless BOOLEANS.include?(value)
raise ArgumentError, "Expected `#{key}` to be either true, false or nil, got #{value}"
end
end
end | ruby | def check_booleans!
booleans_hash.each do |key, value|
unless BOOLEANS.include?(value)
raise ArgumentError, "Expected `#{key}` to be either true, false or nil, got #{value}"
end
end
end | [
"def",
"check_booleans!",
"booleans_hash",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"unless",
"BOOLEANS",
".",
"include?",
"(",
"value",
")",
"raise",
"ArgumentError",
",",
"\"Expected `#{key}` to be either true, false or nil, got #{value}\"",
"end",
"end",
"end"
] | Checks all boolean arguments
@raise ArgumentError | [
"Checks",
"all",
"boolean",
"arguments"
] | 428b44043b879571be03fbab1f3e1800b939fc5e | https://github.com/nesaulov/surrealist/blob/428b44043b879571be03fbab1f3e1800b939fc5e/lib/surrealist/carrier.rb#L64-L70 | train |
nesaulov/surrealist | lib/surrealist/carrier.rb | Surrealist.Carrier.check_root! | def check_root!
unless root.nil? || (root.is_a?(String) && !root.strip.empty?) || root.is_a?(Symbol)
Surrealist::ExceptionRaiser.raise_invalid_root!(root)
end
end | ruby | def check_root!
unless root.nil? || (root.is_a?(String) && !root.strip.empty?) || root.is_a?(Symbol)
Surrealist::ExceptionRaiser.raise_invalid_root!(root)
end
end | [
"def",
"check_root!",
"unless",
"root",
".",
"nil?",
"||",
"(",
"root",
".",
"is_a?",
"(",
"String",
")",
"&&",
"!",
"root",
".",
"strip",
".",
"empty?",
")",
"||",
"root",
".",
"is_a?",
"(",
"Symbol",
")",
"Surrealist",
"::",
"ExceptionRaiser",
".",
"raise_invalid_root!",
"(",
"root",
")",
"end",
"end"
] | Checks if root is not nil, a non-empty string, or symbol
@raise ArgumentError | [
"Checks",
"if",
"root",
"is",
"not",
"nil",
"a",
"non",
"-",
"empty",
"string",
"or",
"symbol"
] | 428b44043b879571be03fbab1f3e1800b939fc5e | https://github.com/nesaulov/surrealist/blob/428b44043b879571be03fbab1f3e1800b939fc5e/lib/surrealist/carrier.rb#L87-L91 | train |
nesaulov/surrealist | lib/surrealist/class_methods.rb | Surrealist.ClassMethods.delegate_surrealization_to | def delegate_surrealization_to(klass)
raise TypeError, "Expected type of Class got #{klass.class} instead" unless klass.is_a?(Class)
Surrealist::ExceptionRaiser.raise_invalid_schema_delegation! unless Helper.surrealist?(klass)
hash = Surrealist::VarsHelper.find_schema(klass)
Surrealist::VarsHelper.set_schema(self, hash)
end | ruby | def delegate_surrealization_to(klass)
raise TypeError, "Expected type of Class got #{klass.class} instead" unless klass.is_a?(Class)
Surrealist::ExceptionRaiser.raise_invalid_schema_delegation! unless Helper.surrealist?(klass)
hash = Surrealist::VarsHelper.find_schema(klass)
Surrealist::VarsHelper.set_schema(self, hash)
end | [
"def",
"delegate_surrealization_to",
"(",
"klass",
")",
"raise",
"TypeError",
",",
"\"Expected type of Class got #{klass.class} instead\"",
"unless",
"klass",
".",
"is_a?",
"(",
"Class",
")",
"Surrealist",
"::",
"ExceptionRaiser",
".",
"raise_invalid_schema_delegation!",
"unless",
"Helper",
".",
"surrealist?",
"(",
"klass",
")",
"hash",
"=",
"Surrealist",
"::",
"VarsHelper",
".",
"find_schema",
"(",
"klass",
")",
"Surrealist",
"::",
"VarsHelper",
".",
"set_schema",
"(",
"self",
",",
"hash",
")",
"end"
] | A DSL method to delegate schema in a declarative style. Must reference a valid
class that includes Surrealist
@param [Class] klass
@example DSL usage example
class Host
include Surrealist
json_schema do
{ name: String }
end
def name
'Parent'
end
end
class Guest < Host
delegate_surrealization_to Host
def name
'Child'
end
end
Guest.new.surrealize
# => "{\"name\":\"Child\"}"
# For more examples see README | [
"A",
"DSL",
"method",
"to",
"delegate",
"schema",
"in",
"a",
"declarative",
"style",
".",
"Must",
"reference",
"a",
"valid",
"class",
"that",
"includes",
"Surrealist"
] | 428b44043b879571be03fbab1f3e1800b939fc5e | https://github.com/nesaulov/surrealist/blob/428b44043b879571be03fbab1f3e1800b939fc5e/lib/surrealist/class_methods.rb#L109-L116 | train |
nesaulov/surrealist | lib/surrealist/class_methods.rb | Surrealist.ClassMethods.surrealize_with | def surrealize_with(klass, tag: Surrealist::VarsHelper::DEFAULT_TAG)
if klass < Surrealist::Serializer
Surrealist::VarsHelper.add_serializer(self, klass, tag: tag)
instance_variable_set(VarsHelper::PARENT_VARIABLE, klass.defined_schema)
else
raise ArgumentError, "#{klass} should be inherited from Surrealist::Serializer"
end
end | ruby | def surrealize_with(klass, tag: Surrealist::VarsHelper::DEFAULT_TAG)
if klass < Surrealist::Serializer
Surrealist::VarsHelper.add_serializer(self, klass, tag: tag)
instance_variable_set(VarsHelper::PARENT_VARIABLE, klass.defined_schema)
else
raise ArgumentError, "#{klass} should be inherited from Surrealist::Serializer"
end
end | [
"def",
"surrealize_with",
"(",
"klass",
",",
"tag",
":",
"Surrealist",
"::",
"VarsHelper",
"::",
"DEFAULT_TAG",
")",
"if",
"klass",
"<",
"Surrealist",
"::",
"Serializer",
"Surrealist",
"::",
"VarsHelper",
".",
"add_serializer",
"(",
"self",
",",
"klass",
",",
"tag",
":",
"tag",
")",
"instance_variable_set",
"(",
"VarsHelper",
"::",
"PARENT_VARIABLE",
",",
"klass",
".",
"defined_schema",
")",
"else",
"raise",
"ArgumentError",
",",
"\"#{klass} should be inherited from Surrealist::Serializer\"",
"end",
"end"
] | A DSL method for defining a class that holds serialization logic.
@param [Class] klass a class that should inherit form Surrealist::Serializer
@raise ArgumentError if Surrealist::Serializer is not found in the ancestors chain | [
"A",
"DSL",
"method",
"for",
"defining",
"a",
"class",
"that",
"holds",
"serialization",
"logic",
"."
] | 428b44043b879571be03fbab1f3e1800b939fc5e | https://github.com/nesaulov/surrealist/blob/428b44043b879571be03fbab1f3e1800b939fc5e/lib/surrealist/class_methods.rb#L123-L130 | train |
contribsys/faktory_worker_ruby | lib/faktory/client.rb | Faktory.Client.fetch | def fetch(*queues)
job = nil
transaction do
command("FETCH", *queues)
job = result!
end
JSON.parse(job) if job
end | ruby | def fetch(*queues)
job = nil
transaction do
command("FETCH", *queues)
job = result!
end
JSON.parse(job) if job
end | [
"def",
"fetch",
"(",
"*",
"queues",
")",
"job",
"=",
"nil",
"transaction",
"do",
"command",
"(",
"\"FETCH\"",
",",
"queues",
")",
"job",
"=",
"result!",
"end",
"JSON",
".",
"parse",
"(",
"job",
")",
"if",
"job",
"end"
] | Returns either a job hash or falsy. | [
"Returns",
"either",
"a",
"job",
"hash",
"or",
"falsy",
"."
] | 8b9e4fe278886fba6b8a251ccd5342dd61038ba5 | https://github.com/contribsys/faktory_worker_ruby/blob/8b9e4fe278886fba6b8a251ccd5342dd61038ba5/lib/faktory/client.rb#L83-L90 | train |
contribsys/faktory_worker_ruby | lib/faktory/client.rb | Faktory.Client.beat | def beat
transaction do
command("BEAT", %Q[{"wid":"#{@@random_process_wid}"}])
str = result!
if str == "OK"
str
else
hash = JSON.parse(str)
hash["state"]
end
end
end | ruby | def beat
transaction do
command("BEAT", %Q[{"wid":"#{@@random_process_wid}"}])
str = result!
if str == "OK"
str
else
hash = JSON.parse(str)
hash["state"]
end
end
end | [
"def",
"beat",
"transaction",
"do",
"command",
"(",
"\"BEAT\"",
",",
"%Q[{\"wid\":\"#{@@random_process_wid}\"}]",
")",
"str",
"=",
"result!",
"if",
"str",
"==",
"\"OK\"",
"str",
"else",
"hash",
"=",
"JSON",
".",
"parse",
"(",
"str",
")",
"hash",
"[",
"\"state\"",
"]",
"end",
"end",
"end"
] | Sends a heartbeat to the server, in order to prove this
worker process is still alive.
Return a string signal to process, legal values are "quiet" or "terminate".
The quiet signal is informative: the server won't allow this process to FETCH
any more jobs anyways. | [
"Sends",
"a",
"heartbeat",
"to",
"the",
"server",
"in",
"order",
"to",
"prove",
"this",
"worker",
"process",
"is",
"still",
"alive",
"."
] | 8b9e4fe278886fba6b8a251ccd5342dd61038ba5 | https://github.com/contribsys/faktory_worker_ruby/blob/8b9e4fe278886fba6b8a251ccd5342dd61038ba5/lib/faktory/client.rb#L115-L126 | train |
excid3/simple_discussion | lib/simple_discussion/will_paginate.rb | SimpleDiscussion.BootstrapLinkRenderer.url | def url(page)
@base_url_params ||= begin
url_params = merge_get_params(default_url_params)
merge_optional_params(url_params)
end
url_params = @base_url_params.dup
add_current_page_param(url_params, page)
# Add optional url_builder support
(@options[:url_builder] || @template).url_for(url_params)
end | ruby | def url(page)
@base_url_params ||= begin
url_params = merge_get_params(default_url_params)
merge_optional_params(url_params)
end
url_params = @base_url_params.dup
add_current_page_param(url_params, page)
# Add optional url_builder support
(@options[:url_builder] || @template).url_for(url_params)
end | [
"def",
"url",
"(",
"page",
")",
"@base_url_params",
"||=",
"begin",
"url_params",
"=",
"merge_get_params",
"(",
"default_url_params",
")",
"merge_optional_params",
"(",
"url_params",
")",
"end",
"url_params",
"=",
"@base_url_params",
".",
"dup",
"add_current_page_param",
"(",
"url_params",
",",
"page",
")",
"# Add optional url_builder support",
"(",
"@options",
"[",
":url_builder",
"]",
"||",
"@template",
")",
".",
"url_for",
"(",
"url_params",
")",
"end"
] | This method adds the `url_builder` option so we can pass in the
mounted Rails engine's scope for will_paginate | [
"This",
"method",
"adds",
"the",
"url_builder",
"option",
"so",
"we",
"can",
"pass",
"in",
"the",
"mounted",
"Rails",
"engine",
"s",
"scope",
"for",
"will_paginate"
] | a14181e7eceb64fc69becb2a8f350963f20ed0ff | https://github.com/excid3/simple_discussion/blob/a14181e7eceb64fc69becb2a8f350963f20ed0ff/lib/simple_discussion/will_paginate.rb#L13-L24 | train |
PierreRambaud/gemirro | lib/gemirro/source.rb | Gemirro.Source.fetch_prerelease_versions | def fetch_prerelease_versions
Utils.logger.info(
"Fetching #{Configuration.prerelease_versions_file}" \
" on #{@name} (#{@host})"
)
Http.get(host + '/' + Configuration.prerelease_versions_file).body
end | ruby | def fetch_prerelease_versions
Utils.logger.info(
"Fetching #{Configuration.prerelease_versions_file}" \
" on #{@name} (#{@host})"
)
Http.get(host + '/' + Configuration.prerelease_versions_file).body
end | [
"def",
"fetch_prerelease_versions",
"Utils",
".",
"logger",
".",
"info",
"(",
"\"Fetching #{Configuration.prerelease_versions_file}\"",
"\" on #{@name} (#{@host})\"",
")",
"Http",
".",
"get",
"(",
"host",
"+",
"'/'",
"+",
"Configuration",
".",
"prerelease_versions_file",
")",
".",
"body",
"end"
] | Fetches a list of all the available Gems and their versions.
@return [String] | [
"Fetches",
"a",
"list",
"of",
"all",
"the",
"available",
"Gems",
"and",
"their",
"versions",
"."
] | 5c6b5abb5334ed3beb256f6764bc336e2cf2dc21 | https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/source.rb#L45-L51 | train |
PierreRambaud/gemirro | lib/gemirro/mirror_directory.rb | Gemirro.MirrorDirectory.add_file | def add_file(name, content)
full_path = File.join(@path, name)
file = MirrorFile.new(full_path)
file.write(content)
file
end | ruby | def add_file(name, content)
full_path = File.join(@path, name)
file = MirrorFile.new(full_path)
file.write(content)
file
end | [
"def",
"add_file",
"(",
"name",
",",
"content",
")",
"full_path",
"=",
"File",
".",
"join",
"(",
"@path",
",",
"name",
")",
"file",
"=",
"MirrorFile",
".",
"new",
"(",
"full_path",
")",
"file",
".",
"write",
"(",
"content",
")",
"file",
"end"
] | Creates a new file with the given name and content.
@param [String] name
@param [String] content
@return [Gem::MirrorFile] | [
"Creates",
"a",
"new",
"file",
"with",
"the",
"given",
"name",
"and",
"content",
"."
] | 5c6b5abb5334ed3beb256f6764bc336e2cf2dc21 | https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/mirror_directory.rb#L39-L46 | train |
PierreRambaud/gemirro | lib/gemirro/gems_fetcher.rb | Gemirro.GemsFetcher.versions_for | def versions_for(gem)
available = @versions_file.versions_for(gem.name)
return [available.last] if gem.only_latest?
versions = available.select do |v|
gem.requirement.satisfied_by?(v[0])
end
versions = [available.last] if versions.empty?
versions
end | ruby | def versions_for(gem)
available = @versions_file.versions_for(gem.name)
return [available.last] if gem.only_latest?
versions = available.select do |v|
gem.requirement.satisfied_by?(v[0])
end
versions = [available.last] if versions.empty?
versions
end | [
"def",
"versions_for",
"(",
"gem",
")",
"available",
"=",
"@versions_file",
".",
"versions_for",
"(",
"gem",
".",
"name",
")",
"return",
"[",
"available",
".",
"last",
"]",
"if",
"gem",
".",
"only_latest?",
"versions",
"=",
"available",
".",
"select",
"do",
"|",
"v",
"|",
"gem",
".",
"requirement",
".",
"satisfied_by?",
"(",
"v",
"[",
"0",
"]",
")",
"end",
"versions",
"=",
"[",
"available",
".",
"last",
"]",
"if",
"versions",
".",
"empty?",
"versions",
"end"
] | Returns an Array containing the versions that should be fetched for a
Gem.
@param [Gemirro::Gem] gem
@return [Array] | [
"Returns",
"an",
"Array",
"containing",
"the",
"versions",
"that",
"should",
"be",
"fetched",
"for",
"a",
"Gem",
"."
] | 5c6b5abb5334ed3beb256f6764bc336e2cf2dc21 | https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/gems_fetcher.rb#L55-L66 | train |
PierreRambaud/gemirro | lib/gemirro/gems_fetcher.rb | Gemirro.GemsFetcher.fetch_gemspec | def fetch_gemspec(gem, version)
filename = gem.gemspec_filename(version)
satisfied = if gem.only_latest?
true
else
gem.requirement.satisfied_by?(version)
end
if gemspec_exists?(filename) || !satisfied
Utils.logger.debug("Skipping #{filename}")
return
end
Utils.logger.info("Fetching #{filename}")
fetch_from_source(filename, gem, version, true)
end | ruby | def fetch_gemspec(gem, version)
filename = gem.gemspec_filename(version)
satisfied = if gem.only_latest?
true
else
gem.requirement.satisfied_by?(version)
end
if gemspec_exists?(filename) || !satisfied
Utils.logger.debug("Skipping #{filename}")
return
end
Utils.logger.info("Fetching #{filename}")
fetch_from_source(filename, gem, version, true)
end | [
"def",
"fetch_gemspec",
"(",
"gem",
",",
"version",
")",
"filename",
"=",
"gem",
".",
"gemspec_filename",
"(",
"version",
")",
"satisfied",
"=",
"if",
"gem",
".",
"only_latest?",
"true",
"else",
"gem",
".",
"requirement",
".",
"satisfied_by?",
"(",
"version",
")",
"end",
"if",
"gemspec_exists?",
"(",
"filename",
")",
"||",
"!",
"satisfied",
"Utils",
".",
"logger",
".",
"debug",
"(",
"\"Skipping #{filename}\"",
")",
"return",
"end",
"Utils",
".",
"logger",
".",
"info",
"(",
"\"Fetching #{filename}\"",
")",
"fetch_from_source",
"(",
"filename",
",",
"gem",
",",
"version",
",",
"true",
")",
"end"
] | Tries to download gemspec from a given name and version
@param [Gemirro::Gem] gem
@param [Gem::Version] version
@return [String] | [
"Tries",
"to",
"download",
"gemspec",
"from",
"a",
"given",
"name",
"and",
"version"
] | 5c6b5abb5334ed3beb256f6764bc336e2cf2dc21 | https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/gems_fetcher.rb#L75-L90 | train |
PierreRambaud/gemirro | lib/gemirro/gems_fetcher.rb | Gemirro.GemsFetcher.fetch_gem | def fetch_gem(gem, version)
filename = gem.filename(version)
satisfied = if gem.only_latest?
true
else
gem.requirement.satisfied_by?(version)
end
name = gem.name
if gem_exists?(filename) || ignore_gem?(name, version, gem.platform) ||
!satisfied
Utils.logger.debug("Skipping #{filename}")
return
end
Utils.configuration.ignore_gem(gem.name, version, gem.platform)
Utils.logger.info("Fetching #{filename}")
fetch_from_source(filename, gem, version)
end | ruby | def fetch_gem(gem, version)
filename = gem.filename(version)
satisfied = if gem.only_latest?
true
else
gem.requirement.satisfied_by?(version)
end
name = gem.name
if gem_exists?(filename) || ignore_gem?(name, version, gem.platform) ||
!satisfied
Utils.logger.debug("Skipping #{filename}")
return
end
Utils.configuration.ignore_gem(gem.name, version, gem.platform)
Utils.logger.info("Fetching #{filename}")
fetch_from_source(filename, gem, version)
end | [
"def",
"fetch_gem",
"(",
"gem",
",",
"version",
")",
"filename",
"=",
"gem",
".",
"filename",
"(",
"version",
")",
"satisfied",
"=",
"if",
"gem",
".",
"only_latest?",
"true",
"else",
"gem",
".",
"requirement",
".",
"satisfied_by?",
"(",
"version",
")",
"end",
"name",
"=",
"gem",
".",
"name",
"if",
"gem_exists?",
"(",
"filename",
")",
"||",
"ignore_gem?",
"(",
"name",
",",
"version",
",",
"gem",
".",
"platform",
")",
"||",
"!",
"satisfied",
"Utils",
".",
"logger",
".",
"debug",
"(",
"\"Skipping #{filename}\"",
")",
"return",
"end",
"Utils",
".",
"configuration",
".",
"ignore_gem",
"(",
"gem",
".",
"name",
",",
"version",
",",
"gem",
".",
"platform",
")",
"Utils",
".",
"logger",
".",
"info",
"(",
"\"Fetching #{filename}\"",
")",
"fetch_from_source",
"(",
"filename",
",",
"gem",
",",
"version",
")",
"end"
] | Tries to download the gem file from a given nam and version
@param [Gemirro::Gem] gem
@param [Gem::Version] version
@return [String] | [
"Tries",
"to",
"download",
"the",
"gem",
"file",
"from",
"a",
"given",
"nam",
"and",
"version"
] | 5c6b5abb5334ed3beb256f6764bc336e2cf2dc21 | https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/gems_fetcher.rb#L99-L118 | train |
PierreRambaud/gemirro | lib/gemirro/versions_fetcher.rb | Gemirro.VersionsFetcher.read_file | def read_file(file, prerelease = false)
destination = Gemirro.configuration.destination
file_dst = File.join(destination, file)
unless File.exist?(file_dst)
File.write(file_dst, @source.fetch_versions) unless prerelease
File.write(file_dst, @source.fetch_prerelease_versions) if prerelease
end
File.read(file_dst)
end | ruby | def read_file(file, prerelease = false)
destination = Gemirro.configuration.destination
file_dst = File.join(destination, file)
unless File.exist?(file_dst)
File.write(file_dst, @source.fetch_versions) unless prerelease
File.write(file_dst, @source.fetch_prerelease_versions) if prerelease
end
File.read(file_dst)
end | [
"def",
"read_file",
"(",
"file",
",",
"prerelease",
"=",
"false",
")",
"destination",
"=",
"Gemirro",
".",
"configuration",
".",
"destination",
"file_dst",
"=",
"File",
".",
"join",
"(",
"destination",
",",
"file",
")",
"unless",
"File",
".",
"exist?",
"(",
"file_dst",
")",
"File",
".",
"write",
"(",
"file_dst",
",",
"@source",
".",
"fetch_versions",
")",
"unless",
"prerelease",
"File",
".",
"write",
"(",
"file_dst",
",",
"@source",
".",
"fetch_prerelease_versions",
")",
"if",
"prerelease",
"end",
"File",
".",
"read",
"(",
"file_dst",
")",
"end"
] | Read file if exists otherwise download its from source
@param [String] file name
@param [TrueClass|FalseClass] prerelease Is prerelease or not | [
"Read",
"file",
"if",
"exists",
"otherwise",
"download",
"its",
"from",
"source"
] | 5c6b5abb5334ed3beb256f6764bc336e2cf2dc21 | https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/versions_fetcher.rb#L33-L42 | train |
PierreRambaud/gemirro | lib/gemirro/gem.rb | Gemirro.Gem.filename | def filename(gem_version = nil)
gem_version ||= version.to_s
n = [name, gem_version]
n.push(@platform) if @platform != 'ruby'
"#{n.join('-')}.gem"
end | ruby | def filename(gem_version = nil)
gem_version ||= version.to_s
n = [name, gem_version]
n.push(@platform) if @platform != 'ruby'
"#{n.join('-')}.gem"
end | [
"def",
"filename",
"(",
"gem_version",
"=",
"nil",
")",
"gem_version",
"||=",
"version",
".",
"to_s",
"n",
"=",
"[",
"name",
",",
"gem_version",
"]",
"n",
".",
"push",
"(",
"@platform",
")",
"if",
"@platform",
"!=",
"'ruby'",
"\"#{n.join('-')}.gem\"",
"end"
] | Returns the filename of the gem file.
@param [String] gem_version
@return [String] | [
"Returns",
"the",
"filename",
"of",
"the",
"gem",
"file",
"."
] | 5c6b5abb5334ed3beb256f6764bc336e2cf2dc21 | https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/gem.rb#L87-L92 | train |
PierreRambaud/gemirro | lib/gemirro/gem.rb | Gemirro.Gem.gemspec_filename | def gemspec_filename(gem_version = nil)
gem_version ||= version.to_s
n = [name, gem_version]
n.push(@platform) if @platform != 'ruby'
"#{n.join('-')}.gemspec.rz"
end | ruby | def gemspec_filename(gem_version = nil)
gem_version ||= version.to_s
n = [name, gem_version]
n.push(@platform) if @platform != 'ruby'
"#{n.join('-')}.gemspec.rz"
end | [
"def",
"gemspec_filename",
"(",
"gem_version",
"=",
"nil",
")",
"gem_version",
"||=",
"version",
".",
"to_s",
"n",
"=",
"[",
"name",
",",
"gem_version",
"]",
"n",
".",
"push",
"(",
"@platform",
")",
"if",
"@platform",
"!=",
"'ruby'",
"\"#{n.join('-')}.gemspec.rz\"",
"end"
] | Returns the filename of the gemspec file.
@param [String] gem_version
@return [String] | [
"Returns",
"the",
"filename",
"of",
"the",
"gemspec",
"file",
"."
] | 5c6b5abb5334ed3beb256f6764bc336e2cf2dc21 | https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/gem.rb#L100-L105 | train |
PierreRambaud/gemirro | lib/gemirro/server.rb | Gemirro.Server.fetch_gem | def fetch_gem(resource)
return unless Utils.configuration.fetch_gem
name = File.basename(resource)
result = name.match(URI_REGEXP)
return unless result
gem_name, gem_version, gem_platform, gem_type = result.captures
return unless gem_name && gem_version
begin
gem = Utils.stored_gem(gem_name, gem_version, gem_platform)
gem.gemspec = true if gem_type == GEMSPEC_TYPE
# rubocop:disable Metrics/LineLength
return if Utils.gems_fetcher.gem_exists?(gem.filename(gem_version)) && gem_type == GEM_TYPE
return if Utils.gems_fetcher.gemspec_exists?(gem.gemspec_filename(gem_version)) && gem_type == GEMSPEC_TYPE
# rubocop:enable Metrics/LineLength
Utils.logger
.info("Try to download #{gem_name} with version #{gem_version}")
Utils.gems_fetcher.source.gems.clear
Utils.gems_fetcher.source.gems.push(gem)
Utils.gems_fetcher.fetch
update_indexes if Utils.configuration.update_on_fetch
rescue StandardError => e
Utils.logger.error(e)
end
end | ruby | def fetch_gem(resource)
return unless Utils.configuration.fetch_gem
name = File.basename(resource)
result = name.match(URI_REGEXP)
return unless result
gem_name, gem_version, gem_platform, gem_type = result.captures
return unless gem_name && gem_version
begin
gem = Utils.stored_gem(gem_name, gem_version, gem_platform)
gem.gemspec = true if gem_type == GEMSPEC_TYPE
# rubocop:disable Metrics/LineLength
return if Utils.gems_fetcher.gem_exists?(gem.filename(gem_version)) && gem_type == GEM_TYPE
return if Utils.gems_fetcher.gemspec_exists?(gem.gemspec_filename(gem_version)) && gem_type == GEMSPEC_TYPE
# rubocop:enable Metrics/LineLength
Utils.logger
.info("Try to download #{gem_name} with version #{gem_version}")
Utils.gems_fetcher.source.gems.clear
Utils.gems_fetcher.source.gems.push(gem)
Utils.gems_fetcher.fetch
update_indexes if Utils.configuration.update_on_fetch
rescue StandardError => e
Utils.logger.error(e)
end
end | [
"def",
"fetch_gem",
"(",
"resource",
")",
"return",
"unless",
"Utils",
".",
"configuration",
".",
"fetch_gem",
"name",
"=",
"File",
".",
"basename",
"(",
"resource",
")",
"result",
"=",
"name",
".",
"match",
"(",
"URI_REGEXP",
")",
"return",
"unless",
"result",
"gem_name",
",",
"gem_version",
",",
"gem_platform",
",",
"gem_type",
"=",
"result",
".",
"captures",
"return",
"unless",
"gem_name",
"&&",
"gem_version",
"begin",
"gem",
"=",
"Utils",
".",
"stored_gem",
"(",
"gem_name",
",",
"gem_version",
",",
"gem_platform",
")",
"gem",
".",
"gemspec",
"=",
"true",
"if",
"gem_type",
"==",
"GEMSPEC_TYPE",
"# rubocop:disable Metrics/LineLength",
"return",
"if",
"Utils",
".",
"gems_fetcher",
".",
"gem_exists?",
"(",
"gem",
".",
"filename",
"(",
"gem_version",
")",
")",
"&&",
"gem_type",
"==",
"GEM_TYPE",
"return",
"if",
"Utils",
".",
"gems_fetcher",
".",
"gemspec_exists?",
"(",
"gem",
".",
"gemspec_filename",
"(",
"gem_version",
")",
")",
"&&",
"gem_type",
"==",
"GEMSPEC_TYPE",
"# rubocop:enable Metrics/LineLength",
"Utils",
".",
"logger",
".",
"info",
"(",
"\"Try to download #{gem_name} with version #{gem_version}\"",
")",
"Utils",
".",
"gems_fetcher",
".",
"source",
".",
"gems",
".",
"clear",
"Utils",
".",
"gems_fetcher",
".",
"source",
".",
"gems",
".",
"push",
"(",
"gem",
")",
"Utils",
".",
"gems_fetcher",
".",
"fetch",
"update_indexes",
"if",
"Utils",
".",
"configuration",
".",
"update_on_fetch",
"rescue",
"StandardError",
"=>",
"e",
"Utils",
".",
"logger",
".",
"error",
"(",
"e",
")",
"end",
"end"
] | Try to fetch gem and download its if it's possible, and
build and install indicies.
@param [String] resource
@return [Indexer] | [
"Try",
"to",
"fetch",
"gem",
"and",
"download",
"its",
"if",
"it",
"s",
"possible",
"and",
"build",
"and",
"install",
"indicies",
"."
] | 5c6b5abb5334ed3beb256f6764bc336e2cf2dc21 | https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/server.rb#L129-L157 | train |
PierreRambaud/gemirro | lib/gemirro/server.rb | Gemirro.Server.update_indexes | def update_indexes
indexer = Gemirro::Indexer.new(Utils.configuration.destination)
indexer.only_origin = true
indexer.ui = ::Gem::SilentUI.new
Utils.logger.info('Generating indexes')
indexer.update_index
indexer.updated_gems.each do |gem|
Utils.cache.flush_key(File.basename(gem))
end
rescue SystemExit => e
Utils.logger.info(e.message)
end | ruby | def update_indexes
indexer = Gemirro::Indexer.new(Utils.configuration.destination)
indexer.only_origin = true
indexer.ui = ::Gem::SilentUI.new
Utils.logger.info('Generating indexes')
indexer.update_index
indexer.updated_gems.each do |gem|
Utils.cache.flush_key(File.basename(gem))
end
rescue SystemExit => e
Utils.logger.info(e.message)
end | [
"def",
"update_indexes",
"indexer",
"=",
"Gemirro",
"::",
"Indexer",
".",
"new",
"(",
"Utils",
".",
"configuration",
".",
"destination",
")",
"indexer",
".",
"only_origin",
"=",
"true",
"indexer",
".",
"ui",
"=",
"::",
"Gem",
"::",
"SilentUI",
".",
"new",
"Utils",
".",
"logger",
".",
"info",
"(",
"'Generating indexes'",
")",
"indexer",
".",
"update_index",
"indexer",
".",
"updated_gems",
".",
"each",
"do",
"|",
"gem",
"|",
"Utils",
".",
"cache",
".",
"flush_key",
"(",
"File",
".",
"basename",
"(",
"gem",
")",
")",
"end",
"rescue",
"SystemExit",
"=>",
"e",
"Utils",
".",
"logger",
".",
"info",
"(",
"e",
".",
"message",
")",
"end"
] | Update indexes files
@return [Indexer] | [
"Update",
"indexes",
"files"
] | 5c6b5abb5334ed3beb256f6764bc336e2cf2dc21 | https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/server.rb#L164-L176 | train |
PierreRambaud/gemirro | lib/gemirro/server.rb | Gemirro.Server.query_gems_list | def query_gems_list
Utils.gems_collection(false) # load collection
gems = Parallel.map(query_gems, in_threads: 4) do |query_gem|
gem_dependencies(query_gem)
end
gems.flatten!
gems.reject!(&:empty?)
gems
end | ruby | def query_gems_list
Utils.gems_collection(false) # load collection
gems = Parallel.map(query_gems, in_threads: 4) do |query_gem|
gem_dependencies(query_gem)
end
gems.flatten!
gems.reject!(&:empty?)
gems
end | [
"def",
"query_gems_list",
"Utils",
".",
"gems_collection",
"(",
"false",
")",
"# load collection",
"gems",
"=",
"Parallel",
".",
"map",
"(",
"query_gems",
",",
"in_threads",
":",
"4",
")",
"do",
"|",
"query_gem",
"|",
"gem_dependencies",
"(",
"query_gem",
")",
"end",
"gems",
".",
"flatten!",
"gems",
".",
"reject!",
"(",
":empty?",
")",
"gems",
"end"
] | Return gems list from query params
@return [Array] | [
"Return",
"gems",
"list",
"from",
"query",
"params"
] | 5c6b5abb5334ed3beb256f6764bc336e2cf2dc21 | https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/server.rb#L192-L201 | train |
PierreRambaud/gemirro | lib/gemirro/server.rb | Gemirro.Server.gem_dependencies | def gem_dependencies(gem_name)
Utils.cache.cache(gem_name) do
gems = Utils.gems_collection(false)
gem_collection = gems.find_by_name(gem_name)
return '' if gem_collection.nil?
gem_collection = Parallel.map(gem_collection, in_threads: 4) do |gem|
[gem, spec_for(gem.name, gem.number, gem.platform)]
end
gem_collection.reject! do |_, spec|
spec.nil?
end
Parallel.map(gem_collection, in_threads: 4) do |gem, spec|
dependencies = spec.dependencies.select do |d|
d.type == :runtime
end
dependencies = Parallel.map(dependencies, in_threads: 4) do |d|
[d.name.is_a?(Array) ? d.name.first : d.name, d.requirement.to_s]
end
{
name: gem.name,
number: gem.number,
platform: gem.platform,
dependencies: dependencies
}
end
end
end | ruby | def gem_dependencies(gem_name)
Utils.cache.cache(gem_name) do
gems = Utils.gems_collection(false)
gem_collection = gems.find_by_name(gem_name)
return '' if gem_collection.nil?
gem_collection = Parallel.map(gem_collection, in_threads: 4) do |gem|
[gem, spec_for(gem.name, gem.number, gem.platform)]
end
gem_collection.reject! do |_, spec|
spec.nil?
end
Parallel.map(gem_collection, in_threads: 4) do |gem, spec|
dependencies = spec.dependencies.select do |d|
d.type == :runtime
end
dependencies = Parallel.map(dependencies, in_threads: 4) do |d|
[d.name.is_a?(Array) ? d.name.first : d.name, d.requirement.to_s]
end
{
name: gem.name,
number: gem.number,
platform: gem.platform,
dependencies: dependencies
}
end
end
end | [
"def",
"gem_dependencies",
"(",
"gem_name",
")",
"Utils",
".",
"cache",
".",
"cache",
"(",
"gem_name",
")",
"do",
"gems",
"=",
"Utils",
".",
"gems_collection",
"(",
"false",
")",
"gem_collection",
"=",
"gems",
".",
"find_by_name",
"(",
"gem_name",
")",
"return",
"''",
"if",
"gem_collection",
".",
"nil?",
"gem_collection",
"=",
"Parallel",
".",
"map",
"(",
"gem_collection",
",",
"in_threads",
":",
"4",
")",
"do",
"|",
"gem",
"|",
"[",
"gem",
",",
"spec_for",
"(",
"gem",
".",
"name",
",",
"gem",
".",
"number",
",",
"gem",
".",
"platform",
")",
"]",
"end",
"gem_collection",
".",
"reject!",
"do",
"|",
"_",
",",
"spec",
"|",
"spec",
".",
"nil?",
"end",
"Parallel",
".",
"map",
"(",
"gem_collection",
",",
"in_threads",
":",
"4",
")",
"do",
"|",
"gem",
",",
"spec",
"|",
"dependencies",
"=",
"spec",
".",
"dependencies",
".",
"select",
"do",
"|",
"d",
"|",
"d",
".",
"type",
"==",
":runtime",
"end",
"dependencies",
"=",
"Parallel",
".",
"map",
"(",
"dependencies",
",",
"in_threads",
":",
"4",
")",
"do",
"|",
"d",
"|",
"[",
"d",
".",
"name",
".",
"is_a?",
"(",
"Array",
")",
"?",
"d",
".",
"name",
".",
"first",
":",
"d",
".",
"name",
",",
"d",
".",
"requirement",
".",
"to_s",
"]",
"end",
"{",
"name",
":",
"gem",
".",
"name",
",",
"number",
":",
"gem",
".",
"number",
",",
"platform",
":",
"gem",
".",
"platform",
",",
"dependencies",
":",
"dependencies",
"}",
"end",
"end",
"end"
] | List of versions and dependencies of each version
from a gem name.
@return [Array] | [
"List",
"of",
"versions",
"and",
"dependencies",
"of",
"each",
"version",
"from",
"a",
"gem",
"name",
"."
] | 5c6b5abb5334ed3beb256f6764bc336e2cf2dc21 | https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/server.rb#L209-L240 | train |
PierreRambaud/gemirro | lib/gemirro/indexer.rb | Gemirro.Indexer.download_from_source | def download_from_source(file)
source_host = Gemirro.configuration.source.host
Utils.logger.info("Download from source: #{file}")
resp = Http.get("#{source_host}/#{File.basename(file)}")
return unless resp.code == 200
resp.body
end | ruby | def download_from_source(file)
source_host = Gemirro.configuration.source.host
Utils.logger.info("Download from source: #{file}")
resp = Http.get("#{source_host}/#{File.basename(file)}")
return unless resp.code == 200
resp.body
end | [
"def",
"download_from_source",
"(",
"file",
")",
"source_host",
"=",
"Gemirro",
".",
"configuration",
".",
"source",
".",
"host",
"Utils",
".",
"logger",
".",
"info",
"(",
"\"Download from source: #{file}\"",
")",
"resp",
"=",
"Http",
".",
"get",
"(",
"\"#{source_host}/#{File.basename(file)}\"",
")",
"return",
"unless",
"resp",
".",
"code",
"==",
"200",
"resp",
".",
"body",
"end"
] | Download file from source
@param [String] file File path
@return [String] | [
"Download",
"file",
"from",
"source"
] | 5c6b5abb5334ed3beb256f6764bc336e2cf2dc21 | https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/indexer.rb#L134-L140 | train |
PierreRambaud/gemirro | lib/gemirro/indexer.rb | Gemirro.Indexer.map_gems_to_specs | def map_gems_to_specs(gems)
gems.map.with_index do |gemfile, index|
# rubocop:disable Metrics/LineLength
Utils.logger.info("[#{index + 1}/#{gems.size}]: Processing #{gemfile.split('/')[-1]}")
# rubocop:enable Metrics/LineLength
if File.size(gemfile).zero?
Utils.logger.warn("Skipping zero-length gem: #{gemfile}")
next
end
begin
spec = if ::Gem::Package.respond_to? :open
::Gem::Package
.open(File.open(gemfile, 'rb'), 'r', &:metadata)
else
::Gem::Package.new(gemfile).spec
end
spec.loaded_from = gemfile
# HACK: fuck this shit - borks all tests that use pl1
if File.basename(gemfile, '.gem') != spec.original_name
exp = spec.full_name
exp << " (#{spec.original_name})" if
spec.original_name != spec.full_name
msg = "Skipping misnamed gem: #{gemfile} should be named #{exp}"
Utils.logger.warn(msg)
next
end
version = spec.version.version
unless version =~ /^\d+\.\d+\.\d+.*/
msg = "Skipping gem #{spec.full_name} - invalid version #{version}"
Utils.logger.warn(msg)
next
end
if ::Gem::VERSION >= '2.5.0'
spec.abbreviate
spec.sanitize
else
abbreviate spec
sanitize spec
end
spec
rescue SignalException
msg = 'Received signal, exiting'
Utils.logger.error(msg)
raise
rescue StandardError => e
msg = ["Unable to process #{gemfile}",
"#{e.message} (#{e.class})",
"\t#{e.backtrace.join "\n\t"}"].join("\n")
Utils.logger.debug(msg)
end
end.compact
end | ruby | def map_gems_to_specs(gems)
gems.map.with_index do |gemfile, index|
# rubocop:disable Metrics/LineLength
Utils.logger.info("[#{index + 1}/#{gems.size}]: Processing #{gemfile.split('/')[-1]}")
# rubocop:enable Metrics/LineLength
if File.size(gemfile).zero?
Utils.logger.warn("Skipping zero-length gem: #{gemfile}")
next
end
begin
spec = if ::Gem::Package.respond_to? :open
::Gem::Package
.open(File.open(gemfile, 'rb'), 'r', &:metadata)
else
::Gem::Package.new(gemfile).spec
end
spec.loaded_from = gemfile
# HACK: fuck this shit - borks all tests that use pl1
if File.basename(gemfile, '.gem') != spec.original_name
exp = spec.full_name
exp << " (#{spec.original_name})" if
spec.original_name != spec.full_name
msg = "Skipping misnamed gem: #{gemfile} should be named #{exp}"
Utils.logger.warn(msg)
next
end
version = spec.version.version
unless version =~ /^\d+\.\d+\.\d+.*/
msg = "Skipping gem #{spec.full_name} - invalid version #{version}"
Utils.logger.warn(msg)
next
end
if ::Gem::VERSION >= '2.5.0'
spec.abbreviate
spec.sanitize
else
abbreviate spec
sanitize spec
end
spec
rescue SignalException
msg = 'Received signal, exiting'
Utils.logger.error(msg)
raise
rescue StandardError => e
msg = ["Unable to process #{gemfile}",
"#{e.message} (#{e.class})",
"\t#{e.backtrace.join "\n\t"}"].join("\n")
Utils.logger.debug(msg)
end
end.compact
end | [
"def",
"map_gems_to_specs",
"(",
"gems",
")",
"gems",
".",
"map",
".",
"with_index",
"do",
"|",
"gemfile",
",",
"index",
"|",
"# rubocop:disable Metrics/LineLength",
"Utils",
".",
"logger",
".",
"info",
"(",
"\"[#{index + 1}/#{gems.size}]: Processing #{gemfile.split('/')[-1]}\"",
")",
"# rubocop:enable Metrics/LineLength",
"if",
"File",
".",
"size",
"(",
"gemfile",
")",
".",
"zero?",
"Utils",
".",
"logger",
".",
"warn",
"(",
"\"Skipping zero-length gem: #{gemfile}\"",
")",
"next",
"end",
"begin",
"spec",
"=",
"if",
"::",
"Gem",
"::",
"Package",
".",
"respond_to?",
":open",
"::",
"Gem",
"::",
"Package",
".",
"open",
"(",
"File",
".",
"open",
"(",
"gemfile",
",",
"'rb'",
")",
",",
"'r'",
",",
":metadata",
")",
"else",
"::",
"Gem",
"::",
"Package",
".",
"new",
"(",
"gemfile",
")",
".",
"spec",
"end",
"spec",
".",
"loaded_from",
"=",
"gemfile",
"# HACK: fuck this shit - borks all tests that use pl1",
"if",
"File",
".",
"basename",
"(",
"gemfile",
",",
"'.gem'",
")",
"!=",
"spec",
".",
"original_name",
"exp",
"=",
"spec",
".",
"full_name",
"exp",
"<<",
"\" (#{spec.original_name})\"",
"if",
"spec",
".",
"original_name",
"!=",
"spec",
".",
"full_name",
"msg",
"=",
"\"Skipping misnamed gem: #{gemfile} should be named #{exp}\"",
"Utils",
".",
"logger",
".",
"warn",
"(",
"msg",
")",
"next",
"end",
"version",
"=",
"spec",
".",
"version",
".",
"version",
"unless",
"version",
"=~",
"/",
"\\d",
"\\.",
"\\d",
"\\.",
"\\d",
"/",
"msg",
"=",
"\"Skipping gem #{spec.full_name} - invalid version #{version}\"",
"Utils",
".",
"logger",
".",
"warn",
"(",
"msg",
")",
"next",
"end",
"if",
"::",
"Gem",
"::",
"VERSION",
">=",
"'2.5.0'",
"spec",
".",
"abbreviate",
"spec",
".",
"sanitize",
"else",
"abbreviate",
"spec",
"sanitize",
"spec",
"end",
"spec",
"rescue",
"SignalException",
"msg",
"=",
"'Received signal, exiting'",
"Utils",
".",
"logger",
".",
"error",
"(",
"msg",
")",
"raise",
"rescue",
"StandardError",
"=>",
"e",
"msg",
"=",
"[",
"\"Unable to process #{gemfile}\"",
",",
"\"#{e.message} (#{e.class})\"",
",",
"\"\\t#{e.backtrace.join \"\\n\\t\"}\"",
"]",
".",
"join",
"(",
"\"\\n\"",
")",
"Utils",
".",
"logger",
".",
"debug",
"(",
"msg",
")",
"end",
"end",
".",
"compact",
"end"
] | Map gems file to specs
@param [Array] gems Gems list
@return [Array] | [
"Map",
"gems",
"file",
"to",
"specs"
] | 5c6b5abb5334ed3beb256f6764bc336e2cf2dc21 | https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/indexer.rb#L179-L237 | train |
PierreRambaud/gemirro | lib/gemirro/gem_version_collection.rb | Gemirro.GemVersionCollection.by_name | def by_name(&block)
if @grouped.nil?
@grouped = @gems.group_by(&:name).map do |name, collection|
[name, GemVersionCollection.new(collection)]
end
@grouped.reject! do |name, _collection|
name.nil?
end
@grouped.sort_by! do |name, _collection|
name.downcase
end
end
if block_given?
@grouped.each(&block)
else
@grouped
end
end | ruby | def by_name(&block)
if @grouped.nil?
@grouped = @gems.group_by(&:name).map do |name, collection|
[name, GemVersionCollection.new(collection)]
end
@grouped.reject! do |name, _collection|
name.nil?
end
@grouped.sort_by! do |name, _collection|
name.downcase
end
end
if block_given?
@grouped.each(&block)
else
@grouped
end
end | [
"def",
"by_name",
"(",
"&",
"block",
")",
"if",
"@grouped",
".",
"nil?",
"@grouped",
"=",
"@gems",
".",
"group_by",
"(",
":name",
")",
".",
"map",
"do",
"|",
"name",
",",
"collection",
"|",
"[",
"name",
",",
"GemVersionCollection",
".",
"new",
"(",
"collection",
")",
"]",
"end",
"@grouped",
".",
"reject!",
"do",
"|",
"name",
",",
"_collection",
"|",
"name",
".",
"nil?",
"end",
"@grouped",
".",
"sort_by!",
"do",
"|",
"name",
",",
"_collection",
"|",
"name",
".",
"downcase",
"end",
"end",
"if",
"block_given?",
"@grouped",
".",
"each",
"(",
"block",
")",
"else",
"@grouped",
"end",
"end"
] | Group gems by name
@param [Proc] block
@return [Array] | [
"Group",
"gems",
"by",
"name"
] | 5c6b5abb5334ed3beb256f6764bc336e2cf2dc21 | https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/gem_version_collection.rb#L71-L91 | train |
PierreRambaud/gemirro | lib/gemirro/gem_version_collection.rb | Gemirro.GemVersionCollection.find_by_name | def find_by_name(gemname)
gem = by_name.select do |name, _collection|
name == gemname
end
gem.first.last if gem.any?
end | ruby | def find_by_name(gemname)
gem = by_name.select do |name, _collection|
name == gemname
end
gem.first.last if gem.any?
end | [
"def",
"find_by_name",
"(",
"gemname",
")",
"gem",
"=",
"by_name",
".",
"select",
"do",
"|",
"name",
",",
"_collection",
"|",
"name",
"==",
"gemname",
"end",
"gem",
".",
"first",
".",
"last",
"if",
"gem",
".",
"any?",
"end"
] | Find gem by name
@param [String] gemname
@return [Array] | [
"Find",
"gem",
"by",
"name"
] | 5c6b5abb5334ed3beb256f6764bc336e2cf2dc21 | https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/gem_version_collection.rb#L99-L105 | train |
PierreRambaud/gemirro | lib/gemirro/configuration.rb | Gemirro.Configuration.logger_level= | def logger_level=(level)
logger.level = LOGGER_LEVEL[level] if LOGGER_LEVEL.key?(level)
logger
end | ruby | def logger_level=(level)
logger.level = LOGGER_LEVEL[level] if LOGGER_LEVEL.key?(level)
logger
end | [
"def",
"logger_level",
"=",
"(",
"level",
")",
"logger",
".",
"level",
"=",
"LOGGER_LEVEL",
"[",
"level",
"]",
"if",
"LOGGER_LEVEL",
".",
"key?",
"(",
"level",
")",
"logger",
"end"
] | Set log level
@param [string]
@return [Logger] | [
"Set",
"log",
"level"
] | 5c6b5abb5334ed3beb256f6764bc336e2cf2dc21 | https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/configuration.rb#L53-L56 | train |
PierreRambaud/gemirro | lib/gemirro/configuration.rb | Gemirro.Configuration.ignore_gem | def ignore_gem(name, version, platform)
ignored_gems[platform] ||= {}
ignored_gems[platform][name] ||= []
ignored_gems[platform][name] << version
end | ruby | def ignore_gem(name, version, platform)
ignored_gems[platform] ||= {}
ignored_gems[platform][name] ||= []
ignored_gems[platform][name] << version
end | [
"def",
"ignore_gem",
"(",
"name",
",",
"version",
",",
"platform",
")",
"ignored_gems",
"[",
"platform",
"]",
"||=",
"{",
"}",
"ignored_gems",
"[",
"platform",
"]",
"[",
"name",
"]",
"||=",
"[",
"]",
"ignored_gems",
"[",
"platform",
"]",
"[",
"name",
"]",
"<<",
"version",
"end"
] | Adds a Gem to the list of Gems to ignore.
@param [String] name
@param [String] version | [
"Adds",
"a",
"Gem",
"to",
"the",
"list",
"of",
"Gems",
"to",
"ignore",
"."
] | 5c6b5abb5334ed3beb256f6764bc336e2cf2dc21 | https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/configuration.rb#L174-L178 | train |
PierreRambaud/gemirro | lib/gemirro/configuration.rb | Gemirro.Configuration.ignore_gem? | def ignore_gem?(name, version, platform)
if ignored_gems[platform][name]
ignored_gems[platform][name].include?(version)
else
false
end
end | ruby | def ignore_gem?(name, version, platform)
if ignored_gems[platform][name]
ignored_gems[platform][name].include?(version)
else
false
end
end | [
"def",
"ignore_gem?",
"(",
"name",
",",
"version",
",",
"platform",
")",
"if",
"ignored_gems",
"[",
"platform",
"]",
"[",
"name",
"]",
"ignored_gems",
"[",
"platform",
"]",
"[",
"name",
"]",
".",
"include?",
"(",
"version",
")",
"else",
"false",
"end",
"end"
] | Checks if a Gem should be ignored.
@param [String] name
@param [String] version
@return [TrueClass|FalseClass] | [
"Checks",
"if",
"a",
"Gem",
"should",
"be",
"ignored",
"."
] | 5c6b5abb5334ed3beb256f6764bc336e2cf2dc21 | https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/configuration.rb#L187-L193 | train |
PierreRambaud/gemirro | lib/gemirro/configuration.rb | Gemirro.Configuration.define_source | def define_source(name, url, &block)
source = Source.new(name, url)
source.instance_eval(&block)
@source = source
end | ruby | def define_source(name, url, &block)
source = Source.new(name, url)
source.instance_eval(&block)
@source = source
end | [
"def",
"define_source",
"(",
"name",
",",
"url",
",",
"&",
"block",
")",
"source",
"=",
"Source",
".",
"new",
"(",
"name",
",",
"url",
")",
"source",
".",
"instance_eval",
"(",
"block",
")",
"@source",
"=",
"source",
"end"
] | Define the source to mirror.
@param [String] name
@param [String] url
@param [Proc] block | [
"Define",
"the",
"source",
"to",
"mirror",
"."
] | 5c6b5abb5334ed3beb256f6764bc336e2cf2dc21 | https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/configuration.rb#L202-L207 | train |
PierreRambaud/gemirro | lib/gemirro/mirror_file.rb | Gemirro.MirrorFile.read | def read
handle = File.open(@path, 'r')
content = handle.read
handle.close
content
end | ruby | def read
handle = File.open(@path, 'r')
content = handle.read
handle.close
content
end | [
"def",
"read",
"handle",
"=",
"File",
".",
"open",
"(",
"@path",
",",
"'r'",
")",
"content",
"=",
"handle",
".",
"read",
"handle",
".",
"close",
"content",
"end"
] | Reads the content of the current file.
@return [String] | [
"Reads",
"the",
"content",
"of",
"the",
"current",
"file",
"."
] | 5c6b5abb5334ed3beb256f6764bc336e2cf2dc21 | https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/mirror_file.rb#L38-L45 | train |
propublica/upton | lib/upton.rb | Upton.Scraper.next_index_page_url | def next_index_page_url(url, pagination_index)
return url unless @paginated
if pagination_index > @pagination_max_pages
puts "Exceeded pagination limit of #{@pagination_max_pages}" if @verbose
EMPTY_STRING
else
uri = URI.parse(url)
query = uri.query ? Hash[URI.decode_www_form(uri.query)] : {}
# update the pagination query string parameter
query[@pagination_param] = pagination_index
uri.query = URI.encode_www_form(query)
puts "Next index pagination url is #{uri}" if @verbose
uri.to_s
end
end | ruby | def next_index_page_url(url, pagination_index)
return url unless @paginated
if pagination_index > @pagination_max_pages
puts "Exceeded pagination limit of #{@pagination_max_pages}" if @verbose
EMPTY_STRING
else
uri = URI.parse(url)
query = uri.query ? Hash[URI.decode_www_form(uri.query)] : {}
# update the pagination query string parameter
query[@pagination_param] = pagination_index
uri.query = URI.encode_www_form(query)
puts "Next index pagination url is #{uri}" if @verbose
uri.to_s
end
end | [
"def",
"next_index_page_url",
"(",
"url",
",",
"pagination_index",
")",
"return",
"url",
"unless",
"@paginated",
"if",
"pagination_index",
">",
"@pagination_max_pages",
"puts",
"\"Exceeded pagination limit of #{@pagination_max_pages}\"",
"if",
"@verbose",
"EMPTY_STRING",
"else",
"uri",
"=",
"URI",
".",
"parse",
"(",
"url",
")",
"query",
"=",
"uri",
".",
"query",
"?",
"Hash",
"[",
"URI",
".",
"decode_www_form",
"(",
"uri",
".",
"query",
")",
"]",
":",
"{",
"}",
"# update the pagination query string parameter",
"query",
"[",
"@pagination_param",
"]",
"=",
"pagination_index",
"uri",
".",
"query",
"=",
"URI",
".",
"encode_www_form",
"(",
"query",
")",
"puts",
"\"Next index pagination url is #{uri}\"",
"if",
"@verbose",
"uri",
".",
"to_s",
"end",
"end"
] | Return the next URL to scrape, given the current URL and its index.
Recursion stops if the fetching URL returns an empty string or an error.
If @paginated is not set (the default), this method returns an empty string.
If @paginated is set, this method will return the next pagination URL
to scrape using @pagination_param and the pagination_index.
If the pagination_index is greater than @pagination_max_pages, then the
method will return an empty string.
Override this method to handle pagination is an alternative way
e.g. next_index_page_url("http://whatever.com/articles?page=1", 2)
ought to return "http://whatever.com/articles?page=2" | [
"Return",
"the",
"next",
"URL",
"to",
"scrape",
"given",
"the",
"current",
"URL",
"and",
"its",
"index",
"."
] | 29c90206317a6a8327a59f63d8117c56db6395eb | https://github.com/propublica/upton/blob/29c90206317a6a8327a59f63d8117c56db6395eb/lib/upton.rb#L149-L164 | train |
propublica/upton | lib/upton.rb | Upton.Scraper.scrape_to_csv | def scrape_to_csv filename, &blk
require 'csv'
self.url_array = self.get_index unless self.url_array
CSV.open filename, 'wb' do |csv|
#this is a conscious choice: each document is a list of things, either single elements or rows (as lists).
self.scrape_from_list(self.url_array, blk).compact.each do |document|
if document[0].respond_to? :map
document.each{|row| csv << row }
else
csv << document
end
end
#self.scrape_from_list(self.url_array, blk).compact.each{|document| csv << document }
end
end | ruby | def scrape_to_csv filename, &blk
require 'csv'
self.url_array = self.get_index unless self.url_array
CSV.open filename, 'wb' do |csv|
#this is a conscious choice: each document is a list of things, either single elements or rows (as lists).
self.scrape_from_list(self.url_array, blk).compact.each do |document|
if document[0].respond_to? :map
document.each{|row| csv << row }
else
csv << document
end
end
#self.scrape_from_list(self.url_array, blk).compact.each{|document| csv << document }
end
end | [
"def",
"scrape_to_csv",
"filename",
",",
"&",
"blk",
"require",
"'csv'",
"self",
".",
"url_array",
"=",
"self",
".",
"get_index",
"unless",
"self",
".",
"url_array",
"CSV",
".",
"open",
"filename",
",",
"'wb'",
"do",
"|",
"csv",
"|",
"#this is a conscious choice: each document is a list of things, either single elements or rows (as lists).",
"self",
".",
"scrape_from_list",
"(",
"self",
".",
"url_array",
",",
"blk",
")",
".",
"compact",
".",
"each",
"do",
"|",
"document",
"|",
"if",
"document",
"[",
"0",
"]",
".",
"respond_to?",
":map",
"document",
".",
"each",
"{",
"|",
"row",
"|",
"csv",
"<<",
"row",
"}",
"else",
"csv",
"<<",
"document",
"end",
"end",
"#self.scrape_from_list(self.url_array, blk).compact.each{|document| csv << document }",
"end",
"end"
] | Writes the scraped result to a CSV at the given filename. | [
"Writes",
"the",
"scraped",
"result",
"to",
"a",
"CSV",
"at",
"the",
"given",
"filename",
"."
] | 29c90206317a6a8327a59f63d8117c56db6395eb | https://github.com/propublica/upton/blob/29c90206317a6a8327a59f63d8117c56db6395eb/lib/upton.rb#L169-L183 | train |
propublica/upton | lib/upton.rb | Upton.Scraper.get_page | def get_page(url, stash=false, options={})
return EMPTY_STRING if url.nil? || url.empty? #url is nil if the <a> lacks an `href` attribute.
global_options = {
:cache => stash,
:verbose => @verbose
}
if @readable_filenames
global_options[:readable_filenames] = true
end
if @stash_folder
global_options[:readable_filenames] = true
global_options[:cache_location] = @stash_folder
end
resp_and_cache = Downloader.new(url, global_options.merge(options)).get
if resp_and_cache[:from_resource]
puts "sleeping #{@sleep_time_between_requests} secs" if @verbose
sleep @sleep_time_between_requests
end
resp_and_cache[:resp]
end | ruby | def get_page(url, stash=false, options={})
return EMPTY_STRING if url.nil? || url.empty? #url is nil if the <a> lacks an `href` attribute.
global_options = {
:cache => stash,
:verbose => @verbose
}
if @readable_filenames
global_options[:readable_filenames] = true
end
if @stash_folder
global_options[:readable_filenames] = true
global_options[:cache_location] = @stash_folder
end
resp_and_cache = Downloader.new(url, global_options.merge(options)).get
if resp_and_cache[:from_resource]
puts "sleeping #{@sleep_time_between_requests} secs" if @verbose
sleep @sleep_time_between_requests
end
resp_and_cache[:resp]
end | [
"def",
"get_page",
"(",
"url",
",",
"stash",
"=",
"false",
",",
"options",
"=",
"{",
"}",
")",
"return",
"EMPTY_STRING",
"if",
"url",
".",
"nil?",
"||",
"url",
".",
"empty?",
"#url is nil if the <a> lacks an `href` attribute.",
"global_options",
"=",
"{",
":cache",
"=>",
"stash",
",",
":verbose",
"=>",
"@verbose",
"}",
"if",
"@readable_filenames",
"global_options",
"[",
":readable_filenames",
"]",
"=",
"true",
"end",
"if",
"@stash_folder",
"global_options",
"[",
":readable_filenames",
"]",
"=",
"true",
"global_options",
"[",
":cache_location",
"]",
"=",
"@stash_folder",
"end",
"resp_and_cache",
"=",
"Downloader",
".",
"new",
"(",
"url",
",",
"global_options",
".",
"merge",
"(",
"options",
")",
")",
".",
"get",
"if",
"resp_and_cache",
"[",
":from_resource",
"]",
"puts",
"\"sleeping #{@sleep_time_between_requests} secs\"",
"if",
"@verbose",
"sleep",
"@sleep_time_between_requests",
"end",
"resp_and_cache",
"[",
":resp",
"]",
"end"
] | Handles getting pages with Downlader, which handles stashing. | [
"Handles",
"getting",
"pages",
"with",
"Downlader",
"which",
"handles",
"stashing",
"."
] | 29c90206317a6a8327a59f63d8117c56db6395eb | https://github.com/propublica/upton/blob/29c90206317a6a8327a59f63d8117c56db6395eb/lib/upton.rb#L206-L225 | train |
propublica/upton | lib/upton.rb | Upton.Scraper.get_instance | def get_instance(url, pagination_index=0, options={})
resps = [self.get_page(url, @debug, options)]
pagination_index = pagination_index.to_i
prev_url = url
while !resps.last.empty?
next_url = self.next_instance_page_url(url, pagination_index + 1)
break if next_url == prev_url || next_url.empty?
next_resp = self.get_page(next_url, @debug, options)
prev_url = next_url
resps << next_resp
end
resps
end | ruby | def get_instance(url, pagination_index=0, options={})
resps = [self.get_page(url, @debug, options)]
pagination_index = pagination_index.to_i
prev_url = url
while !resps.last.empty?
next_url = self.next_instance_page_url(url, pagination_index + 1)
break if next_url == prev_url || next_url.empty?
next_resp = self.get_page(next_url, @debug, options)
prev_url = next_url
resps << next_resp
end
resps
end | [
"def",
"get_instance",
"(",
"url",
",",
"pagination_index",
"=",
"0",
",",
"options",
"=",
"{",
"}",
")",
"resps",
"=",
"[",
"self",
".",
"get_page",
"(",
"url",
",",
"@debug",
",",
"options",
")",
"]",
"pagination_index",
"=",
"pagination_index",
".",
"to_i",
"prev_url",
"=",
"url",
"while",
"!",
"resps",
".",
"last",
".",
"empty?",
"next_url",
"=",
"self",
".",
"next_instance_page_url",
"(",
"url",
",",
"pagination_index",
"+",
"1",
")",
"break",
"if",
"next_url",
"==",
"prev_url",
"||",
"next_url",
".",
"empty?",
"next_resp",
"=",
"self",
".",
"get_page",
"(",
"next_url",
",",
"@debug",
",",
"options",
")",
"prev_url",
"=",
"next_url",
"resps",
"<<",
"next_resp",
"end",
"resps",
"end"
] | Returns the instance at `url`.
If the page is stashed, returns that, otherwise, fetches it from the web.
If an instance is paginated, returns the concatenated output of each
page, e.g. if a news article has two pages. | [
"Returns",
"the",
"instance",
"at",
"url",
"."
] | 29c90206317a6a8327a59f63d8117c56db6395eb | https://github.com/propublica/upton/blob/29c90206317a6a8327a59f63d8117c56db6395eb/lib/upton.rb#L321-L334 | train |
propublica/upton | lib/upton.rb | Upton.Scraper.scrape_from_list | def scrape_from_list(list, blk)
puts "Scraping #{list.size} instances" if @verbose
list.each_with_index.map do |instance_url, instance_index|
instance_resps = get_instance instance_url, nil, :instance_index => instance_index
instance_resps.each_with_index.map do |instance_resp, pagination_index|
blk.call(instance_resp, instance_url, instance_index, pagination_index)
end
end.flatten(1)
end | ruby | def scrape_from_list(list, blk)
puts "Scraping #{list.size} instances" if @verbose
list.each_with_index.map do |instance_url, instance_index|
instance_resps = get_instance instance_url, nil, :instance_index => instance_index
instance_resps.each_with_index.map do |instance_resp, pagination_index|
blk.call(instance_resp, instance_url, instance_index, pagination_index)
end
end.flatten(1)
end | [
"def",
"scrape_from_list",
"(",
"list",
",",
"blk",
")",
"puts",
"\"Scraping #{list.size} instances\"",
"if",
"@verbose",
"list",
".",
"each_with_index",
".",
"map",
"do",
"|",
"instance_url",
",",
"instance_index",
"|",
"instance_resps",
"=",
"get_instance",
"instance_url",
",",
"nil",
",",
":instance_index",
"=>",
"instance_index",
"instance_resps",
".",
"each_with_index",
".",
"map",
"do",
"|",
"instance_resp",
",",
"pagination_index",
"|",
"blk",
".",
"call",
"(",
"instance_resp",
",",
"instance_url",
",",
"instance_index",
",",
"pagination_index",
")",
"end",
"end",
".",
"flatten",
"(",
"1",
")",
"end"
] | Just a helper for +scrape+. | [
"Just",
"a",
"helper",
"for",
"+",
"scrape",
"+",
"."
] | 29c90206317a6a8327a59f63d8117c56db6395eb | https://github.com/propublica/upton/blob/29c90206317a6a8327a59f63d8117c56db6395eb/lib/upton.rb#L337-L345 | train |
cloudfoundry/cf-uaa-lib | lib/uaa/info.rb | CF::UAA.Info.varz | def varz(name, pwd)
json_get(target, "/varz", key_style, "authorization" => Http.basic_auth(name, pwd))
end | ruby | def varz(name, pwd)
json_get(target, "/varz", key_style, "authorization" => Http.basic_auth(name, pwd))
end | [
"def",
"varz",
"(",
"name",
",",
"pwd",
")",
"json_get",
"(",
"target",
",",
"\"/varz\"",
",",
"key_style",
",",
"\"authorization\"",
"=>",
"Http",
".",
"basic_auth",
"(",
"name",
",",
"pwd",
")",
")",
"end"
] | Gets various monitoring and status variables from the server.
Authenticates using +name+ and +pwd+ for basic authentication.
@param (see Misc.server)
@return [Hash] | [
"Gets",
"various",
"monitoring",
"and",
"status",
"variables",
"from",
"the",
"server",
".",
"Authenticates",
"using",
"+",
"name",
"+",
"and",
"+",
"pwd",
"+",
"for",
"basic",
"authentication",
"."
] | e071d69ad5f16053321dfbb95835cf6a9b48227c | https://github.com/cloudfoundry/cf-uaa-lib/blob/e071d69ad5f16053321dfbb95835cf6a9b48227c/lib/uaa/info.rb#L61-L63 | train |
cloudfoundry/cf-uaa-lib | lib/uaa/info.rb | CF::UAA.Info.server | def server
reply = json_get(target, '/login', key_style)
return reply if reply && (reply[:prompts] || reply['prompts'])
raise BadResponse, "Invalid response from target #{target}"
end | ruby | def server
reply = json_get(target, '/login', key_style)
return reply if reply && (reply[:prompts] || reply['prompts'])
raise BadResponse, "Invalid response from target #{target}"
end | [
"def",
"server",
"reply",
"=",
"json_get",
"(",
"target",
",",
"'/login'",
",",
"key_style",
")",
"return",
"reply",
"if",
"reply",
"&&",
"(",
"reply",
"[",
":prompts",
"]",
"||",
"reply",
"[",
"'prompts'",
"]",
")",
"raise",
"BadResponse",
",",
"\"Invalid response from target #{target}\"",
"end"
] | Gets basic information about the target server, including version number,
commit ID, and links to API endpoints.
@return [Hash] | [
"Gets",
"basic",
"information",
"about",
"the",
"target",
"server",
"including",
"version",
"number",
"commit",
"ID",
"and",
"links",
"to",
"API",
"endpoints",
"."
] | e071d69ad5f16053321dfbb95835cf6a9b48227c | https://github.com/cloudfoundry/cf-uaa-lib/blob/e071d69ad5f16053321dfbb95835cf6a9b48227c/lib/uaa/info.rb#L68-L72 | train |
cloudfoundry/cf-uaa-lib | lib/uaa/info.rb | CF::UAA.Info.discover_uaa | def discover_uaa
info = server
links = info['links'] || info[:links]
uaa = links && (links['uaa'] || links[:uaa])
uaa || target
end | ruby | def discover_uaa
info = server
links = info['links'] || info[:links]
uaa = links && (links['uaa'] || links[:uaa])
uaa || target
end | [
"def",
"discover_uaa",
"info",
"=",
"server",
"links",
"=",
"info",
"[",
"'links'",
"]",
"||",
"info",
"[",
":links",
"]",
"uaa",
"=",
"links",
"&&",
"(",
"links",
"[",
"'uaa'",
"]",
"||",
"links",
"[",
":uaa",
"]",
")",
"uaa",
"||",
"target",
"end"
] | Gets a base url for the associated UAA from the target server by inspecting the
links returned from its info endpoint.
@return [String] url of UAA (or the target itself if it didn't provide a response) | [
"Gets",
"a",
"base",
"url",
"for",
"the",
"associated",
"UAA",
"from",
"the",
"target",
"server",
"by",
"inspecting",
"the",
"links",
"returned",
"from",
"its",
"info",
"endpoint",
"."
] | e071d69ad5f16053321dfbb95835cf6a9b48227c | https://github.com/cloudfoundry/cf-uaa-lib/blob/e071d69ad5f16053321dfbb95835cf6a9b48227c/lib/uaa/info.rb#L77-L83 | train |
cloudfoundry/cf-uaa-lib | lib/uaa/info.rb | CF::UAA.Info.validation_key | def validation_key(client_id = nil, client_secret = nil)
hdrs = client_id && client_secret ?
{ "authorization" => Http.basic_auth(client_id, client_secret)} : {}
json_get(target, "/token_key", key_style, hdrs)
end | ruby | def validation_key(client_id = nil, client_secret = nil)
hdrs = client_id && client_secret ?
{ "authorization" => Http.basic_auth(client_id, client_secret)} : {}
json_get(target, "/token_key", key_style, hdrs)
end | [
"def",
"validation_key",
"(",
"client_id",
"=",
"nil",
",",
"client_secret",
"=",
"nil",
")",
"hdrs",
"=",
"client_id",
"&&",
"client_secret",
"?",
"{",
"\"authorization\"",
"=>",
"Http",
".",
"basic_auth",
"(",
"client_id",
",",
"client_secret",
")",
"}",
":",
"{",
"}",
"json_get",
"(",
"target",
",",
"\"/token_key\"",
",",
"key_style",
",",
"hdrs",
")",
"end"
] | Gets the key from the server that is used to validate token signatures. If
the server is configured to use a symetric key, the caller must authenticate
by providing a a +client_id+ and +client_secret+. If the server
is configured to sign with a private key, this call will retrieve the
public key and +client_id+ must be nil.
@param (see Misc.server)
@return [Hash] | [
"Gets",
"the",
"key",
"from",
"the",
"server",
"that",
"is",
"used",
"to",
"validate",
"token",
"signatures",
".",
"If",
"the",
"server",
"is",
"configured",
"to",
"use",
"a",
"symetric",
"key",
"the",
"caller",
"must",
"authenticate",
"by",
"providing",
"a",
"a",
"+",
"client_id",
"+",
"and",
"+",
"client_secret",
"+",
".",
"If",
"the",
"server",
"is",
"configured",
"to",
"sign",
"with",
"a",
"private",
"key",
"this",
"call",
"will",
"retrieve",
"the",
"public",
"key",
"and",
"+",
"client_id",
"+",
"must",
"be",
"nil",
"."
] | e071d69ad5f16053321dfbb95835cf6a9b48227c | https://github.com/cloudfoundry/cf-uaa-lib/blob/e071d69ad5f16053321dfbb95835cf6a9b48227c/lib/uaa/info.rb#L92-L96 | train |
cloudfoundry/cf-uaa-lib | lib/uaa/info.rb | CF::UAA.Info.password_strength | def password_strength(password)
json_parse_reply(key_style, *request(target, :post, '/password/score',
Util.encode_form(:password => password), "content-type" => Http::FORM_UTF8,
"accept" => Http::JSON_UTF8))
end | ruby | def password_strength(password)
json_parse_reply(key_style, *request(target, :post, '/password/score',
Util.encode_form(:password => password), "content-type" => Http::FORM_UTF8,
"accept" => Http::JSON_UTF8))
end | [
"def",
"password_strength",
"(",
"password",
")",
"json_parse_reply",
"(",
"key_style",
",",
"request",
"(",
"target",
",",
":post",
",",
"'/password/score'",
",",
"Util",
".",
"encode_form",
"(",
":password",
"=>",
"password",
")",
",",
"\"content-type\"",
"=>",
"Http",
"::",
"FORM_UTF8",
",",
"\"accept\"",
"=>",
"Http",
"::",
"JSON_UTF8",
")",
")",
"end"
] | Gets information about the given password, including a strength score and
an indication of what strength is required.
@param (see Misc.server)
@return [Hash] | [
"Gets",
"information",
"about",
"the",
"given",
"password",
"including",
"a",
"strength",
"score",
"and",
"an",
"indication",
"of",
"what",
"strength",
"is",
"required",
"."
] | e071d69ad5f16053321dfbb95835cf6a9b48227c | https://github.com/cloudfoundry/cf-uaa-lib/blob/e071d69ad5f16053321dfbb95835cf6a9b48227c/lib/uaa/info.rb#L147-L151 | train |
cloudfoundry/cf-uaa-lib | lib/uaa/scim.rb | CF::UAA.Scim.type_info | def type_info(type, elem)
scimfo = {
user: {
path: '/Users',
name_attr: 'userName',
origin_attr: 'origin'
},
group: {
path: '/Groups',
name_attr: 'displayName',
origin_attr: 'zoneid'
},
client: {
path: '/oauth/clients',
name_attr: 'client_id'
},
user_id: {
path: '/ids/Users',
name_attr: 'userName',
origin_attr: 'origin',
},
group_mapping: {
path: '/Groups/External',
name_attr: 'externalGroup',
origin_attr: 'origin'
}
}
type_info = scimfo[type]
unless type_info
raise ArgumentError, "scim resource type must be one of #{scimfo.keys.inspect}"
end
value = type_info[elem]
unless value
raise ArgumentError, "scim schema element must be one of #{type_info.keys.inspect}"
end
value
end | ruby | def type_info(type, elem)
scimfo = {
user: {
path: '/Users',
name_attr: 'userName',
origin_attr: 'origin'
},
group: {
path: '/Groups',
name_attr: 'displayName',
origin_attr: 'zoneid'
},
client: {
path: '/oauth/clients',
name_attr: 'client_id'
},
user_id: {
path: '/ids/Users',
name_attr: 'userName',
origin_attr: 'origin',
},
group_mapping: {
path: '/Groups/External',
name_attr: 'externalGroup',
origin_attr: 'origin'
}
}
type_info = scimfo[type]
unless type_info
raise ArgumentError, "scim resource type must be one of #{scimfo.keys.inspect}"
end
value = type_info[elem]
unless value
raise ArgumentError, "scim schema element must be one of #{type_info.keys.inspect}"
end
value
end | [
"def",
"type_info",
"(",
"type",
",",
"elem",
")",
"scimfo",
"=",
"{",
"user",
":",
"{",
"path",
":",
"'/Users'",
",",
"name_attr",
":",
"'userName'",
",",
"origin_attr",
":",
"'origin'",
"}",
",",
"group",
":",
"{",
"path",
":",
"'/Groups'",
",",
"name_attr",
":",
"'displayName'",
",",
"origin_attr",
":",
"'zoneid'",
"}",
",",
"client",
":",
"{",
"path",
":",
"'/oauth/clients'",
",",
"name_attr",
":",
"'client_id'",
"}",
",",
"user_id",
":",
"{",
"path",
":",
"'/ids/Users'",
",",
"name_attr",
":",
"'userName'",
",",
"origin_attr",
":",
"'origin'",
",",
"}",
",",
"group_mapping",
":",
"{",
"path",
":",
"'/Groups/External'",
",",
"name_attr",
":",
"'externalGroup'",
",",
"origin_attr",
":",
"'origin'",
"}",
"}",
"type_info",
"=",
"scimfo",
"[",
"type",
"]",
"unless",
"type_info",
"raise",
"ArgumentError",
",",
"\"scim resource type must be one of #{scimfo.keys.inspect}\"",
"end",
"value",
"=",
"type_info",
"[",
"elem",
"]",
"unless",
"value",
"raise",
"ArgumentError",
",",
"\"scim schema element must be one of #{type_info.keys.inspect}\"",
"end",
"value",
"end"
] | an attempt to hide some scim and uaa oddities | [
"an",
"attempt",
"to",
"hide",
"some",
"scim",
"and",
"uaa",
"oddities"
] | e071d69ad5f16053321dfbb95835cf6a9b48227c | https://github.com/cloudfoundry/cf-uaa-lib/blob/e071d69ad5f16053321dfbb95835cf6a9b48227c/lib/uaa/scim.rb#L90-L131 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.