id
int32
0
24.9k
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
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
10,900
puppetlabs/puppet
lib/puppet/util/windows/service.rb
Puppet::Util::Windows.Service.exists?
def exists?(service_name) open_service(service_name, SC_MANAGER_CONNECT, SERVICE_QUERY_STATUS) do |_| true end rescue Puppet::Util::Windows::Error => e return false if e.code == ERROR_SERVICE_DOES_NOT_EXIST raise e end
ruby
def exists?(service_name) open_service(service_name, SC_MANAGER_CONNECT, SERVICE_QUERY_STATUS) do |_| true end rescue Puppet::Util::Windows::Error => e return false if e.code == ERROR_SERVICE_DOES_NOT_EXIST raise e end
[ "def", "exists?", "(", "service_name", ")", "open_service", "(", "service_name", ",", "SC_MANAGER_CONNECT", ",", "SERVICE_QUERY_STATUS", ")", "do", "|", "_", "|", "true", "end", "rescue", "Puppet", "::", "Util", "::", "Windows", "::", "Error", "=>", "e", "return", "false", "if", "e", ".", "code", "==", "ERROR_SERVICE_DOES_NOT_EXIST", "raise", "e", "end" ]
Returns true if the service exists, false otherwise. @param [String] service_name name of the service
[ "Returns", "true", "if", "the", "service", "exists", "false", "otherwise", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/util/windows/service.rb#L286-L293
10,901
puppetlabs/puppet
lib/puppet/util/windows/service.rb
Puppet::Util::Windows.Service.start
def start(service_name, timeout: DEFAULT_TIMEOUT) Puppet.debug _("Starting the %{service_name} service. Timeout set to: %{timeout} seconds") % { service_name: service_name, timeout: timeout } valid_initial_states = [ SERVICE_STOP_PENDING, SERVICE_STOPPED, SERVICE_START_PENDING ] transition_service_state(service_name, valid_initial_states, SERVICE_RUNNING, timeout) do |service| if StartServiceW(service, 0, FFI::Pointer::NULL) == FFI::WIN32_FALSE raise Puppet::Util::Windows::Error, _("Failed to start the service") end end Puppet.debug _("Successfully started the %{service_name} service") % { service_name: service_name } end
ruby
def start(service_name, timeout: DEFAULT_TIMEOUT) Puppet.debug _("Starting the %{service_name} service. Timeout set to: %{timeout} seconds") % { service_name: service_name, timeout: timeout } valid_initial_states = [ SERVICE_STOP_PENDING, SERVICE_STOPPED, SERVICE_START_PENDING ] transition_service_state(service_name, valid_initial_states, SERVICE_RUNNING, timeout) do |service| if StartServiceW(service, 0, FFI::Pointer::NULL) == FFI::WIN32_FALSE raise Puppet::Util::Windows::Error, _("Failed to start the service") end end Puppet.debug _("Successfully started the %{service_name} service") % { service_name: service_name } end
[ "def", "start", "(", "service_name", ",", "timeout", ":", "DEFAULT_TIMEOUT", ")", "Puppet", ".", "debug", "_", "(", "\"Starting the %{service_name} service. Timeout set to: %{timeout} seconds\"", ")", "%", "{", "service_name", ":", "service_name", ",", "timeout", ":", "timeout", "}", "valid_initial_states", "=", "[", "SERVICE_STOP_PENDING", ",", "SERVICE_STOPPED", ",", "SERVICE_START_PENDING", "]", "transition_service_state", "(", "service_name", ",", "valid_initial_states", ",", "SERVICE_RUNNING", ",", "timeout", ")", "do", "|", "service", "|", "if", "StartServiceW", "(", "service", ",", "0", ",", "FFI", "::", "Pointer", "::", "NULL", ")", "==", "FFI", "::", "WIN32_FALSE", "raise", "Puppet", "::", "Util", "::", "Windows", "::", "Error", ",", "_", "(", "\"Failed to start the service\"", ")", "end", "end", "Puppet", ".", "debug", "_", "(", "\"Successfully started the %{service_name} service\"", ")", "%", "{", "service_name", ":", "service_name", "}", "end" ]
Start a windows service @param [String] service_name name of the service to start @param optional [Integer] timeout the minumum number of seconds to wait before timing out
[ "Start", "a", "windows", "service" ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/util/windows/service.rb#L300-L316
10,902
puppetlabs/puppet
lib/puppet/util/windows/service.rb
Puppet::Util::Windows.Service.stop
def stop(service_name, timeout: DEFAULT_TIMEOUT) Puppet.debug _("Stopping the %{service_name} service. Timeout set to: %{timeout} seconds") % { service_name: service_name, timeout: timeout } valid_initial_states = SERVICE_STATES.keys - [SERVICE_STOPPED] transition_service_state(service_name, valid_initial_states, SERVICE_STOPPED, timeout) do |service| send_service_control_signal(service, SERVICE_CONTROL_STOP) end Puppet.debug _("Successfully stopped the %{service_name} service") % { service_name: service_name } end
ruby
def stop(service_name, timeout: DEFAULT_TIMEOUT) Puppet.debug _("Stopping the %{service_name} service. Timeout set to: %{timeout} seconds") % { service_name: service_name, timeout: timeout } valid_initial_states = SERVICE_STATES.keys - [SERVICE_STOPPED] transition_service_state(service_name, valid_initial_states, SERVICE_STOPPED, timeout) do |service| send_service_control_signal(service, SERVICE_CONTROL_STOP) end Puppet.debug _("Successfully stopped the %{service_name} service") % { service_name: service_name } end
[ "def", "stop", "(", "service_name", ",", "timeout", ":", "DEFAULT_TIMEOUT", ")", "Puppet", ".", "debug", "_", "(", "\"Stopping the %{service_name} service. Timeout set to: %{timeout} seconds\"", ")", "%", "{", "service_name", ":", "service_name", ",", "timeout", ":", "timeout", "}", "valid_initial_states", "=", "SERVICE_STATES", ".", "keys", "-", "[", "SERVICE_STOPPED", "]", "transition_service_state", "(", "service_name", ",", "valid_initial_states", ",", "SERVICE_STOPPED", ",", "timeout", ")", "do", "|", "service", "|", "send_service_control_signal", "(", "service", ",", "SERVICE_CONTROL_STOP", ")", "end", "Puppet", ".", "debug", "_", "(", "\"Successfully stopped the %{service_name} service\"", ")", "%", "{", "service_name", ":", "service_name", "}", "end" ]
Stop a windows service @param [String] service_name name of the service to stop @param optional [Integer] timeout the minumum number of seconds to wait before timing out
[ "Stop", "a", "windows", "service" ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/util/windows/service.rb#L323-L333
10,903
puppetlabs/puppet
lib/puppet/util/windows/service.rb
Puppet::Util::Windows.Service.resume
def resume(service_name, timeout: DEFAULT_TIMEOUT) Puppet.debug _("Resuming the %{service_name} service. Timeout set to: %{timeout} seconds") % { service_name: service_name, timeout: timeout } valid_initial_states = [ SERVICE_PAUSE_PENDING, SERVICE_PAUSED, SERVICE_CONTINUE_PENDING ] transition_service_state(service_name, valid_initial_states, SERVICE_RUNNING, timeout) do |service| # The SERVICE_CONTROL_CONTINUE signal can only be sent when # the service is in the SERVICE_PAUSED state wait_on_pending_state(service, SERVICE_PAUSE_PENDING, timeout) send_service_control_signal(service, SERVICE_CONTROL_CONTINUE) end Puppet.debug _("Successfully resumed the %{service_name} service") % { service_name: service_name } end
ruby
def resume(service_name, timeout: DEFAULT_TIMEOUT) Puppet.debug _("Resuming the %{service_name} service. Timeout set to: %{timeout} seconds") % { service_name: service_name, timeout: timeout } valid_initial_states = [ SERVICE_PAUSE_PENDING, SERVICE_PAUSED, SERVICE_CONTINUE_PENDING ] transition_service_state(service_name, valid_initial_states, SERVICE_RUNNING, timeout) do |service| # The SERVICE_CONTROL_CONTINUE signal can only be sent when # the service is in the SERVICE_PAUSED state wait_on_pending_state(service, SERVICE_PAUSE_PENDING, timeout) send_service_control_signal(service, SERVICE_CONTROL_CONTINUE) end Puppet.debug _("Successfully resumed the %{service_name} service") % { service_name: service_name } end
[ "def", "resume", "(", "service_name", ",", "timeout", ":", "DEFAULT_TIMEOUT", ")", "Puppet", ".", "debug", "_", "(", "\"Resuming the %{service_name} service. Timeout set to: %{timeout} seconds\"", ")", "%", "{", "service_name", ":", "service_name", ",", "timeout", ":", "timeout", "}", "valid_initial_states", "=", "[", "SERVICE_PAUSE_PENDING", ",", "SERVICE_PAUSED", ",", "SERVICE_CONTINUE_PENDING", "]", "transition_service_state", "(", "service_name", ",", "valid_initial_states", ",", "SERVICE_RUNNING", ",", "timeout", ")", "do", "|", "service", "|", "# The SERVICE_CONTROL_CONTINUE signal can only be sent when", "# the service is in the SERVICE_PAUSED state", "wait_on_pending_state", "(", "service", ",", "SERVICE_PAUSE_PENDING", ",", "timeout", ")", "send_service_control_signal", "(", "service", ",", "SERVICE_CONTROL_CONTINUE", ")", "end", "Puppet", ".", "debug", "_", "(", "\"Successfully resumed the %{service_name} service\"", ")", "%", "{", "service_name", ":", "service_name", "}", "end" ]
Resume a paused windows service @param [String] service_name name of the service to resume @param optional [Integer] :timeout the minumum number of seconds to wait before timing out
[ "Resume", "a", "paused", "windows", "service" ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/util/windows/service.rb#L340-L358
10,904
puppetlabs/puppet
lib/puppet/util/windows/service.rb
Puppet::Util::Windows.Service.service_state
def service_state(service_name) state = nil open_service(service_name, SC_MANAGER_CONNECT, SERVICE_QUERY_STATUS) do |service| query_status(service) do |status| state = SERVICE_STATES[status[:dwCurrentState]] end end if state.nil? raise Puppet::Error.new(_("Unknown Service state '%{current_state}' for '%{service_name}'") % { current_state: state.to_s, service_name: service_name}) end state end
ruby
def service_state(service_name) state = nil open_service(service_name, SC_MANAGER_CONNECT, SERVICE_QUERY_STATUS) do |service| query_status(service) do |status| state = SERVICE_STATES[status[:dwCurrentState]] end end if state.nil? raise Puppet::Error.new(_("Unknown Service state '%{current_state}' for '%{service_name}'") % { current_state: state.to_s, service_name: service_name}) end state end
[ "def", "service_state", "(", "service_name", ")", "state", "=", "nil", "open_service", "(", "service_name", ",", "SC_MANAGER_CONNECT", ",", "SERVICE_QUERY_STATUS", ")", "do", "|", "service", "|", "query_status", "(", "service", ")", "do", "|", "status", "|", "state", "=", "SERVICE_STATES", "[", "status", "[", ":dwCurrentState", "]", "]", "end", "end", "if", "state", ".", "nil?", "raise", "Puppet", "::", "Error", ".", "new", "(", "_", "(", "\"Unknown Service state '%{current_state}' for '%{service_name}'\"", ")", "%", "{", "current_state", ":", "state", ".", "to_s", ",", "service_name", ":", "service_name", "}", ")", "end", "state", "end" ]
Query the state of a service using QueryServiceStatusEx @param [string] service_name name of the service to query @return [string] the status of the service
[ "Query", "the", "state", "of", "a", "service", "using", "QueryServiceStatusEx" ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/util/windows/service.rb#L365-L376
10,905
puppetlabs/puppet
lib/puppet/util/windows/service.rb
Puppet::Util::Windows.Service.service_start_type
def service_start_type(service_name) start_type = nil open_service(service_name, SC_MANAGER_CONNECT, SERVICE_QUERY_CONFIG) do |service| query_config(service) do |config| start_type = SERVICE_START_TYPES[config[:dwStartType]] end end if start_type.nil? raise Puppet::Error.new(_("Unknown start type '%{start_type}' for '%{service_name}'") % { start_type: start_type.to_s, service_name: service_name}) end start_type end
ruby
def service_start_type(service_name) start_type = nil open_service(service_name, SC_MANAGER_CONNECT, SERVICE_QUERY_CONFIG) do |service| query_config(service) do |config| start_type = SERVICE_START_TYPES[config[:dwStartType]] end end if start_type.nil? raise Puppet::Error.new(_("Unknown start type '%{start_type}' for '%{service_name}'") % { start_type: start_type.to_s, service_name: service_name}) end start_type end
[ "def", "service_start_type", "(", "service_name", ")", "start_type", "=", "nil", "open_service", "(", "service_name", ",", "SC_MANAGER_CONNECT", ",", "SERVICE_QUERY_CONFIG", ")", "do", "|", "service", "|", "query_config", "(", "service", ")", "do", "|", "config", "|", "start_type", "=", "SERVICE_START_TYPES", "[", "config", "[", ":dwStartType", "]", "]", "end", "end", "if", "start_type", ".", "nil?", "raise", "Puppet", "::", "Error", ".", "new", "(", "_", "(", "\"Unknown start type '%{start_type}' for '%{service_name}'\"", ")", "%", "{", "start_type", ":", "start_type", ".", "to_s", ",", "service_name", ":", "service_name", "}", ")", "end", "start_type", "end" ]
Query the configuration of a service using QueryServiceConfigW @param [String] service_name name of the service to query @return [QUERY_SERVICE_CONFIGW.struct] the configuration of the service
[ "Query", "the", "configuration", "of", "a", "service", "using", "QueryServiceConfigW" ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/util/windows/service.rb#L383-L394
10,906
puppetlabs/puppet
lib/puppet/util/windows/service.rb
Puppet::Util::Windows.Service.set_startup_mode
def set_startup_mode(service_name, startup_type) startup_code = SERVICE_START_TYPES.key(startup_type) if startup_code.nil? raise Puppet::Error.new(_("Unknown start type %{start_type}") % {startup_type: startup_type.to_s}) end open_service(service_name, SC_MANAGER_CONNECT, SERVICE_CHANGE_CONFIG) do |service| # Currently the only thing puppet's API can really manage # in this list is dwStartType (the third param). Thus no # generic function was written to make use of all the params # since the API as-is couldn't use them anyway success = ChangeServiceConfigW( service, SERVICE_NO_CHANGE, # dwServiceType startup_code, # dwStartType SERVICE_NO_CHANGE, # dwErrorControl FFI::Pointer::NULL, # lpBinaryPathName FFI::Pointer::NULL, # lpLoadOrderGroup FFI::Pointer::NULL, # lpdwTagId FFI::Pointer::NULL, # lpDependencies FFI::Pointer::NULL, # lpServiceStartName FFI::Pointer::NULL, # lpPassword FFI::Pointer::NULL # lpDisplayName ) if success == FFI::WIN32_FALSE raise Puppet::Util::Windows::Error.new(_("Failed to update service configuration")) end end end
ruby
def set_startup_mode(service_name, startup_type) startup_code = SERVICE_START_TYPES.key(startup_type) if startup_code.nil? raise Puppet::Error.new(_("Unknown start type %{start_type}") % {startup_type: startup_type.to_s}) end open_service(service_name, SC_MANAGER_CONNECT, SERVICE_CHANGE_CONFIG) do |service| # Currently the only thing puppet's API can really manage # in this list is dwStartType (the third param). Thus no # generic function was written to make use of all the params # since the API as-is couldn't use them anyway success = ChangeServiceConfigW( service, SERVICE_NO_CHANGE, # dwServiceType startup_code, # dwStartType SERVICE_NO_CHANGE, # dwErrorControl FFI::Pointer::NULL, # lpBinaryPathName FFI::Pointer::NULL, # lpLoadOrderGroup FFI::Pointer::NULL, # lpdwTagId FFI::Pointer::NULL, # lpDependencies FFI::Pointer::NULL, # lpServiceStartName FFI::Pointer::NULL, # lpPassword FFI::Pointer::NULL # lpDisplayName ) if success == FFI::WIN32_FALSE raise Puppet::Util::Windows::Error.new(_("Failed to update service configuration")) end end end
[ "def", "set_startup_mode", "(", "service_name", ",", "startup_type", ")", "startup_code", "=", "SERVICE_START_TYPES", ".", "key", "(", "startup_type", ")", "if", "startup_code", ".", "nil?", "raise", "Puppet", "::", "Error", ".", "new", "(", "_", "(", "\"Unknown start type %{start_type}\"", ")", "%", "{", "startup_type", ":", "startup_type", ".", "to_s", "}", ")", "end", "open_service", "(", "service_name", ",", "SC_MANAGER_CONNECT", ",", "SERVICE_CHANGE_CONFIG", ")", "do", "|", "service", "|", "# Currently the only thing puppet's API can really manage", "# in this list is dwStartType (the third param). Thus no", "# generic function was written to make use of all the params", "# since the API as-is couldn't use them anyway", "success", "=", "ChangeServiceConfigW", "(", "service", ",", "SERVICE_NO_CHANGE", ",", "# dwServiceType", "startup_code", ",", "# dwStartType", "SERVICE_NO_CHANGE", ",", "# dwErrorControl", "FFI", "::", "Pointer", "::", "NULL", ",", "# lpBinaryPathName", "FFI", "::", "Pointer", "::", "NULL", ",", "# lpLoadOrderGroup", "FFI", "::", "Pointer", "::", "NULL", ",", "# lpdwTagId", "FFI", "::", "Pointer", "::", "NULL", ",", "# lpDependencies", "FFI", "::", "Pointer", "::", "NULL", ",", "# lpServiceStartName", "FFI", "::", "Pointer", "::", "NULL", ",", "# lpPassword", "FFI", "::", "Pointer", "::", "NULL", "# lpDisplayName", ")", "if", "success", "==", "FFI", "::", "WIN32_FALSE", "raise", "Puppet", "::", "Util", "::", "Windows", "::", "Error", ".", "new", "(", "_", "(", "\"Failed to update service configuration\"", ")", ")", "end", "end", "end" ]
Change the startup mode of a windows service @param [string] service_name the name of the service to modify @param [Int] startup_type a code corresponding to a start type for windows service, see the "Service start type codes" section in the Puppet::Util::Windows::Service file for the list of available codes
[ "Change", "the", "startup", "mode", "of", "a", "windows", "service" ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/util/windows/service.rb#L403-L430
10,907
puppetlabs/puppet
lib/puppet/util/windows/service.rb
Puppet::Util::Windows.Service.services
def services services = {} open_scm(SC_MANAGER_ENUMERATE_SERVICE) do |scm| size_required = 0 services_returned = 0 FFI::MemoryPointer.new(:dword) do |bytes_pointer| FFI::MemoryPointer.new(:dword) do |svcs_ret_ptr| FFI::MemoryPointer.new(:dword) do |resume_ptr| resume_ptr.write_dword(0) # Fetch the bytes of memory required to be allocated # for QueryServiceConfigW to return succesfully. This # is done by sending NULL and 0 for the pointer and size # respectively, letting the command fail, then reading the # value of pcbBytesNeeded # # return value will be false from this call, since it's designed # to fail. Just ignore it EnumServicesStatusExW( scm, :SC_ENUM_PROCESS_INFO, ALL_SERVICE_TYPES, SERVICE_STATE_ALL, FFI::Pointer::NULL, 0, bytes_pointer, svcs_ret_ptr, resume_ptr, FFI::Pointer::NULL ) size_required = bytes_pointer.read_dword FFI::MemoryPointer.new(size_required) do |buffer_ptr| resume_ptr.write_dword(0) svcs_ret_ptr.write_dword(0) success = EnumServicesStatusExW( scm, :SC_ENUM_PROCESS_INFO, ALL_SERVICE_TYPES, SERVICE_STATE_ALL, buffer_ptr, buffer_ptr.size, bytes_pointer, svcs_ret_ptr, resume_ptr, FFI::Pointer::NULL ) if success == FFI::WIN32_FALSE raise Puppet::Util::Windows::Error.new(_("Failed to fetch services")) end # Now that the buffer is populated with services # we pull the data from memory using pointer arithmetic: # the number of services returned by the function is # available to be read from svcs_ret_ptr, and we iterate # that many times moving the cursor pointer the length of # ENUM_SERVICE_STATUS_PROCESSW.size. This should iterate # over the buffer and extract each struct. services_returned = svcs_ret_ptr.read_dword cursor_ptr = FFI::Pointer.new(ENUM_SERVICE_STATUS_PROCESSW, buffer_ptr) 0.upto(services_returned - 1) do |index| service = ENUM_SERVICE_STATUS_PROCESSW.new(cursor_ptr[index]) services[service[:lpServiceName].read_arbitrary_wide_string_up_to(SERVICENAME_MAX)] = { :display_name => service[:lpDisplayName].read_arbitrary_wide_string_up_to(SERVICENAME_MAX), :service_status_process => service[:ServiceStatusProcess] } end end # buffer_ptr end # resume_ptr end # scvs_ret_ptr end # bytes_ptr end # open_scm services end
ruby
def services services = {} open_scm(SC_MANAGER_ENUMERATE_SERVICE) do |scm| size_required = 0 services_returned = 0 FFI::MemoryPointer.new(:dword) do |bytes_pointer| FFI::MemoryPointer.new(:dword) do |svcs_ret_ptr| FFI::MemoryPointer.new(:dword) do |resume_ptr| resume_ptr.write_dword(0) # Fetch the bytes of memory required to be allocated # for QueryServiceConfigW to return succesfully. This # is done by sending NULL and 0 for the pointer and size # respectively, letting the command fail, then reading the # value of pcbBytesNeeded # # return value will be false from this call, since it's designed # to fail. Just ignore it EnumServicesStatusExW( scm, :SC_ENUM_PROCESS_INFO, ALL_SERVICE_TYPES, SERVICE_STATE_ALL, FFI::Pointer::NULL, 0, bytes_pointer, svcs_ret_ptr, resume_ptr, FFI::Pointer::NULL ) size_required = bytes_pointer.read_dword FFI::MemoryPointer.new(size_required) do |buffer_ptr| resume_ptr.write_dword(0) svcs_ret_ptr.write_dword(0) success = EnumServicesStatusExW( scm, :SC_ENUM_PROCESS_INFO, ALL_SERVICE_TYPES, SERVICE_STATE_ALL, buffer_ptr, buffer_ptr.size, bytes_pointer, svcs_ret_ptr, resume_ptr, FFI::Pointer::NULL ) if success == FFI::WIN32_FALSE raise Puppet::Util::Windows::Error.new(_("Failed to fetch services")) end # Now that the buffer is populated with services # we pull the data from memory using pointer arithmetic: # the number of services returned by the function is # available to be read from svcs_ret_ptr, and we iterate # that many times moving the cursor pointer the length of # ENUM_SERVICE_STATUS_PROCESSW.size. This should iterate # over the buffer and extract each struct. services_returned = svcs_ret_ptr.read_dword cursor_ptr = FFI::Pointer.new(ENUM_SERVICE_STATUS_PROCESSW, buffer_ptr) 0.upto(services_returned - 1) do |index| service = ENUM_SERVICE_STATUS_PROCESSW.new(cursor_ptr[index]) services[service[:lpServiceName].read_arbitrary_wide_string_up_to(SERVICENAME_MAX)] = { :display_name => service[:lpDisplayName].read_arbitrary_wide_string_up_to(SERVICENAME_MAX), :service_status_process => service[:ServiceStatusProcess] } end end # buffer_ptr end # resume_ptr end # scvs_ret_ptr end # bytes_ptr end # open_scm services end
[ "def", "services", "services", "=", "{", "}", "open_scm", "(", "SC_MANAGER_ENUMERATE_SERVICE", ")", "do", "|", "scm", "|", "size_required", "=", "0", "services_returned", "=", "0", "FFI", "::", "MemoryPointer", ".", "new", "(", ":dword", ")", "do", "|", "bytes_pointer", "|", "FFI", "::", "MemoryPointer", ".", "new", "(", ":dword", ")", "do", "|", "svcs_ret_ptr", "|", "FFI", "::", "MemoryPointer", ".", "new", "(", ":dword", ")", "do", "|", "resume_ptr", "|", "resume_ptr", ".", "write_dword", "(", "0", ")", "# Fetch the bytes of memory required to be allocated", "# for QueryServiceConfigW to return succesfully. This", "# is done by sending NULL and 0 for the pointer and size", "# respectively, letting the command fail, then reading the", "# value of pcbBytesNeeded", "#", "# return value will be false from this call, since it's designed", "# to fail. Just ignore it", "EnumServicesStatusExW", "(", "scm", ",", ":SC_ENUM_PROCESS_INFO", ",", "ALL_SERVICE_TYPES", ",", "SERVICE_STATE_ALL", ",", "FFI", "::", "Pointer", "::", "NULL", ",", "0", ",", "bytes_pointer", ",", "svcs_ret_ptr", ",", "resume_ptr", ",", "FFI", "::", "Pointer", "::", "NULL", ")", "size_required", "=", "bytes_pointer", ".", "read_dword", "FFI", "::", "MemoryPointer", ".", "new", "(", "size_required", ")", "do", "|", "buffer_ptr", "|", "resume_ptr", ".", "write_dword", "(", "0", ")", "svcs_ret_ptr", ".", "write_dword", "(", "0", ")", "success", "=", "EnumServicesStatusExW", "(", "scm", ",", ":SC_ENUM_PROCESS_INFO", ",", "ALL_SERVICE_TYPES", ",", "SERVICE_STATE_ALL", ",", "buffer_ptr", ",", "buffer_ptr", ".", "size", ",", "bytes_pointer", ",", "svcs_ret_ptr", ",", "resume_ptr", ",", "FFI", "::", "Pointer", "::", "NULL", ")", "if", "success", "==", "FFI", "::", "WIN32_FALSE", "raise", "Puppet", "::", "Util", "::", "Windows", "::", "Error", ".", "new", "(", "_", "(", "\"Failed to fetch services\"", ")", ")", "end", "# Now that the buffer is populated with services", "# we pull the data from memory using pointer arithmetic:", "# the number of services returned by the function is", "# available to be read from svcs_ret_ptr, and we iterate", "# that many times moving the cursor pointer the length of", "# ENUM_SERVICE_STATUS_PROCESSW.size. This should iterate", "# over the buffer and extract each struct.", "services_returned", "=", "svcs_ret_ptr", ".", "read_dword", "cursor_ptr", "=", "FFI", "::", "Pointer", ".", "new", "(", "ENUM_SERVICE_STATUS_PROCESSW", ",", "buffer_ptr", ")", "0", ".", "upto", "(", "services_returned", "-", "1", ")", "do", "|", "index", "|", "service", "=", "ENUM_SERVICE_STATUS_PROCESSW", ".", "new", "(", "cursor_ptr", "[", "index", "]", ")", "services", "[", "service", "[", ":lpServiceName", "]", ".", "read_arbitrary_wide_string_up_to", "(", "SERVICENAME_MAX", ")", "]", "=", "{", ":display_name", "=>", "service", "[", ":lpDisplayName", "]", ".", "read_arbitrary_wide_string_up_to", "(", "SERVICENAME_MAX", ")", ",", ":service_status_process", "=>", "service", "[", ":ServiceStatusProcess", "]", "}", "end", "end", "# buffer_ptr", "end", "# resume_ptr", "end", "# scvs_ret_ptr", "end", "# bytes_ptr", "end", "# open_scm", "services", "end" ]
enumerate over all services in all states and return them as a hash @return [Hash] a hash containing services: { 'service name' => { 'display_name' => 'display name', 'service_status_process' => SERVICE_STATUS_PROCESS struct } }
[ "enumerate", "over", "all", "services", "in", "all", "states", "and", "return", "them", "as", "a", "hash" ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/util/windows/service.rb#L441-L511
10,908
puppetlabs/puppet
lib/puppet/util/rdoc/generators/puppet_generator.rb
Generators.PuppetGenerator.gen_sub_directories
def gen_sub_directories super File.makedirs(MODULE_DIR) File.makedirs(NODE_DIR) File.makedirs(PLUGIN_DIR) rescue $stderr.puts $ERROR_INFO.message exit 1 end
ruby
def gen_sub_directories super File.makedirs(MODULE_DIR) File.makedirs(NODE_DIR) File.makedirs(PLUGIN_DIR) rescue $stderr.puts $ERROR_INFO.message exit 1 end
[ "def", "gen_sub_directories", "super", "File", ".", "makedirs", "(", "MODULE_DIR", ")", "File", ".", "makedirs", "(", "NODE_DIR", ")", "File", ".", "makedirs", "(", "PLUGIN_DIR", ")", "rescue", "$stderr", ".", "puts", "$ERROR_INFO", ".", "message", "exit", "1", "end" ]
generate all the subdirectories, modules, classes and files
[ "generate", "all", "the", "subdirectories", "modules", "classes", "and", "files" ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/util/rdoc/generators/puppet_generator.rb#L195-L203
10,909
puppetlabs/puppet
lib/puppet/util/rdoc/generators/puppet_generator.rb
Generators.PuppetGenerator.gen_top_index
def gen_top_index(collection, title, template, filename) template = TemplatePage.new(RDoc::Page::FR_INDEX_BODY, template) res = [] collection.sort.each do |f| if f.document_self res << { "classlist" => CGI.escapeHTML("#{MODULE_DIR}/fr_#{f.index_name}.html"), "module" => CGI.escapeHTML("#{CLASS_DIR}/#{f.index_name}.html"),"name" => CGI.escapeHTML(f.index_name) } end end values = { "entries" => res, 'list_title' => CGI.escapeHTML(title), 'index_url' => main_url, 'charset' => @options.charset, 'style_url' => style_url('', @options.css), } Puppet::FileSystem.open(filename, nil, "w:UTF-8") do |f| template.write_html_on(f, values) end end
ruby
def gen_top_index(collection, title, template, filename) template = TemplatePage.new(RDoc::Page::FR_INDEX_BODY, template) res = [] collection.sort.each do |f| if f.document_self res << { "classlist" => CGI.escapeHTML("#{MODULE_DIR}/fr_#{f.index_name}.html"), "module" => CGI.escapeHTML("#{CLASS_DIR}/#{f.index_name}.html"),"name" => CGI.escapeHTML(f.index_name) } end end values = { "entries" => res, 'list_title' => CGI.escapeHTML(title), 'index_url' => main_url, 'charset' => @options.charset, 'style_url' => style_url('', @options.css), } Puppet::FileSystem.open(filename, nil, "w:UTF-8") do |f| template.write_html_on(f, values) end end
[ "def", "gen_top_index", "(", "collection", ",", "title", ",", "template", ",", "filename", ")", "template", "=", "TemplatePage", ".", "new", "(", "RDoc", "::", "Page", "::", "FR_INDEX_BODY", ",", "template", ")", "res", "=", "[", "]", "collection", ".", "sort", ".", "each", "do", "|", "f", "|", "if", "f", ".", "document_self", "res", "<<", "{", "\"classlist\"", "=>", "CGI", ".", "escapeHTML", "(", "\"#{MODULE_DIR}/fr_#{f.index_name}.html\"", ")", ",", "\"module\"", "=>", "CGI", ".", "escapeHTML", "(", "\"#{CLASS_DIR}/#{f.index_name}.html\"", ")", ",", "\"name\"", "=>", "CGI", ".", "escapeHTML", "(", "f", ".", "index_name", ")", "}", "end", "end", "values", "=", "{", "\"entries\"", "=>", "res", ",", "'list_title'", "=>", "CGI", ".", "escapeHTML", "(", "title", ")", ",", "'index_url'", "=>", "main_url", ",", "'charset'", "=>", "@options", ".", "charset", ",", "'style_url'", "=>", "style_url", "(", "''", ",", "@options", ".", "css", ")", ",", "}", "Puppet", "::", "FileSystem", ".", "open", "(", "filename", ",", "nil", ",", "\"w:UTF-8\"", ")", "do", "|", "f", "|", "template", ".", "write_html_on", "(", "f", ",", "values", ")", "end", "end" ]
generate a top index
[ "generate", "a", "top", "index" ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/util/rdoc/generators/puppet_generator.rb#L211-L231
10,910
puppetlabs/puppet
lib/puppet/util/rdoc/generators/puppet_generator.rb
Generators.PuppetGenerator.gen_class_index
def gen_class_index gen_an_index(@classes, 'All Classes', RDoc::Page::CLASS_INDEX, "fr_class_index.html") @allfiles.each do |file| unless file['file'].context.file_relative_name =~ /\.rb$/ gen_composite_index( file, RDoc::Page::COMBO_INDEX, "#{MODULE_DIR}/fr_#{file["file"].context.module_name}.html") end end end
ruby
def gen_class_index gen_an_index(@classes, 'All Classes', RDoc::Page::CLASS_INDEX, "fr_class_index.html") @allfiles.each do |file| unless file['file'].context.file_relative_name =~ /\.rb$/ gen_composite_index( file, RDoc::Page::COMBO_INDEX, "#{MODULE_DIR}/fr_#{file["file"].context.module_name}.html") end end end
[ "def", "gen_class_index", "gen_an_index", "(", "@classes", ",", "'All Classes'", ",", "RDoc", "::", "Page", "::", "CLASS_INDEX", ",", "\"fr_class_index.html\"", ")", "@allfiles", ".", "each", "do", "|", "file", "|", "unless", "file", "[", "'file'", "]", ".", "context", ".", "file_relative_name", "=~", "/", "\\.", "/", "gen_composite_index", "(", "file", ",", "RDoc", "::", "Page", "::", "COMBO_INDEX", ",", "\"#{MODULE_DIR}/fr_#{file[\"file\"].context.module_name}.html\"", ")", "end", "end", "end" ]
generate the all classes index file and the combo index
[ "generate", "the", "all", "classes", "index", "file", "and", "the", "combo", "index" ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/util/rdoc/generators/puppet_generator.rb#L234-L246
10,911
puppetlabs/puppet
lib/puppet/util/rdoc/generators/puppet_generator.rb
Generators.PuppetGenerator.main_url
def main_url main_page = @options.main_page ref = nil if main_page ref = AllReferences[main_page] if ref ref = ref.path else $stderr.puts "Could not find main page #{main_page}" end end unless ref for file in @files if file.document_self and file.context.global ref = CGI.escapeHTML("#{CLASS_DIR}/#{file.context.module_name}.html") break end end end unless ref for file in @files if file.document_self and !file.context.global ref = CGI.escapeHTML("#{CLASS_DIR}/#{file.context.module_name}.html") break end end end unless ref $stderr.puts "Couldn't find anything to document" $stderr.puts "Perhaps you've used :stopdoc: in all classes" exit(1) end ref end
ruby
def main_url main_page = @options.main_page ref = nil if main_page ref = AllReferences[main_page] if ref ref = ref.path else $stderr.puts "Could not find main page #{main_page}" end end unless ref for file in @files if file.document_self and file.context.global ref = CGI.escapeHTML("#{CLASS_DIR}/#{file.context.module_name}.html") break end end end unless ref for file in @files if file.document_self and !file.context.global ref = CGI.escapeHTML("#{CLASS_DIR}/#{file.context.module_name}.html") break end end end unless ref $stderr.puts "Couldn't find anything to document" $stderr.puts "Perhaps you've used :stopdoc: in all classes" exit(1) end ref end
[ "def", "main_url", "main_page", "=", "@options", ".", "main_page", "ref", "=", "nil", "if", "main_page", "ref", "=", "AllReferences", "[", "main_page", "]", "if", "ref", "ref", "=", "ref", ".", "path", "else", "$stderr", ".", "puts", "\"Could not find main page #{main_page}\"", "end", "end", "unless", "ref", "for", "file", "in", "@files", "if", "file", ".", "document_self", "and", "file", ".", "context", ".", "global", "ref", "=", "CGI", ".", "escapeHTML", "(", "\"#{CLASS_DIR}/#{file.context.module_name}.html\"", ")", "break", "end", "end", "end", "unless", "ref", "for", "file", "in", "@files", "if", "file", ".", "document_self", "and", "!", "file", ".", "context", ".", "global", "ref", "=", "CGI", ".", "escapeHTML", "(", "\"#{CLASS_DIR}/#{file.context.module_name}.html\"", ")", "break", "end", "end", "end", "unless", "ref", "$stderr", ".", "puts", "\"Couldn't find anything to document\"", "$stderr", ".", "puts", "\"Perhaps you've used :stopdoc: in all classes\"", "exit", "(", "1", ")", "end", "ref", "end" ]
returns the initial_page url
[ "returns", "the", "initial_page", "url" ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/util/rdoc/generators/puppet_generator.rb#L310-L347
10,912
puppetlabs/puppet
lib/puppet/util/rdoc/generators/puppet_generator.rb
Generators.HTMLPuppetNode.http_url
def http_url(full_name, prefix) path = full_name.dup path.gsub!(/<<\s*(\w*)/) { "from-#$1" } if path['<<'] File.join(prefix, path.split("::").collect { |p| Digest::MD5.hexdigest(p) }) + ".html" end
ruby
def http_url(full_name, prefix) path = full_name.dup path.gsub!(/<<\s*(\w*)/) { "from-#$1" } if path['<<'] File.join(prefix, path.split("::").collect { |p| Digest::MD5.hexdigest(p) }) + ".html" end
[ "def", "http_url", "(", "full_name", ",", "prefix", ")", "path", "=", "full_name", ".", "dup", "path", ".", "gsub!", "(", "/", "\\s", "\\w", "/", ")", "{", "\"from-#$1\"", "}", "if", "path", "[", "'<<'", "]", "File", ".", "join", "(", "prefix", ",", "path", ".", "split", "(", "\"::\"", ")", ".", "collect", "{", "|", "p", "|", "Digest", "::", "MD5", ".", "hexdigest", "(", "p", ")", "}", ")", "+", "\".html\"", "end" ]
return the relative file name to store this class in, which is also its url
[ "return", "the", "relative", "file", "name", "to", "store", "this", "class", "in", "which", "is", "also", "its", "url" ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/util/rdoc/generators/puppet_generator.rb#L482-L486
10,913
puppetlabs/puppet
lib/puppet/util/provider_features.rb
Puppet::Util::ProviderFeatures.ProviderFeature.methods_available?
def methods_available?(obj) methods.each do |m| if obj.is_a?(Class) return false unless obj.public_method_defined?(m) else return false unless obj.respond_to?(m) end end true end
ruby
def methods_available?(obj) methods.each do |m| if obj.is_a?(Class) return false unless obj.public_method_defined?(m) else return false unless obj.respond_to?(m) end end true end
[ "def", "methods_available?", "(", "obj", ")", "methods", ".", "each", "do", "|", "m", "|", "if", "obj", ".", "is_a?", "(", "Class", ")", "return", "false", "unless", "obj", ".", "public_method_defined?", "(", "m", ")", "else", "return", "false", "unless", "obj", ".", "respond_to?", "(", "m", ")", "end", "end", "true", "end" ]
Checks whether all feature predicate methods are available. @param obj [Object, Class] the object or class to check if feature predicates are available or not. @return [Boolean] Returns whether all of the required methods are available or not in the given object.
[ "Checks", "whether", "all", "feature", "predicate", "methods", "are", "available", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/util/provider_features.rb#L44-L53
10,914
puppetlabs/puppet
lib/puppet/module_tool/metadata.rb
Puppet::ModuleTool.Metadata.update
def update(data) process_name(data) if data['name'] process_version(data) if data['version'] process_source(data) if data['source'] process_data_provider(data) if data['data_provider'] merge_dependencies(data) if data['dependencies'] @data.merge!(data) return self end
ruby
def update(data) process_name(data) if data['name'] process_version(data) if data['version'] process_source(data) if data['source'] process_data_provider(data) if data['data_provider'] merge_dependencies(data) if data['dependencies'] @data.merge!(data) return self end
[ "def", "update", "(", "data", ")", "process_name", "(", "data", ")", "if", "data", "[", "'name'", "]", "process_version", "(", "data", ")", "if", "data", "[", "'version'", "]", "process_source", "(", "data", ")", "if", "data", "[", "'source'", "]", "process_data_provider", "(", "data", ")", "if", "data", "[", "'data_provider'", "]", "merge_dependencies", "(", "data", ")", "if", "data", "[", "'dependencies'", "]", "@data", ".", "merge!", "(", "data", ")", "return", "self", "end" ]
Merges the current set of metadata with another metadata hash. This method also handles the validation of module names and versions, in an effort to be proactive about module publishing constraints.
[ "Merges", "the", "current", "set", "of", "metadata", "with", "another", "metadata", "hash", ".", "This", "method", "also", "handles", "the", "validation", "of", "module", "names", "and", "versions", "in", "an", "effort", "to", "be", "proactive", "about", "module", "publishing", "constraints", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/module_tool/metadata.rb#L51-L60
10,915
puppetlabs/puppet
lib/puppet/module_tool/metadata.rb
Puppet::ModuleTool.Metadata.add_dependency
def add_dependency(name, version_requirement=nil, repository=nil) validate_name(name) validate_version_range(version_requirement) if version_requirement if dup = @data['dependencies'].find { |d| d.full_module_name == name && d.version_requirement != version_requirement } raise ArgumentError, _("Dependency conflict for %{module_name}: Dependency %{name} was given conflicting version requirements %{version_requirement} and %{dup_version}. Verify that there are no duplicates in the metadata.json.") % { module_name: full_module_name, name: name, version_requirement: version_requirement, dup_version: dup.version_requirement } end dep = Dependency.new(name, version_requirement, repository) @data['dependencies'].add(dep) dep end
ruby
def add_dependency(name, version_requirement=nil, repository=nil) validate_name(name) validate_version_range(version_requirement) if version_requirement if dup = @data['dependencies'].find { |d| d.full_module_name == name && d.version_requirement != version_requirement } raise ArgumentError, _("Dependency conflict for %{module_name}: Dependency %{name} was given conflicting version requirements %{version_requirement} and %{dup_version}. Verify that there are no duplicates in the metadata.json.") % { module_name: full_module_name, name: name, version_requirement: version_requirement, dup_version: dup.version_requirement } end dep = Dependency.new(name, version_requirement, repository) @data['dependencies'].add(dep) dep end
[ "def", "add_dependency", "(", "name", ",", "version_requirement", "=", "nil", ",", "repository", "=", "nil", ")", "validate_name", "(", "name", ")", "validate_version_range", "(", "version_requirement", ")", "if", "version_requirement", "if", "dup", "=", "@data", "[", "'dependencies'", "]", ".", "find", "{", "|", "d", "|", "d", ".", "full_module_name", "==", "name", "&&", "d", ".", "version_requirement", "!=", "version_requirement", "}", "raise", "ArgumentError", ",", "_", "(", "\"Dependency conflict for %{module_name}: Dependency %{name} was given conflicting version requirements %{version_requirement} and %{dup_version}. Verify that there are no duplicates in the metadata.json.\"", ")", "%", "{", "module_name", ":", "full_module_name", ",", "name", ":", "name", ",", "version_requirement", ":", "version_requirement", ",", "dup_version", ":", "dup", ".", "version_requirement", "}", "end", "dep", "=", "Dependency", ".", "new", "(", "name", ",", "version_requirement", ",", "repository", ")", "@data", "[", "'dependencies'", "]", ".", "add", "(", "dep", ")", "dep", "end" ]
Validates the name and version_requirement for a dependency, then creates the Dependency and adds it. Returns the Dependency that was added.
[ "Validates", "the", "name", "and", "version_requirement", "for", "a", "dependency", "then", "creates", "the", "Dependency", "and", "adds", "it", ".", "Returns", "the", "Dependency", "that", "was", "added", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/module_tool/metadata.rb#L65-L77
10,916
puppetlabs/puppet
lib/puppet/module_tool/metadata.rb
Puppet::ModuleTool.Metadata.process_name
def process_name(data) validate_name(data['name']) author, @module_name = data['name'].split(/[-\/]/, 2) data['author'] ||= author if @data['author'] == DEFAULTS['author'] end
ruby
def process_name(data) validate_name(data['name']) author, @module_name = data['name'].split(/[-\/]/, 2) data['author'] ||= author if @data['author'] == DEFAULTS['author'] end
[ "def", "process_name", "(", "data", ")", "validate_name", "(", "data", "[", "'name'", "]", ")", "author", ",", "@module_name", "=", "data", "[", "'name'", "]", ".", "split", "(", "/", "\\/", "/", ",", "2", ")", "data", "[", "'author'", "]", "||=", "author", "if", "@data", "[", "'author'", "]", "==", "DEFAULTS", "[", "'author'", "]", "end" ]
Do basic validation and parsing of the name parameter.
[ "Do", "basic", "validation", "and", "parsing", "of", "the", "name", "parameter", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/module_tool/metadata.rb#L120-L125
10,917
puppetlabs/puppet
lib/puppet/module_tool/metadata.rb
Puppet::ModuleTool.Metadata.process_source
def process_source(data) if data['source'] =~ %r[://] source_uri = URI.parse(data['source']) else source_uri = URI.parse("http://#{data['source']}") end if source_uri.host =~ /^(www\.)?github\.com$/ source_uri.scheme = 'https' source_uri.path.sub!(/\.git$/, '') data['project_page'] ||= @data['project_page'] || source_uri.to_s data['issues_url'] ||= @data['issues_url'] || source_uri.to_s.sub(/\/*$/, '') + '/issues' end rescue URI::Error return end
ruby
def process_source(data) if data['source'] =~ %r[://] source_uri = URI.parse(data['source']) else source_uri = URI.parse("http://#{data['source']}") end if source_uri.host =~ /^(www\.)?github\.com$/ source_uri.scheme = 'https' source_uri.path.sub!(/\.git$/, '') data['project_page'] ||= @data['project_page'] || source_uri.to_s data['issues_url'] ||= @data['issues_url'] || source_uri.to_s.sub(/\/*$/, '') + '/issues' end rescue URI::Error return end
[ "def", "process_source", "(", "data", ")", "if", "data", "[", "'source'", "]", "=~", "%r[", "]", "source_uri", "=", "URI", ".", "parse", "(", "data", "[", "'source'", "]", ")", "else", "source_uri", "=", "URI", ".", "parse", "(", "\"http://#{data['source']}\"", ")", "end", "if", "source_uri", ".", "host", "=~", "/", "\\.", "\\.", "/", "source_uri", ".", "scheme", "=", "'https'", "source_uri", ".", "path", ".", "sub!", "(", "/", "\\.", "/", ",", "''", ")", "data", "[", "'project_page'", "]", "||=", "@data", "[", "'project_page'", "]", "||", "source_uri", ".", "to_s", "data", "[", "'issues_url'", "]", "||=", "@data", "[", "'issues_url'", "]", "||", "source_uri", ".", "to_s", ".", "sub", "(", "/", "\\/", "/", ",", "''", ")", "+", "'/issues'", "end", "rescue", "URI", "::", "Error", "return", "end" ]
Do basic parsing of the source parameter. If the source is hosted on GitHub, we can predict sensible defaults for both project_page and issues_url.
[ "Do", "basic", "parsing", "of", "the", "source", "parameter", ".", "If", "the", "source", "is", "hosted", "on", "GitHub", "we", "can", "predict", "sensible", "defaults", "for", "both", "project_page", "and", "issues_url", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/module_tool/metadata.rb#L139-L155
10,918
puppetlabs/puppet
lib/puppet/module_tool/metadata.rb
Puppet::ModuleTool.Metadata.merge_dependencies
def merge_dependencies(data) data['dependencies'].each do |dep| add_dependency(dep['name'], dep['version_requirement'], dep['repository']) end # Clear dependencies so @data dependencies are not overwritten data.delete 'dependencies' end
ruby
def merge_dependencies(data) data['dependencies'].each do |dep| add_dependency(dep['name'], dep['version_requirement'], dep['repository']) end # Clear dependencies so @data dependencies are not overwritten data.delete 'dependencies' end
[ "def", "merge_dependencies", "(", "data", ")", "data", "[", "'dependencies'", "]", ".", "each", "do", "|", "dep", "|", "add_dependency", "(", "dep", "[", "'name'", "]", ",", "dep", "[", "'version_requirement'", "]", ",", "dep", "[", "'repository'", "]", ")", "end", "# Clear dependencies so @data dependencies are not overwritten", "data", ".", "delete", "'dependencies'", "end" ]
Validates and parses the dependencies.
[ "Validates", "and", "parses", "the", "dependencies", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/module_tool/metadata.rb#L158-L165
10,919
puppetlabs/puppet
lib/puppet/module_tool/metadata.rb
Puppet::ModuleTool.Metadata.validate_name
def validate_name(name) return if name =~ /\A[a-z0-9]+[-\/][a-z][a-z0-9_]*\Z/i namespace, modname = name.split(/[-\/]/, 2) modname = :namespace_missing if namespace == '' err = case modname when nil, '', :namespace_missing _("the field must be a namespaced module name") when /[^a-z0-9_]/i _("the module name contains non-alphanumeric (or underscore) characters") when /^[^a-z]/i _("the module name must begin with a letter") else _("the namespace contains non-alphanumeric characters") end raise ArgumentError, _("Invalid 'name' field in metadata.json: %{err}") % { err: err } end
ruby
def validate_name(name) return if name =~ /\A[a-z0-9]+[-\/][a-z][a-z0-9_]*\Z/i namespace, modname = name.split(/[-\/]/, 2) modname = :namespace_missing if namespace == '' err = case modname when nil, '', :namespace_missing _("the field must be a namespaced module name") when /[^a-z0-9_]/i _("the module name contains non-alphanumeric (or underscore) characters") when /^[^a-z]/i _("the module name must begin with a letter") else _("the namespace contains non-alphanumeric characters") end raise ArgumentError, _("Invalid 'name' field in metadata.json: %{err}") % { err: err } end
[ "def", "validate_name", "(", "name", ")", "return", "if", "name", "=~", "/", "\\A", "\\/", "\\Z", "/i", "namespace", ",", "modname", "=", "name", ".", "split", "(", "/", "\\/", "/", ",", "2", ")", "modname", "=", ":namespace_missing", "if", "namespace", "==", "''", "err", "=", "case", "modname", "when", "nil", ",", "''", ",", ":namespace_missing", "_", "(", "\"the field must be a namespaced module name\"", ")", "when", "/", "/i", "_", "(", "\"the module name contains non-alphanumeric (or underscore) characters\"", ")", "when", "/", "/i", "_", "(", "\"the module name must begin with a letter\"", ")", "else", "_", "(", "\"the namespace contains non-alphanumeric characters\"", ")", "end", "raise", "ArgumentError", ",", "_", "(", "\"Invalid 'name' field in metadata.json: %{err}\"", ")", "%", "{", "err", ":", "err", "}", "end" ]
Validates that the given module name is both namespaced and well-formed.
[ "Validates", "that", "the", "given", "module", "name", "is", "both", "namespaced", "and", "well", "-", "formed", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/module_tool/metadata.rb#L168-L186
10,920
puppetlabs/puppet
lib/puppet/module_tool/metadata.rb
Puppet::ModuleTool.Metadata.validate_version
def validate_version(version) return if SemanticPuppet::Version.valid?(version) err = _("version string cannot be parsed as a valid Semantic Version") raise ArgumentError, _("Invalid 'version' field in metadata.json: %{err}") % { err: err } end
ruby
def validate_version(version) return if SemanticPuppet::Version.valid?(version) err = _("version string cannot be parsed as a valid Semantic Version") raise ArgumentError, _("Invalid 'version' field in metadata.json: %{err}") % { err: err } end
[ "def", "validate_version", "(", "version", ")", "return", "if", "SemanticPuppet", "::", "Version", ".", "valid?", "(", "version", ")", "err", "=", "_", "(", "\"version string cannot be parsed as a valid Semantic Version\"", ")", "raise", "ArgumentError", ",", "_", "(", "\"Invalid 'version' field in metadata.json: %{err}\"", ")", "%", "{", "err", ":", "err", "}", "end" ]
Validates that the version string can be parsed as per SemVer.
[ "Validates", "that", "the", "version", "string", "can", "be", "parsed", "as", "per", "SemVer", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/module_tool/metadata.rb#L189-L194
10,921
puppetlabs/puppet
lib/puppet/module_tool/metadata.rb
Puppet::ModuleTool.Metadata.validate_data_provider
def validate_data_provider(value) if value.is_a?(String) unless value =~ /^[a-zA-Z][a-zA-Z0-9_]*$/ if value =~ /^[a-zA-Z]/ raise ArgumentError, _("field 'data_provider' contains non-alphanumeric characters") else raise ArgumentError, _("field 'data_provider' must begin with a letter") end end else raise ArgumentError, _("field 'data_provider' must be a string") end end
ruby
def validate_data_provider(value) if value.is_a?(String) unless value =~ /^[a-zA-Z][a-zA-Z0-9_]*$/ if value =~ /^[a-zA-Z]/ raise ArgumentError, _("field 'data_provider' contains non-alphanumeric characters") else raise ArgumentError, _("field 'data_provider' must begin with a letter") end end else raise ArgumentError, _("field 'data_provider' must be a string") end end
[ "def", "validate_data_provider", "(", "value", ")", "if", "value", ".", "is_a?", "(", "String", ")", "unless", "value", "=~", "/", "/", "if", "value", "=~", "/", "/", "raise", "ArgumentError", ",", "_", "(", "\"field 'data_provider' contains non-alphanumeric characters\"", ")", "else", "raise", "ArgumentError", ",", "_", "(", "\"field 'data_provider' must begin with a letter\"", ")", "end", "end", "else", "raise", "ArgumentError", ",", "_", "(", "\"field 'data_provider' must be a string\"", ")", "end", "end" ]
Validates that the given _value_ is a symbolic name that starts with a letter and then contains only letters, digits, or underscore. Will raise an ArgumentError if that's not the case. @param value [Object] The value to be tested
[ "Validates", "that", "the", "given", "_value_", "is", "a", "symbolic", "name", "that", "starts", "with", "a", "letter", "and", "then", "contains", "only", "letters", "digits", "or", "underscore", ".", "Will", "raise", "an", "ArgumentError", "if", "that", "s", "not", "the", "case", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/module_tool/metadata.rb#L201-L213
10,922
puppetlabs/puppet
lib/puppet/module_tool/metadata.rb
Puppet::ModuleTool.Metadata.validate_version_range
def validate_version_range(version_range) SemanticPuppet::VersionRange.parse(version_range) rescue ArgumentError => e raise ArgumentError, _("Invalid 'version_range' field in metadata.json: %{err}") % { err: e } end
ruby
def validate_version_range(version_range) SemanticPuppet::VersionRange.parse(version_range) rescue ArgumentError => e raise ArgumentError, _("Invalid 'version_range' field in metadata.json: %{err}") % { err: e } end
[ "def", "validate_version_range", "(", "version_range", ")", "SemanticPuppet", "::", "VersionRange", ".", "parse", "(", "version_range", ")", "rescue", "ArgumentError", "=>", "e", "raise", "ArgumentError", ",", "_", "(", "\"Invalid 'version_range' field in metadata.json: %{err}\"", ")", "%", "{", "err", ":", "e", "}", "end" ]
Validates that the version range can be parsed by Semantic.
[ "Validates", "that", "the", "version", "range", "can", "be", "parsed", "by", "Semantic", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/module_tool/metadata.rb#L216-L220
10,923
puppetlabs/puppet
lib/puppet/network/authconfig.rb
Puppet.Network::DefaultAuthProvider.insert_default_acl
def insert_default_acl self.class.default_acl.each do |acl| unless rights[acl[:acl]] Puppet.info _("Inserting default '%{acl}' (auth %{auth}) ACL") % { acl: acl[:acl], auth: acl[:authenticated] } mk_acl(acl) end end # queue an empty (ie deny all) right for every other path # actually this is not strictly necessary as the rights system # denies not explicitly allowed paths unless rights["/"] rights.newright("/").restrict_authenticated(:any) end end
ruby
def insert_default_acl self.class.default_acl.each do |acl| unless rights[acl[:acl]] Puppet.info _("Inserting default '%{acl}' (auth %{auth}) ACL") % { acl: acl[:acl], auth: acl[:authenticated] } mk_acl(acl) end end # queue an empty (ie deny all) right for every other path # actually this is not strictly necessary as the rights system # denies not explicitly allowed paths unless rights["/"] rights.newright("/").restrict_authenticated(:any) end end
[ "def", "insert_default_acl", "self", ".", "class", ".", "default_acl", ".", "each", "do", "|", "acl", "|", "unless", "rights", "[", "acl", "[", ":acl", "]", "]", "Puppet", ".", "info", "_", "(", "\"Inserting default '%{acl}' (auth %{auth}) ACL\"", ")", "%", "{", "acl", ":", "acl", "[", ":acl", "]", ",", "auth", ":", "acl", "[", ":authenticated", "]", "}", "mk_acl", "(", "acl", ")", "end", "end", "# queue an empty (ie deny all) right for every other path", "# actually this is not strictly necessary as the rights system", "# denies not explicitly allowed paths", "unless", "rights", "[", "\"/\"", "]", "rights", ".", "newright", "(", "\"/\"", ")", ".", "restrict_authenticated", "(", ":any", ")", "end", "end" ]
force regular ACLs to be present
[ "force", "regular", "ACLs", "to", "be", "present" ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/network/authconfig.rb#L38-L51
10,924
puppetlabs/puppet
lib/puppet/util/windows/adsi.rb
Puppet::Util::Windows::ADSI.User.op_userflags
def op_userflags(*flags, &block) # Avoid an unnecessary set + commit operation. return if flags.empty? unrecognized_flags = flags.reject { |flag| ADS_USERFLAGS.keys.include?(flag) } unless unrecognized_flags.empty? raise ArgumentError, _("Unrecognized ADS UserFlags: %{unrecognized_flags}") % { unrecognized_flags: unrecognized_flags.join(', ') } end self['UserFlags'] = flags.inject(self['UserFlags'], &block) end
ruby
def op_userflags(*flags, &block) # Avoid an unnecessary set + commit operation. return if flags.empty? unrecognized_flags = flags.reject { |flag| ADS_USERFLAGS.keys.include?(flag) } unless unrecognized_flags.empty? raise ArgumentError, _("Unrecognized ADS UserFlags: %{unrecognized_flags}") % { unrecognized_flags: unrecognized_flags.join(', ') } end self['UserFlags'] = flags.inject(self['UserFlags'], &block) end
[ "def", "op_userflags", "(", "*", "flags", ",", "&", "block", ")", "# Avoid an unnecessary set + commit operation.", "return", "if", "flags", ".", "empty?", "unrecognized_flags", "=", "flags", ".", "reject", "{", "|", "flag", "|", "ADS_USERFLAGS", ".", "keys", ".", "include?", "(", "flag", ")", "}", "unless", "unrecognized_flags", ".", "empty?", "raise", "ArgumentError", ",", "_", "(", "\"Unrecognized ADS UserFlags: %{unrecognized_flags}\"", ")", "%", "{", "unrecognized_flags", ":", "unrecognized_flags", ".", "join", "(", "', '", ")", "}", "end", "self", "[", "'UserFlags'", "]", "=", "flags", ".", "inject", "(", "self", "[", "'UserFlags'", "]", ",", "block", ")", "end" ]
Common helper for set_userflags and unset_userflags. @api private
[ "Common", "helper", "for", "set_userflags", "and", "unset_userflags", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/util/windows/adsi.rb#L417-L427
10,925
puppetlabs/puppet
lib/puppet/network/resolver.rb
Puppet::Network.Resolver.each_srv_record
def each_srv_record(domain, service_name = :puppet, &block) if (domain.nil? or domain.empty?) Puppet.debug "Domain not known; skipping SRV lookup" return end Puppet.debug "Searching for SRV records for domain: #{domain}" case service_name when :puppet then service = '_x-puppet' when :file then service = '_x-puppet-fileserver' else service = "_x-puppet-#{service_name.to_s}" end record_name = "#{service}._tcp.#{domain}" if @record_cache.has_key?(service_name) && !expired?(service_name) records = @record_cache[service_name].records Puppet.debug "Using cached record for #{record_name}" else records = @resolver.getresources(record_name, Resolv::DNS::Resource::IN::SRV) if records.size > 0 @record_cache[service_name] = CacheEntry.new(records) end Puppet.debug "Found #{records.size} SRV records for: #{record_name}" end if records.size == 0 && service_name != :puppet # Try the generic :puppet service if no SRV records were found # for the specific service. each_srv_record(domain, :puppet, &block) else each_priority(records) do |recs| while next_rr = recs.delete(find_weighted_server(recs)) Puppet.debug "Yielding next server of #{next_rr.target.to_s}:#{next_rr.port}" yield next_rr.target.to_s, next_rr.port end end end end
ruby
def each_srv_record(domain, service_name = :puppet, &block) if (domain.nil? or domain.empty?) Puppet.debug "Domain not known; skipping SRV lookup" return end Puppet.debug "Searching for SRV records for domain: #{domain}" case service_name when :puppet then service = '_x-puppet' when :file then service = '_x-puppet-fileserver' else service = "_x-puppet-#{service_name.to_s}" end record_name = "#{service}._tcp.#{domain}" if @record_cache.has_key?(service_name) && !expired?(service_name) records = @record_cache[service_name].records Puppet.debug "Using cached record for #{record_name}" else records = @resolver.getresources(record_name, Resolv::DNS::Resource::IN::SRV) if records.size > 0 @record_cache[service_name] = CacheEntry.new(records) end Puppet.debug "Found #{records.size} SRV records for: #{record_name}" end if records.size == 0 && service_name != :puppet # Try the generic :puppet service if no SRV records were found # for the specific service. each_srv_record(domain, :puppet, &block) else each_priority(records) do |recs| while next_rr = recs.delete(find_weighted_server(recs)) Puppet.debug "Yielding next server of #{next_rr.target.to_s}:#{next_rr.port}" yield next_rr.target.to_s, next_rr.port end end end end
[ "def", "each_srv_record", "(", "domain", ",", "service_name", "=", ":puppet", ",", "&", "block", ")", "if", "(", "domain", ".", "nil?", "or", "domain", ".", "empty?", ")", "Puppet", ".", "debug", "\"Domain not known; skipping SRV lookup\"", "return", "end", "Puppet", ".", "debug", "\"Searching for SRV records for domain: #{domain}\"", "case", "service_name", "when", ":puppet", "then", "service", "=", "'_x-puppet'", "when", ":file", "then", "service", "=", "'_x-puppet-fileserver'", "else", "service", "=", "\"_x-puppet-#{service_name.to_s}\"", "end", "record_name", "=", "\"#{service}._tcp.#{domain}\"", "if", "@record_cache", ".", "has_key?", "(", "service_name", ")", "&&", "!", "expired?", "(", "service_name", ")", "records", "=", "@record_cache", "[", "service_name", "]", ".", "records", "Puppet", ".", "debug", "\"Using cached record for #{record_name}\"", "else", "records", "=", "@resolver", ".", "getresources", "(", "record_name", ",", "Resolv", "::", "DNS", "::", "Resource", "::", "IN", "::", "SRV", ")", "if", "records", ".", "size", ">", "0", "@record_cache", "[", "service_name", "]", "=", "CacheEntry", ".", "new", "(", "records", ")", "end", "Puppet", ".", "debug", "\"Found #{records.size} SRV records for: #{record_name}\"", "end", "if", "records", ".", "size", "==", "0", "&&", "service_name", "!=", ":puppet", "# Try the generic :puppet service if no SRV records were found", "# for the specific service.", "each_srv_record", "(", "domain", ",", ":puppet", ",", "block", ")", "else", "each_priority", "(", "records", ")", "do", "|", "recs", "|", "while", "next_rr", "=", "recs", ".", "delete", "(", "find_weighted_server", "(", "recs", ")", ")", "Puppet", ".", "debug", "\"Yielding next server of #{next_rr.target.to_s}:#{next_rr.port}\"", "yield", "next_rr", ".", "target", ".", "to_s", ",", "next_rr", ".", "port", "end", "end", "end", "end" ]
Iterate through the list of records for this service and yield each server and port pair. Records are only fetched via DNS query the first time and cached for the duration of their service's TTL thereafter. @param [String] domain the domain to search for @param [Symbol] service_name the key of the service we are querying @yields [String, Integer] server and port of selected record
[ "Iterate", "through", "the", "list", "of", "records", "for", "this", "service", "and", "yield", "each", "server", "and", "port", "pair", ".", "Records", "are", "only", "fetched", "via", "DNS", "query", "the", "first", "time", "and", "cached", "for", "the", "duration", "of", "their", "service", "s", "TTL", "thereafter", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/network/resolver.rb#L42-L80
10,926
puppetlabs/puppet
lib/puppet/network/resolver.rb
Puppet::Network.Resolver.find_weighted_server
def find_weighted_server(records) return nil if records.nil? || records.empty? return records.first if records.size == 1 # Calculate the sum of all weights in the list of resource records, # This is used to then select hosts until the weight exceeds what # random number we selected. For example, if we have weights of 1 8 and 3: # # |-|--------|---| # ^ # We generate a random number 5, and iterate through the records, adding # the current record's weight to the accumulator until the weight of the # current record plus previous records is greater than the random number. total_weight = records.inject(0) { |sum,record| sum + weight(record) } current_weight = 0 chosen_weight = 1 + Kernel.rand(total_weight) records.each do |record| current_weight += weight(record) return record if current_weight >= chosen_weight end end
ruby
def find_weighted_server(records) return nil if records.nil? || records.empty? return records.first if records.size == 1 # Calculate the sum of all weights in the list of resource records, # This is used to then select hosts until the weight exceeds what # random number we selected. For example, if we have weights of 1 8 and 3: # # |-|--------|---| # ^ # We generate a random number 5, and iterate through the records, adding # the current record's weight to the accumulator until the weight of the # current record plus previous records is greater than the random number. total_weight = records.inject(0) { |sum,record| sum + weight(record) } current_weight = 0 chosen_weight = 1 + Kernel.rand(total_weight) records.each do |record| current_weight += weight(record) return record if current_weight >= chosen_weight end end
[ "def", "find_weighted_server", "(", "records", ")", "return", "nil", "if", "records", ".", "nil?", "||", "records", ".", "empty?", "return", "records", ".", "first", "if", "records", ".", "size", "==", "1", "# Calculate the sum of all weights in the list of resource records,", "# This is used to then select hosts until the weight exceeds what", "# random number we selected. For example, if we have weights of 1 8 and 3:", "#", "# |-|--------|---|", "# ^", "# We generate a random number 5, and iterate through the records, adding", "# the current record's weight to the accumulator until the weight of the", "# current record plus previous records is greater than the random number.", "total_weight", "=", "records", ".", "inject", "(", "0", ")", "{", "|", "sum", ",", "record", "|", "sum", "+", "weight", "(", "record", ")", "}", "current_weight", "=", "0", "chosen_weight", "=", "1", "+", "Kernel", ".", "rand", "(", "total_weight", ")", "records", ".", "each", "do", "|", "record", "|", "current_weight", "+=", "weight", "(", "record", ")", "return", "record", "if", "current_weight", ">=", "chosen_weight", "end", "end" ]
Given a list of records of the same priority, chooses a random one from among them, favoring those with higher weights. @param [[Resolv::DNS::Resource::IN::SRV]] records a list of records of the same priority @return [Resolv::DNS::Resource::IN:SRV] the chosen record
[ "Given", "a", "list", "of", "records", "of", "the", "same", "priority", "chooses", "a", "random", "one", "from", "among", "them", "favoring", "those", "with", "higher", "weights", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/network/resolver.rb#L87-L110
10,927
puppetlabs/puppet
lib/puppet/network/resolver.rb
Puppet::Network.Resolver.expired?
def expired?(service_name) if entry = @record_cache[service_name] return Time.now > (entry.resolution_time + entry.ttl) else return true end end
ruby
def expired?(service_name) if entry = @record_cache[service_name] return Time.now > (entry.resolution_time + entry.ttl) else return true end end
[ "def", "expired?", "(", "service_name", ")", "if", "entry", "=", "@record_cache", "[", "service_name", "]", "return", "Time", ".", "now", ">", "(", "entry", ".", "resolution_time", "+", "entry", ".", "ttl", ")", "else", "return", "true", "end", "end" ]
Checks if the cached entry for the given service has expired. @param [String] service_name the name of the service to check @return [Boolean] true if the entry has expired, false otherwise. Always returns true if the record had no TTL.
[ "Checks", "if", "the", "cached", "entry", "for", "the", "given", "service", "has", "expired", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/network/resolver.rb#L127-L133
10,928
puppetlabs/puppet
lib/puppet/util.rb
Puppet.Util.clear_environment
def clear_environment(mode = default_env) case mode when :posix ENV.clear when :windows Puppet::Util::Windows::Process.get_environment_strings.each do |key, _| Puppet::Util::Windows::Process.set_environment_variable(key, nil) end else raise _("Unable to clear the environment for mode %{mode}") % { mode: mode } end end
ruby
def clear_environment(mode = default_env) case mode when :posix ENV.clear when :windows Puppet::Util::Windows::Process.get_environment_strings.each do |key, _| Puppet::Util::Windows::Process.set_environment_variable(key, nil) end else raise _("Unable to clear the environment for mode %{mode}") % { mode: mode } end end
[ "def", "clear_environment", "(", "mode", "=", "default_env", ")", "case", "mode", "when", ":posix", "ENV", ".", "clear", "when", ":windows", "Puppet", "::", "Util", "::", "Windows", "::", "Process", ".", "get_environment_strings", ".", "each", "do", "|", "key", ",", "_", "|", "Puppet", "::", "Util", "::", "Windows", "::", "Process", ".", "set_environment_variable", "(", "key", ",", "nil", ")", "end", "else", "raise", "_", "(", "\"Unable to clear the environment for mode %{mode}\"", ")", "%", "{", "mode", ":", "mode", "}", "end", "end" ]
Removes all environment variables @param mode [Symbol] Which operating system mode to use e.g. :posix or :windows. Use nil to autodetect @api private
[ "Removes", "all", "environment", "variables" ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/util.rb#L72-L83
10,929
puppetlabs/puppet
lib/puppet/util.rb
Puppet.Util.which
def which(bin) if absolute_path?(bin) return bin if FileTest.file? bin and FileTest.executable? bin else exts = Puppet::Util.get_env('PATHEXT') exts = exts ? exts.split(File::PATH_SEPARATOR) : %w[.COM .EXE .BAT .CMD] Puppet::Util.get_env('PATH').split(File::PATH_SEPARATOR).each do |dir| begin dest = File.expand_path(File.join(dir, bin)) rescue ArgumentError => e # if the user's PATH contains a literal tilde (~) character and HOME is not set, we may get # an ArgumentError here. Let's check to see if that is the case; if not, re-raise whatever error # was thrown. if e.to_s =~ /HOME/ and (Puppet::Util.get_env('HOME').nil? || Puppet::Util.get_env('HOME') == "") # if we get here they have a tilde in their PATH. We'll issue a single warning about this and then # ignore this path element and carry on with our lives. #TRANSLATORS PATH and HOME are environment variables and should not be translated Puppet::Util::Warnings.warnonce(_("PATH contains a ~ character, and HOME is not set; ignoring PATH element '%{dir}'.") % { dir: dir }) elsif e.to_s =~ /doesn't exist|can't find user/ # ...otherwise, we just skip the non-existent entry, and do nothing. #TRANSLATORS PATH is an environment variable and should not be translated Puppet::Util::Warnings.warnonce(_("Couldn't expand PATH containing a ~ character; ignoring PATH element '%{dir}'.") % { dir: dir }) else raise end else if Puppet::Util::Platform.windows? && File.extname(dest).empty? exts.each do |ext| destext = File.expand_path(dest + ext) return destext if FileTest.file? destext and FileTest.executable? destext end end return dest if FileTest.file? dest and FileTest.executable? dest end end end nil end
ruby
def which(bin) if absolute_path?(bin) return bin if FileTest.file? bin and FileTest.executable? bin else exts = Puppet::Util.get_env('PATHEXT') exts = exts ? exts.split(File::PATH_SEPARATOR) : %w[.COM .EXE .BAT .CMD] Puppet::Util.get_env('PATH').split(File::PATH_SEPARATOR).each do |dir| begin dest = File.expand_path(File.join(dir, bin)) rescue ArgumentError => e # if the user's PATH contains a literal tilde (~) character and HOME is not set, we may get # an ArgumentError here. Let's check to see if that is the case; if not, re-raise whatever error # was thrown. if e.to_s =~ /HOME/ and (Puppet::Util.get_env('HOME').nil? || Puppet::Util.get_env('HOME') == "") # if we get here they have a tilde in their PATH. We'll issue a single warning about this and then # ignore this path element and carry on with our lives. #TRANSLATORS PATH and HOME are environment variables and should not be translated Puppet::Util::Warnings.warnonce(_("PATH contains a ~ character, and HOME is not set; ignoring PATH element '%{dir}'.") % { dir: dir }) elsif e.to_s =~ /doesn't exist|can't find user/ # ...otherwise, we just skip the non-existent entry, and do nothing. #TRANSLATORS PATH is an environment variable and should not be translated Puppet::Util::Warnings.warnonce(_("Couldn't expand PATH containing a ~ character; ignoring PATH element '%{dir}'.") % { dir: dir }) else raise end else if Puppet::Util::Platform.windows? && File.extname(dest).empty? exts.each do |ext| destext = File.expand_path(dest + ext) return destext if FileTest.file? destext and FileTest.executable? destext end end return dest if FileTest.file? dest and FileTest.executable? dest end end end nil end
[ "def", "which", "(", "bin", ")", "if", "absolute_path?", "(", "bin", ")", "return", "bin", "if", "FileTest", ".", "file?", "bin", "and", "FileTest", ".", "executable?", "bin", "else", "exts", "=", "Puppet", "::", "Util", ".", "get_env", "(", "'PATHEXT'", ")", "exts", "=", "exts", "?", "exts", ".", "split", "(", "File", "::", "PATH_SEPARATOR", ")", ":", "%w[", ".COM", ".EXE", ".BAT", ".CMD", "]", "Puppet", "::", "Util", ".", "get_env", "(", "'PATH'", ")", ".", "split", "(", "File", "::", "PATH_SEPARATOR", ")", ".", "each", "do", "|", "dir", "|", "begin", "dest", "=", "File", ".", "expand_path", "(", "File", ".", "join", "(", "dir", ",", "bin", ")", ")", "rescue", "ArgumentError", "=>", "e", "# if the user's PATH contains a literal tilde (~) character and HOME is not set, we may get", "# an ArgumentError here. Let's check to see if that is the case; if not, re-raise whatever error", "# was thrown.", "if", "e", ".", "to_s", "=~", "/", "/", "and", "(", "Puppet", "::", "Util", ".", "get_env", "(", "'HOME'", ")", ".", "nil?", "||", "Puppet", "::", "Util", ".", "get_env", "(", "'HOME'", ")", "==", "\"\"", ")", "# if we get here they have a tilde in their PATH. We'll issue a single warning about this and then", "# ignore this path element and carry on with our lives.", "#TRANSLATORS PATH and HOME are environment variables and should not be translated", "Puppet", "::", "Util", "::", "Warnings", ".", "warnonce", "(", "_", "(", "\"PATH contains a ~ character, and HOME is not set; ignoring PATH element '%{dir}'.\"", ")", "%", "{", "dir", ":", "dir", "}", ")", "elsif", "e", ".", "to_s", "=~", "/", "/", "# ...otherwise, we just skip the non-existent entry, and do nothing.", "#TRANSLATORS PATH is an environment variable and should not be translated", "Puppet", "::", "Util", "::", "Warnings", ".", "warnonce", "(", "_", "(", "\"Couldn't expand PATH containing a ~ character; ignoring PATH element '%{dir}'.\"", ")", "%", "{", "dir", ":", "dir", "}", ")", "else", "raise", "end", "else", "if", "Puppet", "::", "Util", "::", "Platform", ".", "windows?", "&&", "File", ".", "extname", "(", "dest", ")", ".", "empty?", "exts", ".", "each", "do", "|", "ext", "|", "destext", "=", "File", ".", "expand_path", "(", "dest", "+", "ext", ")", "return", "destext", "if", "FileTest", ".", "file?", "destext", "and", "FileTest", ".", "executable?", "destext", "end", "end", "return", "dest", "if", "FileTest", ".", "file?", "dest", "and", "FileTest", ".", "executable?", "dest", "end", "end", "end", "nil", "end" ]
Resolve a path for an executable to the absolute path. This tries to behave in the same manner as the unix `which` command and uses the `PATH` environment variable. @api public @param bin [String] the name of the executable to find. @return [String] the absolute path to the found executable.
[ "Resolve", "a", "path", "for", "an", "executable", "to", "the", "absolute", "path", ".", "This", "tries", "to", "behave", "in", "the", "same", "manner", "as", "the", "unix", "which", "command", "and", "uses", "the", "PATH", "environment", "variable", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/util.rb#L248-L285
10,930
puppetlabs/puppet
lib/puppet/util.rb
Puppet.Util.path_to_uri
def path_to_uri(path) return unless path params = { :scheme => 'file' } if Puppet::Util::Platform.windows? path = path.gsub(/\\/, '/') if unc = /^\/\/([^\/]+)(\/.+)/.match(path) params[:host] = unc[1] path = unc[2] elsif path =~ /^[a-z]:\//i path = '/' + path end end # have to split *after* any relevant escaping params[:path], params[:query] = uri_encode(path).split('?') search_for_fragment = params[:query] ? :query : :path if params[search_for_fragment].include?('#') params[search_for_fragment], _, params[:fragment] = params[search_for_fragment].rpartition('#') end begin URI::Generic.build(params) rescue => detail raise Puppet::Error, _("Failed to convert '%{path}' to URI: %{detail}") % { path: path, detail: detail }, detail.backtrace end end
ruby
def path_to_uri(path) return unless path params = { :scheme => 'file' } if Puppet::Util::Platform.windows? path = path.gsub(/\\/, '/') if unc = /^\/\/([^\/]+)(\/.+)/.match(path) params[:host] = unc[1] path = unc[2] elsif path =~ /^[a-z]:\//i path = '/' + path end end # have to split *after* any relevant escaping params[:path], params[:query] = uri_encode(path).split('?') search_for_fragment = params[:query] ? :query : :path if params[search_for_fragment].include?('#') params[search_for_fragment], _, params[:fragment] = params[search_for_fragment].rpartition('#') end begin URI::Generic.build(params) rescue => detail raise Puppet::Error, _("Failed to convert '%{path}' to URI: %{detail}") % { path: path, detail: detail }, detail.backtrace end end
[ "def", "path_to_uri", "(", "path", ")", "return", "unless", "path", "params", "=", "{", ":scheme", "=>", "'file'", "}", "if", "Puppet", "::", "Util", "::", "Platform", ".", "windows?", "path", "=", "path", ".", "gsub", "(", "/", "\\\\", "/", ",", "'/'", ")", "if", "unc", "=", "/", "\\/", "\\/", "\\/", "\\/", "/", ".", "match", "(", "path", ")", "params", "[", ":host", "]", "=", "unc", "[", "1", "]", "path", "=", "unc", "[", "2", "]", "elsif", "path", "=~", "/", "\\/", "/i", "path", "=", "'/'", "+", "path", "end", "end", "# have to split *after* any relevant escaping", "params", "[", ":path", "]", ",", "params", "[", ":query", "]", "=", "uri_encode", "(", "path", ")", ".", "split", "(", "'?'", ")", "search_for_fragment", "=", "params", "[", ":query", "]", "?", ":query", ":", ":path", "if", "params", "[", "search_for_fragment", "]", ".", "include?", "(", "'#'", ")", "params", "[", "search_for_fragment", "]", ",", "_", ",", "params", "[", ":fragment", "]", "=", "params", "[", "search_for_fragment", "]", ".", "rpartition", "(", "'#'", ")", "end", "begin", "URI", "::", "Generic", ".", "build", "(", "params", ")", "rescue", "=>", "detail", "raise", "Puppet", "::", "Error", ",", "_", "(", "\"Failed to convert '%{path}' to URI: %{detail}\"", ")", "%", "{", "path", ":", "path", ",", "detail", ":", "detail", "}", ",", "detail", ".", "backtrace", "end", "end" ]
Convert a path to a file URI
[ "Convert", "a", "path", "to", "a", "file", "URI" ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/util.rb#L319-L347
10,931
puppetlabs/puppet
lib/puppet/util.rb
Puppet.Util.uri_to_path
def uri_to_path(uri) return unless uri.is_a?(URI) # CGI.unescape doesn't handle space rules properly in uri paths # URI.unescape does, but returns strings in their original encoding path = URI.unescape(uri.path.encode(Encoding::UTF_8)) if Puppet::Util::Platform.windows? && uri.scheme == 'file' if uri.host path = "//#{uri.host}" + path # UNC else path.sub!(/^\//, '') end end path end
ruby
def uri_to_path(uri) return unless uri.is_a?(URI) # CGI.unescape doesn't handle space rules properly in uri paths # URI.unescape does, but returns strings in their original encoding path = URI.unescape(uri.path.encode(Encoding::UTF_8)) if Puppet::Util::Platform.windows? && uri.scheme == 'file' if uri.host path = "//#{uri.host}" + path # UNC else path.sub!(/^\//, '') end end path end
[ "def", "uri_to_path", "(", "uri", ")", "return", "unless", "uri", ".", "is_a?", "(", "URI", ")", "# CGI.unescape doesn't handle space rules properly in uri paths", "# URI.unescape does, but returns strings in their original encoding", "path", "=", "URI", ".", "unescape", "(", "uri", ".", "path", ".", "encode", "(", "Encoding", "::", "UTF_8", ")", ")", "if", "Puppet", "::", "Util", "::", "Platform", ".", "windows?", "&&", "uri", ".", "scheme", "==", "'file'", "if", "uri", ".", "host", "path", "=", "\"//#{uri.host}\"", "+", "path", "# UNC", "else", "path", ".", "sub!", "(", "/", "\\/", "/", ",", "''", ")", "end", "end", "path", "end" ]
Get the path component of a URI
[ "Get", "the", "path", "component", "of", "a", "URI" ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/util.rb#L351-L367
10,932
puppetlabs/puppet
lib/puppet/util.rb
Puppet.Util.exit_on_fail
def exit_on_fail(message, code = 1) yield # First, we need to check and see if we are catching a SystemExit error. These will be raised # when we daemonize/fork, and they do not necessarily indicate a failure case. rescue SystemExit => err raise err # Now we need to catch *any* other kind of exception, because we may be calling third-party # code (e.g. webrick), and we have no idea what they might throw. rescue Exception => err ## NOTE: when debugging spec failures, these two lines can be very useful #puts err.inspect #puts Puppet::Util.pretty_backtrace(err.backtrace) Puppet.log_exception(err, "#{message}: #{err}") Puppet::Util::Log.force_flushqueue() exit(code) end
ruby
def exit_on_fail(message, code = 1) yield # First, we need to check and see if we are catching a SystemExit error. These will be raised # when we daemonize/fork, and they do not necessarily indicate a failure case. rescue SystemExit => err raise err # Now we need to catch *any* other kind of exception, because we may be calling third-party # code (e.g. webrick), and we have no idea what they might throw. rescue Exception => err ## NOTE: when debugging spec failures, these two lines can be very useful #puts err.inspect #puts Puppet::Util.pretty_backtrace(err.backtrace) Puppet.log_exception(err, "#{message}: #{err}") Puppet::Util::Log.force_flushqueue() exit(code) end
[ "def", "exit_on_fail", "(", "message", ",", "code", "=", "1", ")", "yield", "# First, we need to check and see if we are catching a SystemExit error. These will be raised", "# when we daemonize/fork, and they do not necessarily indicate a failure case.", "rescue", "SystemExit", "=>", "err", "raise", "err", "# Now we need to catch *any* other kind of exception, because we may be calling third-party", "# code (e.g. webrick), and we have no idea what they might throw.", "rescue", "Exception", "=>", "err", "## NOTE: when debugging spec failures, these two lines can be very useful", "#puts err.inspect", "#puts Puppet::Util.pretty_backtrace(err.backtrace)", "Puppet", ".", "log_exception", "(", "err", ",", "\"#{message}: #{err}\"", ")", "Puppet", "::", "Util", "::", "Log", ".", "force_flushqueue", "(", ")", "exit", "(", "code", ")", "end" ]
Executes a block of code, wrapped with some special exception handling. Causes the ruby interpreter to exit if the block throws an exception. @api public @param [String] message a message to log if the block fails @param [Integer] code the exit code that the ruby interpreter should return if the block fails @yield
[ "Executes", "a", "block", "of", "code", "wrapped", "with", "some", "special", "exception", "handling", ".", "Causes", "the", "ruby", "interpreter", "to", "exit", "if", "the", "block", "throws", "an", "exception", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/util.rb#L683-L699
10,933
puppetlabs/puppet
lib/puppet/pops/evaluator/runtime3_converter.rb
Puppet::Pops::Evaluator.Runtime3Converter.map_args
def map_args(args, scope, undef_value) args.map {|a| convert(a, scope, undef_value) } end
ruby
def map_args(args, scope, undef_value) args.map {|a| convert(a, scope, undef_value) } end
[ "def", "map_args", "(", "args", ",", "scope", ",", "undef_value", ")", "args", ".", "map", "{", "|", "a", "|", "convert", "(", "a", ",", "scope", ",", "undef_value", ")", "}", "end" ]
Converts 4x supported values to a 3x values. @param args [Array] Array of values to convert @param scope [Puppet::Parser::Scope] The scope to use when converting @param undef_value [Object] The value that nil is converted to @return [Array] The converted values
[ "Converts", "4x", "supported", "values", "to", "a", "3x", "values", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/pops/evaluator/runtime3_converter.rb#L48-L50
10,934
puppetlabs/puppet
lib/puppet/type.rb
Puppet.Type.delete
def delete(attr) attr = attr.intern if @parameters.has_key?(attr) @parameters.delete(attr) else raise Puppet::DevError.new(_("Undefined attribute '%{attribute}' in %{name}") % { attribute: attr, name: self}) end end
ruby
def delete(attr) attr = attr.intern if @parameters.has_key?(attr) @parameters.delete(attr) else raise Puppet::DevError.new(_("Undefined attribute '%{attribute}' in %{name}") % { attribute: attr, name: self}) end end
[ "def", "delete", "(", "attr", ")", "attr", "=", "attr", ".", "intern", "if", "@parameters", ".", "has_key?", "(", "attr", ")", "@parameters", ".", "delete", "(", "attr", ")", "else", "raise", "Puppet", "::", "DevError", ".", "new", "(", "_", "(", "\"Undefined attribute '%{attribute}' in %{name}\"", ")", "%", "{", "attribute", ":", "attr", ",", "name", ":", "self", "}", ")", "end", "end" ]
Removes an attribute from the object; useful in testing or in cleanup when an error has been encountered @todo Don't know what the attr is (name or Property/Parameter?). Guessing it is a String name... @todo Is it possible to delete a meta-parameter? @todo What does delete mean? Is it deleted from the type or is its value state 'is'/'should' deleted? @param attr [String] the attribute to delete from this object. WHAT IS THE TYPE? @raise [Puppet::DecError] when an attempt is made to delete an attribute that does not exists.
[ "Removes", "an", "attribute", "from", "the", "object", ";", "useful", "in", "testing", "or", "in", "cleanup", "when", "an", "error", "has", "been", "encountered" ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/type.rb#L700-L707
10,935
puppetlabs/puppet
lib/puppet/type.rb
Puppet.Type.managed?
def managed? # Once an object is managed, it always stays managed; but an object # that is listed as unmanaged might become managed later in the process, # so we have to check that every time if @managed return @managed else @managed = false properties.each { |property| s = property.should if s and ! property.class.unmanaged @managed = true break end } return @managed end end
ruby
def managed? # Once an object is managed, it always stays managed; but an object # that is listed as unmanaged might become managed later in the process, # so we have to check that every time if @managed return @managed else @managed = false properties.each { |property| s = property.should if s and ! property.class.unmanaged @managed = true break end } return @managed end end
[ "def", "managed?", "# Once an object is managed, it always stays managed; but an object", "# that is listed as unmanaged might become managed later in the process,", "# so we have to check that every time", "if", "@managed", "return", "@managed", "else", "@managed", "=", "false", "properties", ".", "each", "{", "|", "property", "|", "s", "=", "property", ".", "should", "if", "s", "and", "!", "property", ".", "class", ".", "unmanaged", "@managed", "=", "true", "break", "end", "}", "return", "@managed", "end", "end" ]
Returns true if the instance is a managed instance. A 'yes' here means that the instance was created from the language, vs. being created in order resolve other questions, such as finding a package in a list. @note An object that is managed always stays managed, but an object that is not managed may become managed later in its lifecycle. @return [Boolean] true if the object is managed
[ "Returns", "true", "if", "the", "instance", "is", "a", "managed", "instance", ".", "A", "yes", "here", "means", "that", "the", "instance", "was", "created", "from", "the", "language", "vs", ".", "being", "created", "in", "order", "resolve", "other", "questions", "such", "as", "finding", "a", "package", "in", "a", "list", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/type.rb#L927-L944
10,936
puppetlabs/puppet
lib/puppet/type.rb
Puppet.Type.retrieve
def retrieve fail "Provider #{provider.class.name} is not functional on this host" if self.provider.is_a?(Puppet::Provider) and ! provider.class.suitable? result = Puppet::Resource.new(self.class, title) # Provide the name, so we know we'll always refer to a real thing result[:name] = self[:name] unless self[:name] == title if ensure_prop = property(:ensure) or (self.class.needs_ensure_retrieved and self.class.validattr?(:ensure) and ensure_prop = newattr(:ensure)) result[:ensure] = ensure_state = ensure_prop.retrieve else ensure_state = nil end properties.each do |property| next if property.name == :ensure if ensure_state == :absent result[property] = :absent else result[property] = property.retrieve end end result end
ruby
def retrieve fail "Provider #{provider.class.name} is not functional on this host" if self.provider.is_a?(Puppet::Provider) and ! provider.class.suitable? result = Puppet::Resource.new(self.class, title) # Provide the name, so we know we'll always refer to a real thing result[:name] = self[:name] unless self[:name] == title if ensure_prop = property(:ensure) or (self.class.needs_ensure_retrieved and self.class.validattr?(:ensure) and ensure_prop = newattr(:ensure)) result[:ensure] = ensure_state = ensure_prop.retrieve else ensure_state = nil end properties.each do |property| next if property.name == :ensure if ensure_state == :absent result[property] = :absent else result[property] = property.retrieve end end result end
[ "def", "retrieve", "fail", "\"Provider #{provider.class.name} is not functional on this host\"", "if", "self", ".", "provider", ".", "is_a?", "(", "Puppet", "::", "Provider", ")", "and", "!", "provider", ".", "class", ".", "suitable?", "result", "=", "Puppet", "::", "Resource", ".", "new", "(", "self", ".", "class", ",", "title", ")", "# Provide the name, so we know we'll always refer to a real thing", "result", "[", ":name", "]", "=", "self", "[", ":name", "]", "unless", "self", "[", ":name", "]", "==", "title", "if", "ensure_prop", "=", "property", "(", ":ensure", ")", "or", "(", "self", ".", "class", ".", "needs_ensure_retrieved", "and", "self", ".", "class", ".", "validattr?", "(", ":ensure", ")", "and", "ensure_prop", "=", "newattr", "(", ":ensure", ")", ")", "result", "[", ":ensure", "]", "=", "ensure_state", "=", "ensure_prop", ".", "retrieve", "else", "ensure_state", "=", "nil", "end", "properties", ".", "each", "do", "|", "property", "|", "next", "if", "property", ".", "name", "==", ":ensure", "if", "ensure_state", "==", ":absent", "result", "[", "property", "]", "=", ":absent", "else", "result", "[", "property", "]", "=", "property", ".", "retrieve", "end", "end", "result", "end" ]
Retrieves the current value of all contained properties. Parameters and meta-parameters are not included in the result. @todo As opposed to all non contained properties? How is this different than any of the other methods that also "gets" properties/parameters/etc. ? @return [Puppet::Resource] array of all property values (mix of types) @raise [fail???] if there is a provider and it is not suitable for the host this is evaluated for.
[ "Retrieves", "the", "current", "value", "of", "all", "contained", "properties", ".", "Parameters", "and", "meta", "-", "parameters", "are", "not", "included", "in", "the", "result", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/type.rb#L1068-L1092
10,937
puppetlabs/puppet
lib/puppet/type.rb
Puppet.Type.builddepends
def builddepends # Handle the requires self.class.relationship_params.collect do |klass| if param = @parameters[klass.name] param.to_edges end end.flatten.reject { |r| r.nil? } end
ruby
def builddepends # Handle the requires self.class.relationship_params.collect do |klass| if param = @parameters[klass.name] param.to_edges end end.flatten.reject { |r| r.nil? } end
[ "def", "builddepends", "# Handle the requires", "self", ".", "class", ".", "relationship_params", ".", "collect", "do", "|", "klass", "|", "if", "param", "=", "@parameters", "[", "klass", ".", "name", "]", "param", ".", "to_edges", "end", "end", ".", "flatten", ".", "reject", "{", "|", "r", "|", "r", ".", "nil?", "}", "end" ]
Builds the dependencies associated with this resource. @return [Array<Puppet::Relationship>] list of relationships to other resources
[ "Builds", "the", "dependencies", "associated", "with", "this", "resource", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/type.rb#L2194-L2201
10,938
puppetlabs/puppet
lib/puppet/type.rb
Puppet.Type.set_sensitive_parameters
def set_sensitive_parameters(sensitive_parameters) sensitive_parameters.each do |name| p = parameter(name) if p.is_a?(Puppet::Property) p.sensitive = true elsif p.is_a?(Puppet::Parameter) warning(_("Unable to mark '%{name}' as sensitive: %{name} is a parameter and not a property, and cannot be automatically redacted.") % { name: name }) elsif self.class.attrclass(name) warning(_("Unable to mark '%{name}' as sensitive: the property itself was not assigned a value.") % { name: name }) else err(_("Unable to mark '%{name}' as sensitive: the property itself is not defined on %{type}.") % { name: name, type: type }) end end parameters.each do |name, param| next if param.sensitive if param.is_a?(Puppet::Parameter) param.sensitive = param.is_sensitive if param.respond_to?(:is_sensitive) end end end
ruby
def set_sensitive_parameters(sensitive_parameters) sensitive_parameters.each do |name| p = parameter(name) if p.is_a?(Puppet::Property) p.sensitive = true elsif p.is_a?(Puppet::Parameter) warning(_("Unable to mark '%{name}' as sensitive: %{name} is a parameter and not a property, and cannot be automatically redacted.") % { name: name }) elsif self.class.attrclass(name) warning(_("Unable to mark '%{name}' as sensitive: the property itself was not assigned a value.") % { name: name }) else err(_("Unable to mark '%{name}' as sensitive: the property itself is not defined on %{type}.") % { name: name, type: type }) end end parameters.each do |name, param| next if param.sensitive if param.is_a?(Puppet::Parameter) param.sensitive = param.is_sensitive if param.respond_to?(:is_sensitive) end end end
[ "def", "set_sensitive_parameters", "(", "sensitive_parameters", ")", "sensitive_parameters", ".", "each", "do", "|", "name", "|", "p", "=", "parameter", "(", "name", ")", "if", "p", ".", "is_a?", "(", "Puppet", "::", "Property", ")", "p", ".", "sensitive", "=", "true", "elsif", "p", ".", "is_a?", "(", "Puppet", "::", "Parameter", ")", "warning", "(", "_", "(", "\"Unable to mark '%{name}' as sensitive: %{name} is a parameter and not a property, and cannot be automatically redacted.\"", ")", "%", "{", "name", ":", "name", "}", ")", "elsif", "self", ".", "class", ".", "attrclass", "(", "name", ")", "warning", "(", "_", "(", "\"Unable to mark '%{name}' as sensitive: the property itself was not assigned a value.\"", ")", "%", "{", "name", ":", "name", "}", ")", "else", "err", "(", "_", "(", "\"Unable to mark '%{name}' as sensitive: the property itself is not defined on %{type}.\"", ")", "%", "{", "name", ":", "name", ",", "type", ":", "type", "}", ")", "end", "end", "parameters", ".", "each", "do", "|", "name", ",", "param", "|", "next", "if", "param", ".", "sensitive", "if", "param", ".", "is_a?", "(", "Puppet", "::", "Parameter", ")", "param", ".", "sensitive", "=", "param", ".", "is_sensitive", "if", "param", ".", "respond_to?", "(", ":is_sensitive", ")", "end", "end", "end" ]
Mark parameters associated with this type as sensitive, based on the associated resource. Currently, only instances of `Puppet::Property` can be easily marked for sensitive data handling and information redaction is limited to redacting events generated while synchronizing properties. While support for redaction will be broadened in the future we can't automatically deduce how to redact arbitrary parameters, so if a parameter is marked for redaction the best we can do is warn that we can't handle treating that parameter as sensitive and move on. In some unusual cases a given parameter will be marked as sensitive but that sensitive context needs to be transferred to another parameter. In this case resource types may need to override this method in order to copy the sensitive context from one parameter to another (and in the process force the early generation of a parameter that might otherwise be lazily generated.) See `Puppet::Type.type(:file)#set_sensitive_parameters` for an example of this. @note This method visibility is protected since it should only be called by #initialize, but is marked as public as subclasses may need to override this method. @api public @param sensitive_parameters [Array<Symbol>] A list of parameters to mark as sensitive. @return [void]
[ "Mark", "parameters", "associated", "with", "this", "type", "as", "sensitive", "based", "on", "the", "associated", "resource", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/type.rb#L2439-L2460
10,939
puppetlabs/puppet
lib/puppet/type.rb
Puppet.Type.finish
def finish # Call post_compile hook on every parameter that implements it. This includes all subclasses # of parameter including, but not limited to, regular parameters, metaparameters, relationship # parameters, and properties. eachparameter do |parameter| parameter.post_compile if parameter.respond_to? :post_compile end # Make sure all of our relationships are valid. Again, must be done # when the entire catalog is instantiated. self.class.relationship_params.collect do |klass| if param = @parameters[klass.name] param.validate_relationship end end.flatten.reject { |r| r.nil? } end
ruby
def finish # Call post_compile hook on every parameter that implements it. This includes all subclasses # of parameter including, but not limited to, regular parameters, metaparameters, relationship # parameters, and properties. eachparameter do |parameter| parameter.post_compile if parameter.respond_to? :post_compile end # Make sure all of our relationships are valid. Again, must be done # when the entire catalog is instantiated. self.class.relationship_params.collect do |klass| if param = @parameters[klass.name] param.validate_relationship end end.flatten.reject { |r| r.nil? } end
[ "def", "finish", "# Call post_compile hook on every parameter that implements it. This includes all subclasses", "# of parameter including, but not limited to, regular parameters, metaparameters, relationship", "# parameters, and properties.", "eachparameter", "do", "|", "parameter", "|", "parameter", ".", "post_compile", "if", "parameter", ".", "respond_to?", ":post_compile", "end", "# Make sure all of our relationships are valid. Again, must be done", "# when the entire catalog is instantiated.", "self", ".", "class", ".", "relationship_params", ".", "collect", "do", "|", "klass", "|", "if", "param", "=", "@parameters", "[", "klass", ".", "name", "]", "param", ".", "validate_relationship", "end", "end", ".", "flatten", ".", "reject", "{", "|", "r", "|", "r", ".", "nil?", "}", "end" ]
Finishes any outstanding processing. This method should be called as a final step in setup, to allow the parameters that have associated auto-require needs to be processed. @todo what is the expected sequence here - who is responsible for calling this? When? Is the returned type correct? @return [Array<Puppet::Parameter>] the validated list/set of attributes
[ "Finishes", "any", "outstanding", "processing", ".", "This", "method", "should", "be", "called", "as", "a", "final", "step", "in", "setup", "to", "allow", "the", "parameters", "that", "have", "associated", "auto", "-", "require", "needs", "to", "be", "processed", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/type.rb#L2528-L2543
10,940
puppetlabs/puppet
lib/puppet/environments.rb
Puppet::Environments.EnvironmentCreator.for
def for(module_path, manifest) Puppet::Node::Environment.create(:anonymous, module_path.split(File::PATH_SEPARATOR), manifest) end
ruby
def for(module_path, manifest) Puppet::Node::Environment.create(:anonymous, module_path.split(File::PATH_SEPARATOR), manifest) end
[ "def", "for", "(", "module_path", ",", "manifest", ")", "Puppet", "::", "Node", "::", "Environment", ".", "create", "(", ":anonymous", ",", "module_path", ".", "split", "(", "File", "::", "PATH_SEPARATOR", ")", ",", "manifest", ")", "end" ]
Create an anonymous environment. @param module_path [String] A list of module directories separated by the PATH_SEPARATOR @param manifest [String] The path to the manifest @return A new environment with the `name` `:anonymous` @api private
[ "Create", "an", "anonymous", "environment", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/environments.rb#L21-L25
10,941
puppetlabs/puppet
lib/puppet/environments.rb
Puppet::Environments.Static.get_conf
def get_conf(name) env = get(name) if env Puppet::Settings::EnvironmentConf.static_for(env, Puppet[:environment_timeout], Puppet[:static_catalogs], Puppet[:rich_data]) else nil end end
ruby
def get_conf(name) env = get(name) if env Puppet::Settings::EnvironmentConf.static_for(env, Puppet[:environment_timeout], Puppet[:static_catalogs], Puppet[:rich_data]) else nil end end
[ "def", "get_conf", "(", "name", ")", "env", "=", "get", "(", "name", ")", "if", "env", "Puppet", "::", "Settings", "::", "EnvironmentConf", ".", "static_for", "(", "env", ",", "Puppet", "[", ":environment_timeout", "]", ",", "Puppet", "[", ":static_catalogs", "]", ",", "Puppet", "[", ":rich_data", "]", ")", "else", "nil", "end", "end" ]
Returns a basic environment configuration object tied to the environment's implementation values. Will not interpolate. @!macro loader_get_conf
[ "Returns", "a", "basic", "environment", "configuration", "object", "tied", "to", "the", "environment", "s", "implementation", "values", ".", "Will", "not", "interpolate", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/environments.rb#L115-L122
10,942
puppetlabs/puppet
lib/puppet/environments.rb
Puppet::Environments.Cached.add_entry
def add_entry(name, cache_entry) Puppet.debug {"Caching environment '#{name}' #{cache_entry.label}"} @cache[name] = cache_entry expires = cache_entry.expires @expirations.add(expires) if @next_expiration > expires @next_expiration = expires end end
ruby
def add_entry(name, cache_entry) Puppet.debug {"Caching environment '#{name}' #{cache_entry.label}"} @cache[name] = cache_entry expires = cache_entry.expires @expirations.add(expires) if @next_expiration > expires @next_expiration = expires end end
[ "def", "add_entry", "(", "name", ",", "cache_entry", ")", "Puppet", ".", "debug", "{", "\"Caching environment '#{name}' #{cache_entry.label}\"", "}", "@cache", "[", "name", "]", "=", "cache_entry", "expires", "=", "cache_entry", ".", "expires", "@expirations", ".", "add", "(", "expires", ")", "if", "@next_expiration", ">", "expires", "@next_expiration", "=", "expires", "end", "end" ]
Adds a cache entry to the cache
[ "Adds", "a", "cache", "entry", "to", "the", "cache" ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/environments.rb#L365-L373
10,943
puppetlabs/puppet
lib/puppet/environments.rb
Puppet::Environments.Cached.clear_all_expired
def clear_all_expired() t = Time.now return if t < @next_expiration && ! @cache.any? {|name, _| @cache_expiration_service.expired?(name.to_sym) } to_expire = @cache.select { |name, entry| entry.expires < t || @cache_expiration_service.expired?(name.to_sym) } to_expire.each do |name, entry| Puppet.debug {"Evicting cache entry for environment '#{name}'"} @cache_expiration_service.evicted(name) clear(name) @expirations.delete(entry.expires) Puppet.settings.clear_environment_settings(name) end @next_expiration = @expirations.first || END_OF_TIME end
ruby
def clear_all_expired() t = Time.now return if t < @next_expiration && ! @cache.any? {|name, _| @cache_expiration_service.expired?(name.to_sym) } to_expire = @cache.select { |name, entry| entry.expires < t || @cache_expiration_service.expired?(name.to_sym) } to_expire.each do |name, entry| Puppet.debug {"Evicting cache entry for environment '#{name}'"} @cache_expiration_service.evicted(name) clear(name) @expirations.delete(entry.expires) Puppet.settings.clear_environment_settings(name) end @next_expiration = @expirations.first || END_OF_TIME end
[ "def", "clear_all_expired", "(", ")", "t", "=", "Time", ".", "now", "return", "if", "t", "<", "@next_expiration", "&&", "!", "@cache", ".", "any?", "{", "|", "name", ",", "_", "|", "@cache_expiration_service", ".", "expired?", "(", "name", ".", "to_sym", ")", "}", "to_expire", "=", "@cache", ".", "select", "{", "|", "name", ",", "entry", "|", "entry", ".", "expires", "<", "t", "||", "@cache_expiration_service", ".", "expired?", "(", "name", ".", "to_sym", ")", "}", "to_expire", ".", "each", "do", "|", "name", ",", "entry", "|", "Puppet", ".", "debug", "{", "\"Evicting cache entry for environment '#{name}'\"", "}", "@cache_expiration_service", ".", "evicted", "(", "name", ")", "clear", "(", "name", ")", "@expirations", ".", "delete", "(", "entry", ".", "expires", ")", "Puppet", ".", "settings", ".", "clear_environment_settings", "(", "name", ")", "end", "@next_expiration", "=", "@expirations", ".", "first", "||", "END_OF_TIME", "end" ]
Clears all environments that have expired, either by exceeding their time to live, or through an explicit eviction determined by the cache expiration service.
[ "Clears", "all", "environments", "that", "have", "expired", "either", "by", "exceeding", "their", "time", "to", "live", "or", "through", "an", "explicit", "eviction", "determined", "by", "the", "cache", "expiration", "service", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/environments.rb#L396-L408
10,944
puppetlabs/puppet
lib/puppet/environments.rb
Puppet::Environments.Cached.entry
def entry(env) ttl = (conf = get_conf(env.name)) ? conf.environment_timeout : Puppet.settings.value(:environment_timeout) case ttl when 0 NotCachedEntry.new(env) # Entry that is always expired (avoids syscall to get time) when Float::INFINITY Entry.new(env) # Entry that never expires (avoids syscall to get time) else TTLEntry.new(env, ttl) end end
ruby
def entry(env) ttl = (conf = get_conf(env.name)) ? conf.environment_timeout : Puppet.settings.value(:environment_timeout) case ttl when 0 NotCachedEntry.new(env) # Entry that is always expired (avoids syscall to get time) when Float::INFINITY Entry.new(env) # Entry that never expires (avoids syscall to get time) else TTLEntry.new(env, ttl) end end
[ "def", "entry", "(", "env", ")", "ttl", "=", "(", "conf", "=", "get_conf", "(", "env", ".", "name", ")", ")", "?", "conf", ".", "environment_timeout", ":", "Puppet", ".", "settings", ".", "value", "(", ":environment_timeout", ")", "case", "ttl", "when", "0", "NotCachedEntry", ".", "new", "(", "env", ")", "# Entry that is always expired (avoids syscall to get time)", "when", "Float", "::", "INFINITY", "Entry", ".", "new", "(", "env", ")", "# Entry that never expires (avoids syscall to get time)", "else", "TTLEntry", ".", "new", "(", "env", ",", "ttl", ")", "end", "end" ]
Creates a suitable cache entry given the time to live for one environment
[ "Creates", "a", "suitable", "cache", "entry", "given", "the", "time", "to", "live", "for", "one", "environment" ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/environments.rb#L425-L435
10,945
puppetlabs/puppet
lib/puppet/environments.rb
Puppet::Environments.Cached.evict_if_expired
def evict_if_expired(name) if (result = @cache[name]) && (result.expired? || @cache_expiration_service.expired?(name)) Puppet.debug {"Evicting cache entry for environment '#{name}'"} @cache_expiration_service.evicted(name) clear(name) Puppet.settings.clear_environment_settings(name) end end
ruby
def evict_if_expired(name) if (result = @cache[name]) && (result.expired? || @cache_expiration_service.expired?(name)) Puppet.debug {"Evicting cache entry for environment '#{name}'"} @cache_expiration_service.evicted(name) clear(name) Puppet.settings.clear_environment_settings(name) end end
[ "def", "evict_if_expired", "(", "name", ")", "if", "(", "result", "=", "@cache", "[", "name", "]", ")", "&&", "(", "result", ".", "expired?", "||", "@cache_expiration_service", ".", "expired?", "(", "name", ")", ")", "Puppet", ".", "debug", "{", "\"Evicting cache entry for environment '#{name}'\"", "}", "@cache_expiration_service", ".", "evicted", "(", "name", ")", "clear", "(", "name", ")", "Puppet", ".", "settings", ".", "clear_environment_settings", "(", "name", ")", "end", "end" ]
Evicts the entry if it has expired Also clears caches in Settings that may prevent the entry from being updated
[ "Evicts", "the", "entry", "if", "it", "has", "expired", "Also", "clears", "caches", "in", "Settings", "that", "may", "prevent", "the", "entry", "from", "being", "updated" ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/environments.rb#L439-L446
10,946
puppetlabs/puppet
lib/puppet/module_tool/checksums.rb
Puppet::ModuleTool.Checksums.data
def data unless @data @data = {} @path.find do |descendant| if Puppet::ModuleTool.artifact?(descendant) Find.prune elsif descendant.file? path = descendant.relative_path_from(@path) @data[path.to_s] = checksum(descendant) end end end return @data end
ruby
def data unless @data @data = {} @path.find do |descendant| if Puppet::ModuleTool.artifact?(descendant) Find.prune elsif descendant.file? path = descendant.relative_path_from(@path) @data[path.to_s] = checksum(descendant) end end end return @data end
[ "def", "data", "unless", "@data", "@data", "=", "{", "}", "@path", ".", "find", "do", "|", "descendant", "|", "if", "Puppet", "::", "ModuleTool", ".", "artifact?", "(", "descendant", ")", "Find", ".", "prune", "elsif", "descendant", ".", "file?", "path", "=", "descendant", ".", "relative_path_from", "(", "@path", ")", "@data", "[", "path", ".", "to_s", "]", "=", "checksum", "(", "descendant", ")", "end", "end", "end", "return", "@data", "end" ]
Return checksums for object's +Pathname+, generate if it's needed. Result is a hash of path strings to checksum strings.
[ "Return", "checksums", "for", "object", "s", "+", "Pathname", "+", "generate", "if", "it", "s", "needed", ".", "Result", "is", "a", "hash", "of", "path", "strings", "to", "checksum", "strings", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/module_tool/checksums.rb#L26-L39
10,947
puppetlabs/puppet
lib/puppet/rest/route.rb
Puppet::Rest.Route.with_base_url
def with_base_url(dns_resolver) if @server && @port # First try connecting to the previously selected server and port. begin return yield(base_url) rescue SystemCallError => e if Puppet[:use_srv_records] Puppet.debug "Connection to cached server and port #{@server}:#{@port} failed, reselecting." else raise Puppet::Error, _("Connection to cached server and port %{server}:%{port} failed: %{message}") % { server: @server, port: @port, message: e.message } end end end if Puppet[:use_srv_records] dns_resolver.each_srv_record(Puppet[:srv_domain], @srv_service) do |srv_server, srv_port| # Try each of the servers for this service in weighted order # until a working one is found. begin @server = srv_server @port = srv_port return yield(base_url) rescue SystemCallError Puppet.debug "Connection to selected server and port #{@server}:#{@port} failed. Trying next cached SRV record." @server = nil @port = nil end end end # If not using SRV records, fall back to the defaults calculated above @server = @default_server @port = @default_port Puppet.debug "No more servers in SRV record, falling back to #{@server}:#{@port}" if Puppet[:use_srv_records] return yield(base_url) end
ruby
def with_base_url(dns_resolver) if @server && @port # First try connecting to the previously selected server and port. begin return yield(base_url) rescue SystemCallError => e if Puppet[:use_srv_records] Puppet.debug "Connection to cached server and port #{@server}:#{@port} failed, reselecting." else raise Puppet::Error, _("Connection to cached server and port %{server}:%{port} failed: %{message}") % { server: @server, port: @port, message: e.message } end end end if Puppet[:use_srv_records] dns_resolver.each_srv_record(Puppet[:srv_domain], @srv_service) do |srv_server, srv_port| # Try each of the servers for this service in weighted order # until a working one is found. begin @server = srv_server @port = srv_port return yield(base_url) rescue SystemCallError Puppet.debug "Connection to selected server and port #{@server}:#{@port} failed. Trying next cached SRV record." @server = nil @port = nil end end end # If not using SRV records, fall back to the defaults calculated above @server = @default_server @port = @default_port Puppet.debug "No more servers in SRV record, falling back to #{@server}:#{@port}" if Puppet[:use_srv_records] return yield(base_url) end
[ "def", "with_base_url", "(", "dns_resolver", ")", "if", "@server", "&&", "@port", "# First try connecting to the previously selected server and port.", "begin", "return", "yield", "(", "base_url", ")", "rescue", "SystemCallError", "=>", "e", "if", "Puppet", "[", ":use_srv_records", "]", "Puppet", ".", "debug", "\"Connection to cached server and port #{@server}:#{@port} failed, reselecting.\"", "else", "raise", "Puppet", "::", "Error", ",", "_", "(", "\"Connection to cached server and port %{server}:%{port} failed: %{message}\"", ")", "%", "{", "server", ":", "@server", ",", "port", ":", "@port", ",", "message", ":", "e", ".", "message", "}", "end", "end", "end", "if", "Puppet", "[", ":use_srv_records", "]", "dns_resolver", ".", "each_srv_record", "(", "Puppet", "[", ":srv_domain", "]", ",", "@srv_service", ")", "do", "|", "srv_server", ",", "srv_port", "|", "# Try each of the servers for this service in weighted order", "# until a working one is found.", "begin", "@server", "=", "srv_server", "@port", "=", "srv_port", "return", "yield", "(", "base_url", ")", "rescue", "SystemCallError", "Puppet", ".", "debug", "\"Connection to selected server and port #{@server}:#{@port} failed. Trying next cached SRV record.\"", "@server", "=", "nil", "@port", "=", "nil", "end", "end", "end", "# If not using SRV records, fall back to the defaults calculated above", "@server", "=", "@default_server", "@port", "=", "@default_port", "Puppet", ".", "debug", "\"No more servers in SRV record, falling back to #{@server}:#{@port}\"", "if", "Puppet", "[", ":use_srv_records", "]", "return", "yield", "(", "base_url", ")", "end" ]
Create a Route containing information for querying the given API, hosted at a server determined either by SRV service or by the fallback server on the fallback port. @param [String] api the path leading to the root of the API. Must contain a trailing slash for proper endpoint path construction @param [Symbol] server_setting the setting to check for special server configuration @param [Symbol] port_setting the setting to check for speical port configuration @param [Symbol] srv_service the name of the service when using SRV records Select a server and port to create a base URL for the API specified by this route. If the connection fails and SRV records are in use, the next suitable server will be tried. If SRV records are not in use or no successful connection could be made, fall back to the configured server and port for this API, taking into account failover settings. @parma [Puppet::Network::Resolver] dns_resolver the DNS resolver to use to check SRV records @yield [URI] supply a base URL to make a request with @raise [Puppet::Error] if connection to selected server and port fails, and SRV records are not in use
[ "Create", "a", "Route", "containing", "information", "for", "querying", "the", "given", "API", "hosted", "at", "a", "server", "determined", "either", "by", "SRV", "service", "or", "by", "the", "fallback", "server", "on", "the", "fallback", "port", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/rest/route.rb#L37-L74
10,948
puppetlabs/puppet
lib/puppet/application.rb
Puppet.Application.run
def run # I don't really like the names of these lifecycle phases. It would be nice to change them to some more meaningful # names, and make deprecated aliases. --cprice 2012-03-16 exit_on_fail(_("Could not get application-specific default settings")) do initialize_app_defaults end Puppet::ApplicationSupport.push_application_context(self.class.run_mode, self.class.get_environment_mode) exit_on_fail(_("Could not initialize")) { preinit } exit_on_fail(_("Could not parse application options")) { parse_options } exit_on_fail(_("Could not prepare for execution")) { setup } if deprecated? Puppet.deprecation_warning(_("`puppet %{name}` is deprecated and will be removed in a future release.") % { name: name }) end exit_on_fail(_("Could not configure routes from %{route_file}") % { route_file: Puppet[:route_file] }) { configure_indirector_routes } exit_on_fail(_("Could not log runtime debug info")) { log_runtime_environment } exit_on_fail(_("Could not run")) { run_command } end
ruby
def run # I don't really like the names of these lifecycle phases. It would be nice to change them to some more meaningful # names, and make deprecated aliases. --cprice 2012-03-16 exit_on_fail(_("Could not get application-specific default settings")) do initialize_app_defaults end Puppet::ApplicationSupport.push_application_context(self.class.run_mode, self.class.get_environment_mode) exit_on_fail(_("Could not initialize")) { preinit } exit_on_fail(_("Could not parse application options")) { parse_options } exit_on_fail(_("Could not prepare for execution")) { setup } if deprecated? Puppet.deprecation_warning(_("`puppet %{name}` is deprecated and will be removed in a future release.") % { name: name }) end exit_on_fail(_("Could not configure routes from %{route_file}") % { route_file: Puppet[:route_file] }) { configure_indirector_routes } exit_on_fail(_("Could not log runtime debug info")) { log_runtime_environment } exit_on_fail(_("Could not run")) { run_command } end
[ "def", "run", "# I don't really like the names of these lifecycle phases. It would be nice to change them to some more meaningful", "# names, and make deprecated aliases. --cprice 2012-03-16", "exit_on_fail", "(", "_", "(", "\"Could not get application-specific default settings\"", ")", ")", "do", "initialize_app_defaults", "end", "Puppet", "::", "ApplicationSupport", ".", "push_application_context", "(", "self", ".", "class", ".", "run_mode", ",", "self", ".", "class", ".", "get_environment_mode", ")", "exit_on_fail", "(", "_", "(", "\"Could not initialize\"", ")", ")", "{", "preinit", "}", "exit_on_fail", "(", "_", "(", "\"Could not parse application options\"", ")", ")", "{", "parse_options", "}", "exit_on_fail", "(", "_", "(", "\"Could not prepare for execution\"", ")", ")", "{", "setup", "}", "if", "deprecated?", "Puppet", ".", "deprecation_warning", "(", "_", "(", "\"`puppet %{name}` is deprecated and will be removed in a future release.\"", ")", "%", "{", "name", ":", "name", "}", ")", "end", "exit_on_fail", "(", "_", "(", "\"Could not configure routes from %{route_file}\"", ")", "%", "{", "route_file", ":", "Puppet", "[", ":route_file", "]", "}", ")", "{", "configure_indirector_routes", "}", "exit_on_fail", "(", "_", "(", "\"Could not log runtime debug info\"", ")", ")", "{", "log_runtime_environment", "}", "exit_on_fail", "(", "_", "(", "\"Could not run\"", ")", ")", "{", "run_command", "}", "end" ]
Execute the application. @api public @return [void]
[ "Execute", "the", "application", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/application.rb#L361-L383
10,949
puppetlabs/puppet
lib/puppet/application.rb
Puppet.Application.log_runtime_environment
def log_runtime_environment(extra_info=nil) runtime_info = { 'puppet_version' => Puppet.version, 'ruby_version' => RUBY_VERSION, 'run_mode' => self.class.run_mode.name, } runtime_info['default_encoding'] = Encoding.default_external runtime_info.merge!(extra_info) unless extra_info.nil? Puppet.debug 'Runtime environment: ' + runtime_info.map{|k,v| k + '=' + v.to_s}.join(', ') end
ruby
def log_runtime_environment(extra_info=nil) runtime_info = { 'puppet_version' => Puppet.version, 'ruby_version' => RUBY_VERSION, 'run_mode' => self.class.run_mode.name, } runtime_info['default_encoding'] = Encoding.default_external runtime_info.merge!(extra_info) unless extra_info.nil? Puppet.debug 'Runtime environment: ' + runtime_info.map{|k,v| k + '=' + v.to_s}.join(', ') end
[ "def", "log_runtime_environment", "(", "extra_info", "=", "nil", ")", "runtime_info", "=", "{", "'puppet_version'", "=>", "Puppet", ".", "version", ",", "'ruby_version'", "=>", "RUBY_VERSION", ",", "'run_mode'", "=>", "self", ".", "class", ".", "run_mode", ".", "name", ",", "}", "runtime_info", "[", "'default_encoding'", "]", "=", "Encoding", ".", "default_external", "runtime_info", ".", "merge!", "(", "extra_info", ")", "unless", "extra_info", ".", "nil?", "Puppet", ".", "debug", "'Runtime environment: '", "+", "runtime_info", ".", "map", "{", "|", "k", ",", "v", "|", "k", "+", "'='", "+", "v", ".", "to_s", "}", ".", "join", "(", "', '", ")", "end" ]
Output basic information about the runtime environment for debugging purposes. @api public @param extra_info [Hash{String => #to_s}] a flat hash of extra information to log. Intended to be passed to super by subclasses. @return [void]
[ "Output", "basic", "information", "about", "the", "runtime", "environment", "for", "debugging", "purposes", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/application.rb#L444-L454
10,950
puppetlabs/puppet
lib/puppet/functions.rb
Puppet::Functions.DispatcherBuilder.required_repeated_param
def required_repeated_param(type, name) internal_param(type, name, true) raise ArgumentError, _('A required repeated parameter cannot be added after an optional parameter') if @min != @max @min += 1 @max = :default end
ruby
def required_repeated_param(type, name) internal_param(type, name, true) raise ArgumentError, _('A required repeated parameter cannot be added after an optional parameter') if @min != @max @min += 1 @max = :default end
[ "def", "required_repeated_param", "(", "type", ",", "name", ")", "internal_param", "(", "type", ",", "name", ",", "true", ")", "raise", "ArgumentError", ",", "_", "(", "'A required repeated parameter cannot be added after an optional parameter'", ")", "if", "@min", "!=", "@max", "@min", "+=", "1", "@max", "=", ":default", "end" ]
Defines a repeated positional parameter with _type_ and _name_ that may occur 1 to "infinite" number of times. It may only appear last or just before a block parameter. @param type [String] The type specification for the parameter. @param name [Symbol] The name of the parameter. This is primarily used for error message output and does not have to match an implementation method parameter. @return [Void] @api public
[ "Defines", "a", "repeated", "positional", "parameter", "with", "_type_", "and", "_name_", "that", "may", "occur", "1", "to", "infinite", "number", "of", "times", ".", "It", "may", "only", "appear", "last", "or", "just", "before", "a", "block", "parameter", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/functions.rb#L461-L466
10,951
puppetlabs/puppet
lib/puppet/functions.rb
Puppet::Functions.DispatcherBuilder.block_param
def block_param(*type_and_name) case type_and_name.size when 0 type = @all_callables name = :block when 1 type = @all_callables name = type_and_name[0] when 2 type, name = type_and_name type = Puppet::Pops::Types::TypeParser.singleton.parse(type, loader) unless type.is_a?(Puppet::Pops::Types::PAnyType) else raise ArgumentError, _("block_param accepts max 2 arguments (type, name), got %{size}.") % { size: type_and_name.size } end unless Puppet::Pops::Types::TypeCalculator.is_kind_of_callable?(type, false) raise ArgumentError, _("Expected PCallableType or PVariantType thereof, got %{type_class}") % { type_class: type.class } end unless name.is_a?(Symbol) raise ArgumentError, _("Expected block_param name to be a Symbol, got %{name_class}") % { name_class: name.class } end if @block_type.nil? @block_type = type @block_name = name else raise ArgumentError, _('Attempt to redefine block') end end
ruby
def block_param(*type_and_name) case type_and_name.size when 0 type = @all_callables name = :block when 1 type = @all_callables name = type_and_name[0] when 2 type, name = type_and_name type = Puppet::Pops::Types::TypeParser.singleton.parse(type, loader) unless type.is_a?(Puppet::Pops::Types::PAnyType) else raise ArgumentError, _("block_param accepts max 2 arguments (type, name), got %{size}.") % { size: type_and_name.size } end unless Puppet::Pops::Types::TypeCalculator.is_kind_of_callable?(type, false) raise ArgumentError, _("Expected PCallableType or PVariantType thereof, got %{type_class}") % { type_class: type.class } end unless name.is_a?(Symbol) raise ArgumentError, _("Expected block_param name to be a Symbol, got %{name_class}") % { name_class: name.class } end if @block_type.nil? @block_type = type @block_name = name else raise ArgumentError, _('Attempt to redefine block') end end
[ "def", "block_param", "(", "*", "type_and_name", ")", "case", "type_and_name", ".", "size", "when", "0", "type", "=", "@all_callables", "name", "=", ":block", "when", "1", "type", "=", "@all_callables", "name", "=", "type_and_name", "[", "0", "]", "when", "2", "type", ",", "name", "=", "type_and_name", "type", "=", "Puppet", "::", "Pops", "::", "Types", "::", "TypeParser", ".", "singleton", ".", "parse", "(", "type", ",", "loader", ")", "unless", "type", ".", "is_a?", "(", "Puppet", "::", "Pops", "::", "Types", "::", "PAnyType", ")", "else", "raise", "ArgumentError", ",", "_", "(", "\"block_param accepts max 2 arguments (type, name), got %{size}.\"", ")", "%", "{", "size", ":", "type_and_name", ".", "size", "}", "end", "unless", "Puppet", "::", "Pops", "::", "Types", "::", "TypeCalculator", ".", "is_kind_of_callable?", "(", "type", ",", "false", ")", "raise", "ArgumentError", ",", "_", "(", "\"Expected PCallableType or PVariantType thereof, got %{type_class}\"", ")", "%", "{", "type_class", ":", "type", ".", "class", "}", "end", "unless", "name", ".", "is_a?", "(", "Symbol", ")", "raise", "ArgumentError", ",", "_", "(", "\"Expected block_param name to be a Symbol, got %{name_class}\"", ")", "%", "{", "name_class", ":", "name", ".", "class", "}", "end", "if", "@block_type", ".", "nil?", "@block_type", "=", "type", "@block_name", "=", "name", "else", "raise", "ArgumentError", ",", "_", "(", "'Attempt to redefine block'", ")", "end", "end" ]
Defines one required block parameter that may appear last. If type and name is missing the default type is "Callable", and the name is "block". If only one parameter is given, then that is the name and the type is "Callable". @api public
[ "Defines", "one", "required", "block", "parameter", "that", "may", "appear", "last", ".", "If", "type", "and", "name", "is", "missing", "the", "default", "type", "is", "Callable", "and", "the", "name", "is", "block", ".", "If", "only", "one", "parameter", "is", "given", "then", "that", "is", "the", "name", "and", "the", "type", "is", "Callable", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/functions.rb#L473-L502
10,952
puppetlabs/puppet
lib/puppet/functions.rb
Puppet::Functions.LocalTypeAliasesBuilder.type
def type(assignment_string) # Get location to use in case of error - this produces ruby filename and where call to 'type' occurred # but strips off the rest of the internal "where" as it is not meaningful to user. # rb_location = caller[0] begin result = parser.parse_string("type #{assignment_string}", nil) rescue StandardError => e rb_location = rb_location.gsub(/:in.*$/, '') # Create a meaningful location for parse errors - show both what went wrong with the parsing # and in which ruby file it was found. raise ArgumentError, _("Parsing of 'type \"%{assignment_string}\"' failed with message: <%{message}>.\n" + "Called from <%{ruby_file_location}>") % { assignment_string: assignment_string, message: e.message, ruby_file_location: rb_location } end unless result.body.kind_of?(Puppet::Pops::Model::TypeAlias) rb_location = rb_location.gsub(/:in.*$/, '') raise ArgumentError, _("Expected a type alias assignment on the form 'AliasType = T', got '%{assignment_string}'.\n"+ "Called from <%{ruby_file_location}>") % { assignment_string: assignment_string, ruby_file_location: rb_location } end @local_types << result.body end
ruby
def type(assignment_string) # Get location to use in case of error - this produces ruby filename and where call to 'type' occurred # but strips off the rest of the internal "where" as it is not meaningful to user. # rb_location = caller[0] begin result = parser.parse_string("type #{assignment_string}", nil) rescue StandardError => e rb_location = rb_location.gsub(/:in.*$/, '') # Create a meaningful location for parse errors - show both what went wrong with the parsing # and in which ruby file it was found. raise ArgumentError, _("Parsing of 'type \"%{assignment_string}\"' failed with message: <%{message}>.\n" + "Called from <%{ruby_file_location}>") % { assignment_string: assignment_string, message: e.message, ruby_file_location: rb_location } end unless result.body.kind_of?(Puppet::Pops::Model::TypeAlias) rb_location = rb_location.gsub(/:in.*$/, '') raise ArgumentError, _("Expected a type alias assignment on the form 'AliasType = T', got '%{assignment_string}'.\n"+ "Called from <%{ruby_file_location}>") % { assignment_string: assignment_string, ruby_file_location: rb_location } end @local_types << result.body end
[ "def", "type", "(", "assignment_string", ")", "# Get location to use in case of error - this produces ruby filename and where call to 'type' occurred", "# but strips off the rest of the internal \"where\" as it is not meaningful to user.", "#", "rb_location", "=", "caller", "[", "0", "]", "begin", "result", "=", "parser", ".", "parse_string", "(", "\"type #{assignment_string}\"", ",", "nil", ")", "rescue", "StandardError", "=>", "e", "rb_location", "=", "rb_location", ".", "gsub", "(", "/", "/", ",", "''", ")", "# Create a meaningful location for parse errors - show both what went wrong with the parsing", "# and in which ruby file it was found.", "raise", "ArgumentError", ",", "_", "(", "\"Parsing of 'type \\\"%{assignment_string}\\\"' failed with message: <%{message}>.\\n\"", "+", "\"Called from <%{ruby_file_location}>\"", ")", "%", "{", "assignment_string", ":", "assignment_string", ",", "message", ":", "e", ".", "message", ",", "ruby_file_location", ":", "rb_location", "}", "end", "unless", "result", ".", "body", ".", "kind_of?", "(", "Puppet", "::", "Pops", "::", "Model", "::", "TypeAlias", ")", "rb_location", "=", "rb_location", ".", "gsub", "(", "/", "/", ",", "''", ")", "raise", "ArgumentError", ",", "_", "(", "\"Expected a type alias assignment on the form 'AliasType = T', got '%{assignment_string}'.\\n\"", "+", "\"Called from <%{ruby_file_location}>\"", ")", "%", "{", "assignment_string", ":", "assignment_string", ",", "ruby_file_location", ":", "rb_location", "}", "end", "@local_types", "<<", "result", ".", "body", "end" ]
Defines a local type alias, the given string should be a Puppet Language type alias expression in string form without the leading 'type' keyword. Calls to local_type must be made before the first parameter definition or an error will be raised. @param assignment_string [String] a string on the form 'AliasType = ExistingType' @api public
[ "Defines", "a", "local", "type", "alias", "the", "given", "string", "should", "be", "a", "Puppet", "Language", "type", "alias", "expression", "in", "string", "form", "without", "the", "leading", "type", "keyword", ".", "Calls", "to", "local_type", "must", "be", "made", "before", "the", "first", "parameter", "definition", "or", "an", "error", "will", "be", "raised", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/functions.rb#L623-L651
10,953
puppetlabs/puppet
lib/puppet/pops/merge_strategy.rb
Puppet::Pops.MergeStrategy.lookup
def lookup(lookup_variants, lookup_invocation) case lookup_variants.size when 0 throw :no_such_key when 1 merge_single(yield(lookup_variants[0])) else lookup_invocation.with(:merge, self) do result = lookup_variants.reduce(NOT_FOUND) do |memo, lookup_variant| not_found = true value = catch(:no_such_key) do v = yield(lookup_variant) not_found = false v end if not_found memo else memo.equal?(NOT_FOUND) ? convert_value(value) : merge(memo, value) end end throw :no_such_key if result == NOT_FOUND lookup_invocation.report_result(result) end end end
ruby
def lookup(lookup_variants, lookup_invocation) case lookup_variants.size when 0 throw :no_such_key when 1 merge_single(yield(lookup_variants[0])) else lookup_invocation.with(:merge, self) do result = lookup_variants.reduce(NOT_FOUND) do |memo, lookup_variant| not_found = true value = catch(:no_such_key) do v = yield(lookup_variant) not_found = false v end if not_found memo else memo.equal?(NOT_FOUND) ? convert_value(value) : merge(memo, value) end end throw :no_such_key if result == NOT_FOUND lookup_invocation.report_result(result) end end end
[ "def", "lookup", "(", "lookup_variants", ",", "lookup_invocation", ")", "case", "lookup_variants", ".", "size", "when", "0", "throw", ":no_such_key", "when", "1", "merge_single", "(", "yield", "(", "lookup_variants", "[", "0", "]", ")", ")", "else", "lookup_invocation", ".", "with", "(", ":merge", ",", "self", ")", "do", "result", "=", "lookup_variants", ".", "reduce", "(", "NOT_FOUND", ")", "do", "|", "memo", ",", "lookup_variant", "|", "not_found", "=", "true", "value", "=", "catch", "(", ":no_such_key", ")", "do", "v", "=", "yield", "(", "lookup_variant", ")", "not_found", "=", "false", "v", "end", "if", "not_found", "memo", "else", "memo", ".", "equal?", "(", "NOT_FOUND", ")", "?", "convert_value", "(", "value", ")", ":", "merge", "(", "memo", ",", "value", ")", "end", "end", "throw", ":no_such_key", "if", "result", "==", "NOT_FOUND", "lookup_invocation", ".", "report_result", "(", "result", ")", "end", "end", "end" ]
Merges the result of yielding the given _lookup_variants_ to a given block. @param lookup_variants [Array] The variants to pass as second argument to the given block @return [Object] the merged value. @yield [} ] @yieldparam variant [Object] each variant given in the _lookup_variants_ array. @yieldreturn [Object] the value to merge with other values @throws :no_such_key if the lookup was unsuccessful Merges the result of yielding the given _lookup_variants_ to a given block. @param lookup_variants [Array] The variants to pass as second argument to the given block @return [Object] the merged value. @yield [} ] @yieldparam variant [Object] each variant given in the _lookup_variants_ array. @yieldreturn [Object] the value to merge with other values @throws :no_such_key if the lookup was unsuccessful
[ "Merges", "the", "result", "of", "yielding", "the", "given", "_lookup_variants_", "to", "a", "given", "block", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/pops/merge_strategy.rb#L121-L146
10,954
puppetlabs/puppet
lib/puppet/network/http/compression.rb
Puppet::Network::HTTP::Compression.Active.uncompress_body
def uncompress_body(response) case response['content-encoding'] when 'gzip' # ZLib::GzipReader has an associated encoding, by default Encoding.default_external return Zlib::GzipReader.new(StringIO.new(response.body), :encoding => Encoding::BINARY).read when 'deflate' return Zlib::Inflate.new.inflate(response.body) when nil, 'identity' return response.body else raise Net::HTTPError.new(_("Unknown content encoding - %{encoding}") % { encoding: response['content-encoding'] }, response) end end
ruby
def uncompress_body(response) case response['content-encoding'] when 'gzip' # ZLib::GzipReader has an associated encoding, by default Encoding.default_external return Zlib::GzipReader.new(StringIO.new(response.body), :encoding => Encoding::BINARY).read when 'deflate' return Zlib::Inflate.new.inflate(response.body) when nil, 'identity' return response.body else raise Net::HTTPError.new(_("Unknown content encoding - %{encoding}") % { encoding: response['content-encoding'] }, response) end end
[ "def", "uncompress_body", "(", "response", ")", "case", "response", "[", "'content-encoding'", "]", "when", "'gzip'", "# ZLib::GzipReader has an associated encoding, by default Encoding.default_external", "return", "Zlib", "::", "GzipReader", ".", "new", "(", "StringIO", ".", "new", "(", "response", ".", "body", ")", ",", ":encoding", "=>", "Encoding", "::", "BINARY", ")", ".", "read", "when", "'deflate'", "return", "Zlib", "::", "Inflate", ".", "new", ".", "inflate", "(", "response", ".", "body", ")", "when", "nil", ",", "'identity'", "return", "response", ".", "body", "else", "raise", "Net", "::", "HTTPError", ".", "new", "(", "_", "(", "\"Unknown content encoding - %{encoding}\"", ")", "%", "{", "encoding", ":", "response", "[", "'content-encoding'", "]", "}", ",", "response", ")", "end", "end" ]
return an uncompressed body if the response has been compressed
[ "return", "an", "uncompressed", "body", "if", "the", "response", "has", "been", "compressed" ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/network/http/compression.rb#L20-L32
10,955
puppetlabs/puppet
lib/puppet/network/rights.rb
Puppet::Network.Rights.newright
def newright(name, line=nil, file=nil) add_right( Right.new(name, line, file) ) end
ruby
def newright(name, line=nil, file=nil) add_right( Right.new(name, line, file) ) end
[ "def", "newright", "(", "name", ",", "line", "=", "nil", ",", "file", "=", "nil", ")", "add_right", "(", "Right", ".", "new", "(", "name", ",", "line", ",", "file", ")", ")", "end" ]
Define a new right to which access can be provided.
[ "Define", "a", "new", "right", "to", "which", "access", "can", "be", "provided", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/network/rights.rb#L82-L84
10,956
puppetlabs/puppet
lib/puppet/network/authstore.rb
Puppet.Network::AuthStore.allowed?
def allowed?(name, ip) if name or ip # This is probably unnecessary, and can cause some weirdness in # cases where we're operating over localhost but don't have a real # IP defined. raise Puppet::DevError, _("Name and IP must be passed to 'allowed?'") unless name and ip # else, we're networked and such else # we're local return true end # yay insecure overrides return true if globalallow? if decl = declarations.find { |d| d.match?(name, ip) } return decl.result end info _("defaulting to no access for %{name}") % { name: name } false end
ruby
def allowed?(name, ip) if name or ip # This is probably unnecessary, and can cause some weirdness in # cases where we're operating over localhost but don't have a real # IP defined. raise Puppet::DevError, _("Name and IP must be passed to 'allowed?'") unless name and ip # else, we're networked and such else # we're local return true end # yay insecure overrides return true if globalallow? if decl = declarations.find { |d| d.match?(name, ip) } return decl.result end info _("defaulting to no access for %{name}") % { name: name } false end
[ "def", "allowed?", "(", "name", ",", "ip", ")", "if", "name", "or", "ip", "# This is probably unnecessary, and can cause some weirdness in", "# cases where we're operating over localhost but don't have a real", "# IP defined.", "raise", "Puppet", "::", "DevError", ",", "_", "(", "\"Name and IP must be passed to 'allowed?'\"", ")", "unless", "name", "and", "ip", "# else, we're networked and such", "else", "# we're local", "return", "true", "end", "# yay insecure overrides", "return", "true", "if", "globalallow?", "if", "decl", "=", "declarations", ".", "find", "{", "|", "d", "|", "d", ".", "match?", "(", "name", ",", "ip", ")", "}", "return", "decl", ".", "result", "end", "info", "_", "(", "\"defaulting to no access for %{name}\"", ")", "%", "{", "name", ":", "name", "}", "false", "end" ]
Is a given combination of name and ip address allowed? If either input is non-nil, then both inputs must be provided. If neither input is provided, then the authstore is considered local and defaults to "true".
[ "Is", "a", "given", "combination", "of", "name", "and", "ip", "address", "allowed?", "If", "either", "input", "is", "non", "-", "nil", "then", "both", "inputs", "must", "be", "provided", ".", "If", "neither", "input", "is", "provided", "then", "the", "authstore", "is", "considered", "local", "and", "defaults", "to", "true", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/network/authstore.rb#L17-L38
10,957
puppetlabs/puppet
lib/puppet/metatype/manager.rb
Puppet::MetaType.Manager.type
def type(name) # Avoid loading if name obviously is not a type name if name.to_s.include?(':') return nil end @types ||= {} # We are overwhelmingly symbols here, which usually match, so it is worth # having this special-case to return quickly. Like, 25K symbols vs. 300 # strings in this method. --daniel 2012-07-17 return @types[name] if @types.include? name # Try mangling the name, if it is a string. if name.is_a? String name = name.downcase.intern return @types[name] if @types.include? name end # Try loading the type. if typeloader.load(name, Puppet.lookup(:current_environment)) #TRANSLATORS 'puppet/type/%{name}' should not be translated Puppet.warning(_("Loaded puppet/type/%{name} but no class was created") % { name: name }) unless @types.include? name elsif !Puppet[:always_retry_plugins] # PUP-5482 - Only look for a type once if plugin retry is disabled @types[name] = nil end # ...and I guess that is that, eh. return @types[name] end
ruby
def type(name) # Avoid loading if name obviously is not a type name if name.to_s.include?(':') return nil end @types ||= {} # We are overwhelmingly symbols here, which usually match, so it is worth # having this special-case to return quickly. Like, 25K symbols vs. 300 # strings in this method. --daniel 2012-07-17 return @types[name] if @types.include? name # Try mangling the name, if it is a string. if name.is_a? String name = name.downcase.intern return @types[name] if @types.include? name end # Try loading the type. if typeloader.load(name, Puppet.lookup(:current_environment)) #TRANSLATORS 'puppet/type/%{name}' should not be translated Puppet.warning(_("Loaded puppet/type/%{name} but no class was created") % { name: name }) unless @types.include? name elsif !Puppet[:always_retry_plugins] # PUP-5482 - Only look for a type once if plugin retry is disabled @types[name] = nil end # ...and I guess that is that, eh. return @types[name] end
[ "def", "type", "(", "name", ")", "# Avoid loading if name obviously is not a type name", "if", "name", ".", "to_s", ".", "include?", "(", "':'", ")", "return", "nil", "end", "@types", "||=", "{", "}", "# We are overwhelmingly symbols here, which usually match, so it is worth", "# having this special-case to return quickly. Like, 25K symbols vs. 300", "# strings in this method. --daniel 2012-07-17", "return", "@types", "[", "name", "]", "if", "@types", ".", "include?", "name", "# Try mangling the name, if it is a string.", "if", "name", ".", "is_a?", "String", "name", "=", "name", ".", "downcase", ".", "intern", "return", "@types", "[", "name", "]", "if", "@types", ".", "include?", "name", "end", "# Try loading the type.", "if", "typeloader", ".", "load", "(", "name", ",", "Puppet", ".", "lookup", "(", ":current_environment", ")", ")", "#TRANSLATORS 'puppet/type/%{name}' should not be translated", "Puppet", ".", "warning", "(", "_", "(", "\"Loaded puppet/type/%{name} but no class was created\"", ")", "%", "{", "name", ":", "name", "}", ")", "unless", "@types", ".", "include?", "name", "elsif", "!", "Puppet", "[", ":always_retry_plugins", "]", "# PUP-5482 - Only look for a type once if plugin retry is disabled", "@types", "[", "name", "]", "=", "nil", "end", "# ...and I guess that is that, eh.", "return", "@types", "[", "name", "]", "end" ]
Returns a Type instance by name. This will load the type if not already defined. @param [String, Symbol] name of the wanted Type @return [Puppet::Type, nil] the type or nil if the type was not defined and could not be loaded
[ "Returns", "a", "Type", "instance", "by", "name", ".", "This", "will", "load", "the", "type", "if", "not", "already", "defined", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/metatype/manager.rb#L153-L182
10,958
puppetlabs/puppet
lib/puppet/pops/loaders.rb
Puppet::Pops.Loaders.[]
def [](loader_name) loader = @loaders_by_name[loader_name] if loader.nil? # Unable to find the module private loader. Try resolving the module loader = private_loader_for_module(loader_name[0..-9]) if loader_name.end_with?(' private') raise Puppet::ParseError, _("Unable to find loader named '%{loader_name}'") % { loader_name: loader_name } if loader.nil? end loader end
ruby
def [](loader_name) loader = @loaders_by_name[loader_name] if loader.nil? # Unable to find the module private loader. Try resolving the module loader = private_loader_for_module(loader_name[0..-9]) if loader_name.end_with?(' private') raise Puppet::ParseError, _("Unable to find loader named '%{loader_name}'") % { loader_name: loader_name } if loader.nil? end loader end
[ "def", "[]", "(", "loader_name", ")", "loader", "=", "@loaders_by_name", "[", "loader_name", "]", "if", "loader", ".", "nil?", "# Unable to find the module private loader. Try resolving the module", "loader", "=", "private_loader_for_module", "(", "loader_name", "[", "0", "..", "-", "9", "]", ")", "if", "loader_name", ".", "end_with?", "(", "' private'", ")", "raise", "Puppet", "::", "ParseError", ",", "_", "(", "\"Unable to find loader named '%{loader_name}'\"", ")", "%", "{", "loader_name", ":", "loader_name", "}", "if", "loader", ".", "nil?", "end", "loader", "end" ]
Lookup a loader by its unique name. @param [String] loader_name the name of the loader to lookup @return [Loader] the found loader @raise [Puppet::ParserError] if no loader is found
[ "Lookup", "a", "loader", "by", "its", "unique", "name", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/pops/loaders.rb#L183-L191
10,959
puppetlabs/puppet
lib/puppet/pops/loaders.rb
Puppet::Pops.Loaders.find_loader
def find_loader(module_name) if module_name.nil? || EMPTY_STRING == module_name # Use the public environment loader public_environment_loader else # TODO : Later check if definition is private, and then add it to private_loader_for_module # loader = public_loader_for_module(module_name) if loader.nil? raise Puppet::ParseError, _("Internal Error: did not find public loader for module: '%{module_name}'") % { module_name: module_name } end loader end end
ruby
def find_loader(module_name) if module_name.nil? || EMPTY_STRING == module_name # Use the public environment loader public_environment_loader else # TODO : Later check if definition is private, and then add it to private_loader_for_module # loader = public_loader_for_module(module_name) if loader.nil? raise Puppet::ParseError, _("Internal Error: did not find public loader for module: '%{module_name}'") % { module_name: module_name } end loader end end
[ "def", "find_loader", "(", "module_name", ")", "if", "module_name", ".", "nil?", "||", "EMPTY_STRING", "==", "module_name", "# Use the public environment loader", "public_environment_loader", "else", "# TODO : Later check if definition is private, and then add it to private_loader_for_module", "#", "loader", "=", "public_loader_for_module", "(", "module_name", ")", "if", "loader", ".", "nil?", "raise", "Puppet", "::", "ParseError", ",", "_", "(", "\"Internal Error: did not find public loader for module: '%{module_name}'\"", ")", "%", "{", "module_name", ":", "module_name", "}", "end", "loader", "end", "end" ]
Finds the appropriate loader for the given `module_name`, or for the environment in case `module_name` is `nil` or empty. @param module_name [String,nil] the name of the module @return [Loader::Loader] the found loader @raise [Puppet::ParseError] if no loader can be found @api private
[ "Finds", "the", "appropriate", "loader", "for", "the", "given", "module_name", "or", "for", "the", "environment", "in", "case", "module_name", "is", "nil", "or", "empty", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/pops/loaders.rb#L200-L213
10,960
puppetlabs/puppet
lib/puppet/pops/loaders.rb
Puppet::Pops.Loaders.load_main_manifest
def load_main_manifest parser = Parser::EvaluatingParser.singleton parsed_code = Puppet[:code] program = if parsed_code != "" parser.parse_string(parsed_code, 'unknown-source-location') else file = @environment.manifest # if the manifest file is a reference to a directory, parse and combine # all .pp files in that directory if file == Puppet::Node::Environment::NO_MANIFEST nil elsif File.directory?(file) raise Puppet::Error, "manifest of environment '#{@environment.name}' appoints directory '#{file}'. It must be a file" elsif File.exists?(file) parser.parse_file(file) else raise Puppet::Error, "manifest of environment '#{@environment.name}' appoints '#{file}'. It does not exist" end end instantiate_definitions(program, public_environment_loader) unless program.nil? program rescue Puppet::ParseErrorWithIssue => detail detail.environment = @environment.name raise rescue => detail msg = _('Could not parse for environment %{env}: %{detail}') % { env: @environment, detail: detail } error = Puppet::Error.new(msg) error.set_backtrace(detail.backtrace) raise error end
ruby
def load_main_manifest parser = Parser::EvaluatingParser.singleton parsed_code = Puppet[:code] program = if parsed_code != "" parser.parse_string(parsed_code, 'unknown-source-location') else file = @environment.manifest # if the manifest file is a reference to a directory, parse and combine # all .pp files in that directory if file == Puppet::Node::Environment::NO_MANIFEST nil elsif File.directory?(file) raise Puppet::Error, "manifest of environment '#{@environment.name}' appoints directory '#{file}'. It must be a file" elsif File.exists?(file) parser.parse_file(file) else raise Puppet::Error, "manifest of environment '#{@environment.name}' appoints '#{file}'. It does not exist" end end instantiate_definitions(program, public_environment_loader) unless program.nil? program rescue Puppet::ParseErrorWithIssue => detail detail.environment = @environment.name raise rescue => detail msg = _('Could not parse for environment %{env}: %{detail}') % { env: @environment, detail: detail } error = Puppet::Error.new(msg) error.set_backtrace(detail.backtrace) raise error end
[ "def", "load_main_manifest", "parser", "=", "Parser", "::", "EvaluatingParser", ".", "singleton", "parsed_code", "=", "Puppet", "[", ":code", "]", "program", "=", "if", "parsed_code", "!=", "\"\"", "parser", ".", "parse_string", "(", "parsed_code", ",", "'unknown-source-location'", ")", "else", "file", "=", "@environment", ".", "manifest", "# if the manifest file is a reference to a directory, parse and combine", "# all .pp files in that directory", "if", "file", "==", "Puppet", "::", "Node", "::", "Environment", "::", "NO_MANIFEST", "nil", "elsif", "File", ".", "directory?", "(", "file", ")", "raise", "Puppet", "::", "Error", ",", "\"manifest of environment '#{@environment.name}' appoints directory '#{file}'. It must be a file\"", "elsif", "File", ".", "exists?", "(", "file", ")", "parser", ".", "parse_file", "(", "file", ")", "else", "raise", "Puppet", "::", "Error", ",", "\"manifest of environment '#{@environment.name}' appoints '#{file}'. It does not exist\"", "end", "end", "instantiate_definitions", "(", "program", ",", "public_environment_loader", ")", "unless", "program", ".", "nil?", "program", "rescue", "Puppet", "::", "ParseErrorWithIssue", "=>", "detail", "detail", ".", "environment", "=", "@environment", ".", "name", "raise", "rescue", "=>", "detail", "msg", "=", "_", "(", "'Could not parse for environment %{env}: %{detail}'", ")", "%", "{", "env", ":", "@environment", ",", "detail", ":", "detail", "}", "error", "=", "Puppet", "::", "Error", ".", "new", "(", "msg", ")", "error", ".", "set_backtrace", "(", "detail", ".", "backtrace", ")", "raise", "error", "end" ]
Load the main manifest for the given environment There are two sources that can be used for the initial parse: 1. The value of `Puppet[:code]`: Puppet can take a string from its settings and parse that as a manifest. This is used by various Puppet applications to read in a manifest and pass it to the environment as a side effect. This is attempted first. 2. The contents of the environment's +manifest+ attribute: Puppet will try to load the environment manifest. The manifest must be a file. @return [Model::Program] The manifest parsed into a model object
[ "Load", "the", "main", "manifest", "for", "the", "given", "environment" ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/pops/loaders.rb#L272-L302
10,961
puppetlabs/puppet
lib/puppet/pops/loaders.rb
Puppet::Pops.Loaders.instantiate_definitions
def instantiate_definitions(program, loader) program.definitions.each { |d| instantiate_definition(d, loader) } nil end
ruby
def instantiate_definitions(program, loader) program.definitions.each { |d| instantiate_definition(d, loader) } nil end
[ "def", "instantiate_definitions", "(", "program", ",", "loader", ")", "program", ".", "definitions", ".", "each", "{", "|", "d", "|", "instantiate_definition", "(", "d", ",", "loader", ")", "}", "nil", "end" ]
Add 4.x definitions found in the given program to the given loader.
[ "Add", "4", ".", "x", "definitions", "found", "in", "the", "given", "program", "to", "the", "given", "loader", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/pops/loaders.rb#L305-L308
10,962
puppetlabs/puppet
lib/puppet/pops/loaders.rb
Puppet::Pops.Loaders.instantiate_definition
def instantiate_definition(definition, loader) case definition when Model::PlanDefinition instantiate_PlanDefinition(definition, loader) when Model::FunctionDefinition instantiate_FunctionDefinition(definition, loader) when Model::TypeAlias instantiate_TypeAlias(definition, loader) when Model::TypeMapping instantiate_TypeMapping(definition, loader) else raise Puppet::ParseError, "Internal Error: Unknown type of definition - got '#{definition.class}'" end end
ruby
def instantiate_definition(definition, loader) case definition when Model::PlanDefinition instantiate_PlanDefinition(definition, loader) when Model::FunctionDefinition instantiate_FunctionDefinition(definition, loader) when Model::TypeAlias instantiate_TypeAlias(definition, loader) when Model::TypeMapping instantiate_TypeMapping(definition, loader) else raise Puppet::ParseError, "Internal Error: Unknown type of definition - got '#{definition.class}'" end end
[ "def", "instantiate_definition", "(", "definition", ",", "loader", ")", "case", "definition", "when", "Model", "::", "PlanDefinition", "instantiate_PlanDefinition", "(", "definition", ",", "loader", ")", "when", "Model", "::", "FunctionDefinition", "instantiate_FunctionDefinition", "(", "definition", ",", "loader", ")", "when", "Model", "::", "TypeAlias", "instantiate_TypeAlias", "(", "definition", ",", "loader", ")", "when", "Model", "::", "TypeMapping", "instantiate_TypeMapping", "(", "definition", ",", "loader", ")", "else", "raise", "Puppet", "::", "ParseError", ",", "\"Internal Error: Unknown type of definition - got '#{definition.class}'\"", "end", "end" ]
Add given 4.x definition to the given loader.
[ "Add", "given", "4", ".", "x", "definition", "to", "the", "given", "loader", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/pops/loaders.rb#L311-L324
10,963
puppetlabs/puppet
lib/puppet/util/inifile.rb
Puppet::Util::IniConfig.Section.[]=
def []=(key, value) entry = find_entry(key) @dirty = true if entry.nil? @entries << [key, value] else entry[1] = value end end
ruby
def []=(key, value) entry = find_entry(key) @dirty = true if entry.nil? @entries << [key, value] else entry[1] = value end end
[ "def", "[]=", "(", "key", ",", "value", ")", "entry", "=", "find_entry", "(", "key", ")", "@dirty", "=", "true", "if", "entry", ".", "nil?", "@entries", "<<", "[", "key", ",", "value", "]", "else", "entry", "[", "1", "]", "=", "value", "end", "end" ]
Set the entry 'key=value'. If no entry with the given key exists, one is appended to the end of the section
[ "Set", "the", "entry", "key", "=", "value", ".", "If", "no", "entry", "with", "the", "given", "key", "exists", "one", "is", "appended", "to", "the", "end", "of", "the", "section" ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/util/inifile.rb#L60-L68
10,964
puppetlabs/puppet
lib/puppet/util/inifile.rb
Puppet::Util::IniConfig.Section.format
def format if @destroy text = "" else text = "[#{name}]\n" @entries.each do |entry| if entry.is_a?(Array) key, value = entry text << "#{key}=#{value}\n" unless value.nil? else text << entry end end end text end
ruby
def format if @destroy text = "" else text = "[#{name}]\n" @entries.each do |entry| if entry.is_a?(Array) key, value = entry text << "#{key}=#{value}\n" unless value.nil? else text << entry end end end text end
[ "def", "format", "if", "@destroy", "text", "=", "\"\"", "else", "text", "=", "\"[#{name}]\\n\"", "@entries", ".", "each", "do", "|", "entry", "|", "if", "entry", ".", "is_a?", "(", "Array", ")", "key", ",", "value", "=", "entry", "text", "<<", "\"#{key}=#{value}\\n\"", "unless", "value", ".", "nil?", "else", "text", "<<", "entry", "end", "end", "end", "text", "end" ]
Format the section as text in the way it should be written to file
[ "Format", "the", "section", "as", "text", "in", "the", "way", "it", "should", "be", "written", "to", "file" ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/util/inifile.rb#L79-L94
10,965
puppetlabs/puppet
lib/puppet/util/inifile.rb
Puppet::Util::IniConfig.PhysicalFile.read
def read text = @filetype.read if text.nil? raise IniParseError, _("Cannot read nonexistent file %{file}") % { file: @file.inspect } end parse(text) end
ruby
def read text = @filetype.read if text.nil? raise IniParseError, _("Cannot read nonexistent file %{file}") % { file: @file.inspect } end parse(text) end
[ "def", "read", "text", "=", "@filetype", ".", "read", "if", "text", ".", "nil?", "raise", "IniParseError", ",", "_", "(", "\"Cannot read nonexistent file %{file}\"", ")", "%", "{", "file", ":", "@file", ".", "inspect", "}", "end", "parse", "(", "text", ")", "end" ]
Read and parse the on-disk file associated with this object
[ "Read", "and", "parse", "the", "on", "-", "disk", "file", "associated", "with", "this", "object" ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/util/inifile.rb#L136-L142
10,966
puppetlabs/puppet
lib/puppet/util/inifile.rb
Puppet::Util::IniConfig.PhysicalFile.add_section
def add_section(name) if section_exists?(name) raise IniParseError.new(_("Section %{name} is already defined, cannot redefine") % { name: name.inspect }, @file) end section = Section.new(name, @file) @contents << section section end
ruby
def add_section(name) if section_exists?(name) raise IniParseError.new(_("Section %{name} is already defined, cannot redefine") % { name: name.inspect }, @file) end section = Section.new(name, @file) @contents << section section end
[ "def", "add_section", "(", "name", ")", "if", "section_exists?", "(", "name", ")", "raise", "IniParseError", ".", "new", "(", "_", "(", "\"Section %{name} is already defined, cannot redefine\"", ")", "%", "{", "name", ":", "name", ".", "inspect", "}", ",", "@file", ")", "end", "section", "=", "Section", ".", "new", "(", "name", ",", "@file", ")", "@contents", "<<", "section", "section", "end" ]
Create a new section and store it in the file contents @api private @param name [String] The name of the section to create @return [Puppet::Util::IniConfig::Section]
[ "Create", "a", "new", "section", "and", "store", "it", "in", "the", "file", "contents" ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/util/inifile.rb#L238-L247
10,967
puppetlabs/puppet
lib/puppet/error.rb
Puppet.ExternalFileError.to_s
def to_s msg = super @file = nil if (@file.is_a?(String) && @file.empty?) msg += Puppet::Util::Errors.error_location_with_space(@file, @line, @pos) msg end
ruby
def to_s msg = super @file = nil if (@file.is_a?(String) && @file.empty?) msg += Puppet::Util::Errors.error_location_with_space(@file, @line, @pos) msg end
[ "def", "to_s", "msg", "=", "super", "@file", "=", "nil", "if", "(", "@file", ".", "is_a?", "(", "String", ")", "&&", "@file", ".", "empty?", ")", "msg", "+=", "Puppet", "::", "Util", "::", "Errors", ".", "error_location_with_space", "(", "@file", ",", "@line", ",", "@pos", ")", "msg", "end" ]
May be called with 3 arguments for message, file, line, and exception, or 4 args including the position on the line.
[ "May", "be", "called", "with", "3", "arguments", "for", "message", "file", "line", "and", "exception", "or", "4", "args", "including", "the", "position", "on", "the", "line", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/error.rb#L31-L36
10,968
puppetlabs/puppet
lib/puppet/network/http/connection.rb
Puppet::Network::HTTP.Connection.handle_retry_after
def handle_retry_after(response) retry_after = response['Retry-After'] return response if retry_after.nil? retry_sleep = parse_retry_after_header(retry_after) # Recover remote hostname if Net::HTTPResponse was generated by a # method that fills in the uri attribute. # server_hostname = if response.uri.is_a?(URI) response.uri.host else # TRANSLATORS: Used in the phrase: # "Received a response from the remote server." _('the remote server') end if retry_sleep.nil? Puppet.err(_('Received a %{status_code} response from %{server_hostname}, but the Retry-After header value of "%{retry_after}" could not be converted to an integer or RFC 2822 date.') % {status_code: response.code, server_hostname: server_hostname, retry_after: retry_after.inspect}) return response end # Cap maximum sleep at the run interval of the Puppet agent. retry_sleep = [retry_sleep, Puppet[:runinterval]].min Puppet.warning(_('Received a %{status_code} response from %{server_hostname}. Sleeping for %{retry_sleep} seconds before retrying the request.') % {status_code: response.code, server_hostname: server_hostname, retry_sleep: retry_sleep}) ::Kernel.sleep(retry_sleep) return nil end
ruby
def handle_retry_after(response) retry_after = response['Retry-After'] return response if retry_after.nil? retry_sleep = parse_retry_after_header(retry_after) # Recover remote hostname if Net::HTTPResponse was generated by a # method that fills in the uri attribute. # server_hostname = if response.uri.is_a?(URI) response.uri.host else # TRANSLATORS: Used in the phrase: # "Received a response from the remote server." _('the remote server') end if retry_sleep.nil? Puppet.err(_('Received a %{status_code} response from %{server_hostname}, but the Retry-After header value of "%{retry_after}" could not be converted to an integer or RFC 2822 date.') % {status_code: response.code, server_hostname: server_hostname, retry_after: retry_after.inspect}) return response end # Cap maximum sleep at the run interval of the Puppet agent. retry_sleep = [retry_sleep, Puppet[:runinterval]].min Puppet.warning(_('Received a %{status_code} response from %{server_hostname}. Sleeping for %{retry_sleep} seconds before retrying the request.') % {status_code: response.code, server_hostname: server_hostname, retry_sleep: retry_sleep}) ::Kernel.sleep(retry_sleep) return nil end
[ "def", "handle_retry_after", "(", "response", ")", "retry_after", "=", "response", "[", "'Retry-After'", "]", "return", "response", "if", "retry_after", ".", "nil?", "retry_sleep", "=", "parse_retry_after_header", "(", "retry_after", ")", "# Recover remote hostname if Net::HTTPResponse was generated by a", "# method that fills in the uri attribute.", "#", "server_hostname", "=", "if", "response", ".", "uri", ".", "is_a?", "(", "URI", ")", "response", ".", "uri", ".", "host", "else", "# TRANSLATORS: Used in the phrase:", "# \"Received a response from the remote server.\"", "_", "(", "'the remote server'", ")", "end", "if", "retry_sleep", ".", "nil?", "Puppet", ".", "err", "(", "_", "(", "'Received a %{status_code} response from %{server_hostname}, but the Retry-After header value of \"%{retry_after}\" could not be converted to an integer or RFC 2822 date.'", ")", "%", "{", "status_code", ":", "response", ".", "code", ",", "server_hostname", ":", "server_hostname", ",", "retry_after", ":", "retry_after", ".", "inspect", "}", ")", "return", "response", "end", "# Cap maximum sleep at the run interval of the Puppet agent.", "retry_sleep", "=", "[", "retry_sleep", ",", "Puppet", "[", ":runinterval", "]", "]", ".", "min", "Puppet", ".", "warning", "(", "_", "(", "'Received a %{status_code} response from %{server_hostname}. Sleeping for %{retry_sleep} seconds before retrying the request.'", ")", "%", "{", "status_code", ":", "response", ".", "code", ",", "server_hostname", ":", "server_hostname", ",", "retry_sleep", ":", "retry_sleep", "}", ")", "::", "Kernel", ".", "sleep", "(", "retry_sleep", ")", "return", "nil", "end" ]
Handles the Retry-After header of a HTTPResponse This method checks the response for a Retry-After header and handles it by sleeping for the indicated number of seconds. The response is returned unmodified if no Retry-After header is present. @param response [Net::HTTPResponse] A response received from the HTTP client. @return [nil] Sleeps and returns nil if the response contained a Retry-After header that indicated the request should be retried. @return [Net::HTTPResponse] Returns the `response` unmodified if no Retry-After header was present or the Retry-After header could not be parsed as an integer or RFC 2822 date.
[ "Handles", "the", "Retry", "-", "After", "header", "of", "a", "HTTPResponse" ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/network/http/connection.rb#L242-L278
10,969
puppetlabs/puppet
lib/puppet/network/http/connection.rb
Puppet::Network::HTTP.Connection.parse_retry_after_header
def parse_retry_after_header(header_value) retry_after = begin Integer(header_value) rescue TypeError, ArgumentError begin DateTime.rfc2822(header_value) rescue ArgumentError return nil end end case retry_after when Integer retry_after when DateTime sleep = (retry_after.to_time - DateTime.now.to_time).to_i (sleep > 0) ? sleep : 0 end end
ruby
def parse_retry_after_header(header_value) retry_after = begin Integer(header_value) rescue TypeError, ArgumentError begin DateTime.rfc2822(header_value) rescue ArgumentError return nil end end case retry_after when Integer retry_after when DateTime sleep = (retry_after.to_time - DateTime.now.to_time).to_i (sleep > 0) ? sleep : 0 end end
[ "def", "parse_retry_after_header", "(", "header_value", ")", "retry_after", "=", "begin", "Integer", "(", "header_value", ")", "rescue", "TypeError", ",", "ArgumentError", "begin", "DateTime", ".", "rfc2822", "(", "header_value", ")", "rescue", "ArgumentError", "return", "nil", "end", "end", "case", "retry_after", "when", "Integer", "retry_after", "when", "DateTime", "sleep", "=", "(", "retry_after", ".", "to_time", "-", "DateTime", ".", "now", ".", "to_time", ")", ".", "to_i", "(", "sleep", ">", "0", ")", "?", "sleep", ":", "0", "end", "end" ]
Parse the value of a Retry-After header Parses a string containing an Integer or RFC 2822 datestamp and returns an integer number of seconds before a request can be retried. @param header_value [String] The value of the Retry-After header. @return [Integer] Number of seconds to wait before retrying the request. Will be equal to 0 for the case of date that has already passed. @return [nil] Returns `nil` when the `header_value` can't be parsed as an Integer or RFC 2822 date.
[ "Parse", "the", "value", "of", "a", "Retry", "-", "After", "header" ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/network/http/connection.rb#L292-L310
10,970
puppetlabs/puppet
lib/puppet/util/windows/registry.rb
Puppet::Util::Windows.Registry.values_by_name
def values_by_name(key, names) vals = {} names.each do |name| FFI::Pointer.from_string_to_wide_string(name) do |subkeyname_ptr| begin _, vals[name] = read(key, subkeyname_ptr) rescue Puppet::Util::Windows::Error => e # ignore missing names, but raise other errors raise e unless e.code == Puppet::Util::Windows::Error::ERROR_FILE_NOT_FOUND end end end vals end
ruby
def values_by_name(key, names) vals = {} names.each do |name| FFI::Pointer.from_string_to_wide_string(name) do |subkeyname_ptr| begin _, vals[name] = read(key, subkeyname_ptr) rescue Puppet::Util::Windows::Error => e # ignore missing names, but raise other errors raise e unless e.code == Puppet::Util::Windows::Error::ERROR_FILE_NOT_FOUND end end end vals end
[ "def", "values_by_name", "(", "key", ",", "names", ")", "vals", "=", "{", "}", "names", ".", "each", "do", "|", "name", "|", "FFI", "::", "Pointer", ".", "from_string_to_wide_string", "(", "name", ")", "do", "|", "subkeyname_ptr", "|", "begin", "_", ",", "vals", "[", "name", "]", "=", "read", "(", "key", ",", "subkeyname_ptr", ")", "rescue", "Puppet", "::", "Util", "::", "Windows", "::", "Error", "=>", "e", "# ignore missing names, but raise other errors", "raise", "e", "unless", "e", ".", "code", "==", "Puppet", "::", "Util", "::", "Windows", "::", "Error", "::", "ERROR_FILE_NOT_FOUND", "end", "end", "end", "vals", "end" ]
Retrieve a set of values from a registry key given their names Value names listed but not found in the registry will not be added to the resultant Hashtable @param key [RegistryKey] An open handle to a Registry Key @param names [String[]] An array of names of registry values to return if they exist @return [Hashtable<String, Object>] A hashtable of all of the found values in the registry key
[ "Retrieve", "a", "set", "of", "values", "from", "a", "registry", "key", "given", "their", "names", "Value", "names", "listed", "but", "not", "found", "in", "the", "registry", "will", "not", "be", "added", "to", "the", "resultant", "Hashtable" ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/util/windows/registry.rb#L75-L88
10,971
puppetlabs/puppet
lib/puppet/util/fileparsing.rb
Puppet::Util::FileParsing.FileRecord.fields=
def fields=(fields) @fields = fields.collect do |field| r = field.intern raise ArgumentError.new(_("Cannot have fields named %{name}") % { name: r }) if INVALID_FIELDS.include?(r) r end end
ruby
def fields=(fields) @fields = fields.collect do |field| r = field.intern raise ArgumentError.new(_("Cannot have fields named %{name}") % { name: r }) if INVALID_FIELDS.include?(r) r end end
[ "def", "fields", "=", "(", "fields", ")", "@fields", "=", "fields", ".", "collect", "do", "|", "field", "|", "r", "=", "field", ".", "intern", "raise", "ArgumentError", ".", "new", "(", "_", "(", "\"Cannot have fields named %{name}\"", ")", "%", "{", "name", ":", "r", "}", ")", "if", "INVALID_FIELDS", ".", "include?", "(", "r", ")", "r", "end", "end" ]
Customize this so we can do a bit of validation.
[ "Customize", "this", "so", "we", "can", "do", "a", "bit", "of", "validation", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/util/fileparsing.rb#L40-L46
10,972
puppetlabs/puppet
lib/puppet/util/fileparsing.rb
Puppet::Util::FileParsing.FileRecord.join
def join(details) joinchar = self.joiner fields.collect { |field| # If the field is marked absent, use the appropriate replacement if details[field] == :absent or details[field] == [:absent] or details[field].nil? if self.optional.include?(field) self.absent else raise ArgumentError, _("Field '%{field}' is required") % { field: field } end else details[field].to_s end }.reject { |c| c.nil?}.join(joinchar) end
ruby
def join(details) joinchar = self.joiner fields.collect { |field| # If the field is marked absent, use the appropriate replacement if details[field] == :absent or details[field] == [:absent] or details[field].nil? if self.optional.include?(field) self.absent else raise ArgumentError, _("Field '%{field}' is required") % { field: field } end else details[field].to_s end }.reject { |c| c.nil?}.join(joinchar) end
[ "def", "join", "(", "details", ")", "joinchar", "=", "self", ".", "joiner", "fields", ".", "collect", "{", "|", "field", "|", "# If the field is marked absent, use the appropriate replacement", "if", "details", "[", "field", "]", "==", ":absent", "or", "details", "[", "field", "]", "==", "[", ":absent", "]", "or", "details", "[", "field", "]", ".", "nil?", "if", "self", ".", "optional", ".", "include?", "(", "field", ")", "self", ".", "absent", "else", "raise", "ArgumentError", ",", "_", "(", "\"Field '%{field}' is required\"", ")", "%", "{", "field", ":", "field", "}", "end", "else", "details", "[", "field", "]", ".", "to_s", "end", "}", ".", "reject", "{", "|", "c", "|", "c", ".", "nil?", "}", ".", "join", "(", "joinchar", ")", "end" ]
Convert a record into a line by joining the fields together appropriately. This is pulled into a separate method so it can be called by the hooks.
[ "Convert", "a", "record", "into", "a", "line", "by", "joining", "the", "fields", "together", "appropriately", ".", "This", "is", "pulled", "into", "a", "separate", "method", "so", "it", "can", "be", "called", "by", "the", "hooks", "." ]
4baeed97cbb7571ddc6635f0a24debe2e8b22cd3
https://github.com/puppetlabs/puppet/blob/4baeed97cbb7571ddc6635f0a24debe2e8b22cd3/lib/puppet/util/fileparsing.rb#L102-L117
10,973
zendesk/ruby-kafka
lib/kafka/round_robin_assignment_strategy.rb
Kafka.RoundRobinAssignmentStrategy.assign
def assign(members:, topics:) group_assignment = {} members.each do |member_id| group_assignment[member_id] = Protocol::MemberAssignment.new end topic_partitions = topics.flat_map do |topic| begin partitions = @cluster.partitions_for(topic).map(&:partition_id) rescue UnknownTopicOrPartition raise UnknownTopicOrPartition, "unknown topic #{topic}" end Array.new(partitions.count) { topic }.zip(partitions) end partitions_per_member = topic_partitions.group_by.with_index do |_, index| index % members.count end.values members.zip(partitions_per_member).each do |member_id, member_partitions| unless member_partitions.nil? member_partitions.each do |topic, partition| group_assignment[member_id].assign(topic, [partition]) end end end group_assignment rescue Kafka::LeaderNotAvailable sleep 1 retry end
ruby
def assign(members:, topics:) group_assignment = {} members.each do |member_id| group_assignment[member_id] = Protocol::MemberAssignment.new end topic_partitions = topics.flat_map do |topic| begin partitions = @cluster.partitions_for(topic).map(&:partition_id) rescue UnknownTopicOrPartition raise UnknownTopicOrPartition, "unknown topic #{topic}" end Array.new(partitions.count) { topic }.zip(partitions) end partitions_per_member = topic_partitions.group_by.with_index do |_, index| index % members.count end.values members.zip(partitions_per_member).each do |member_id, member_partitions| unless member_partitions.nil? member_partitions.each do |topic, partition| group_assignment[member_id].assign(topic, [partition]) end end end group_assignment rescue Kafka::LeaderNotAvailable sleep 1 retry end
[ "def", "assign", "(", "members", ":", ",", "topics", ":", ")", "group_assignment", "=", "{", "}", "members", ".", "each", "do", "|", "member_id", "|", "group_assignment", "[", "member_id", "]", "=", "Protocol", "::", "MemberAssignment", ".", "new", "end", "topic_partitions", "=", "topics", ".", "flat_map", "do", "|", "topic", "|", "begin", "partitions", "=", "@cluster", ".", "partitions_for", "(", "topic", ")", ".", "map", "(", ":partition_id", ")", "rescue", "UnknownTopicOrPartition", "raise", "UnknownTopicOrPartition", ",", "\"unknown topic #{topic}\"", "end", "Array", ".", "new", "(", "partitions", ".", "count", ")", "{", "topic", "}", ".", "zip", "(", "partitions", ")", "end", "partitions_per_member", "=", "topic_partitions", ".", "group_by", ".", "with_index", "do", "|", "_", ",", "index", "|", "index", "%", "members", ".", "count", "end", ".", "values", "members", ".", "zip", "(", "partitions_per_member", ")", ".", "each", "do", "|", "member_id", ",", "member_partitions", "|", "unless", "member_partitions", ".", "nil?", "member_partitions", ".", "each", "do", "|", "topic", ",", "partition", "|", "group_assignment", "[", "member_id", "]", ".", "assign", "(", "topic", ",", "[", "partition", "]", ")", "end", "end", "end", "group_assignment", "rescue", "Kafka", "::", "LeaderNotAvailable", "sleep", "1", "retry", "end" ]
Assign the topic partitions to the group members. @param members [Array<String>] member ids @param topics [Array<String>] topics @return [Hash<String, Protocol::MemberAssignment>] a hash mapping member ids to assignments.
[ "Assign", "the", "topic", "partitions", "to", "the", "group", "members", "." ]
2a73471b6a607a52dc85c79301ba522acb4566b5
https://github.com/zendesk/ruby-kafka/blob/2a73471b6a607a52dc85c79301ba522acb4566b5/lib/kafka/round_robin_assignment_strategy.rb#L20-L52
10,974
zendesk/ruby-kafka
lib/kafka/message_buffer.rb
Kafka.MessageBuffer.clear_messages
def clear_messages(topic:, partition:) return unless @buffer.key?(topic) && @buffer[topic].key?(partition) @size -= @buffer[topic][partition].count @bytesize -= @buffer[topic][partition].map(&:bytesize).reduce(0, :+) @buffer[topic].delete(partition) @buffer.delete(topic) if @buffer[topic].empty? end
ruby
def clear_messages(topic:, partition:) return unless @buffer.key?(topic) && @buffer[topic].key?(partition) @size -= @buffer[topic][partition].count @bytesize -= @buffer[topic][partition].map(&:bytesize).reduce(0, :+) @buffer[topic].delete(partition) @buffer.delete(topic) if @buffer[topic].empty? end
[ "def", "clear_messages", "(", "topic", ":", ",", "partition", ":", ")", "return", "unless", "@buffer", ".", "key?", "(", "topic", ")", "&&", "@buffer", "[", "topic", "]", ".", "key?", "(", "partition", ")", "@size", "-=", "@buffer", "[", "topic", "]", "[", "partition", "]", ".", "count", "@bytesize", "-=", "@buffer", "[", "topic", "]", "[", "partition", "]", ".", "map", "(", ":bytesize", ")", ".", "reduce", "(", "0", ",", ":+", ")", "@buffer", "[", "topic", "]", ".", "delete", "(", "partition", ")", "@buffer", ".", "delete", "(", "topic", ")", "if", "@buffer", "[", "topic", "]", ".", "empty?", "end" ]
Clears buffered messages for the given topic and partition. @param topic [String] the name of the topic. @param partition [Integer] the partition id. @return [nil]
[ "Clears", "buffered", "messages", "for", "the", "given", "topic", "and", "partition", "." ]
2a73471b6a607a52dc85c79301ba522acb4566b5
https://github.com/zendesk/ruby-kafka/blob/2a73471b6a607a52dc85c79301ba522acb4566b5/lib/kafka/message_buffer.rb#L57-L65
10,975
zendesk/ruby-kafka
lib/kafka/client.rb
Kafka.Client.deliver_message
def deliver_message(value, key: nil, headers: {}, topic:, partition: nil, partition_key: nil, retries: 1) create_time = Time.now message = PendingMessage.new( value: value, key: key, headers: headers, topic: topic, partition: partition, partition_key: partition_key, create_time: create_time ) if partition.nil? partition_count = @cluster.partitions_for(topic).count partition = Partitioner.partition_for_key(partition_count, message) end buffer = MessageBuffer.new buffer.write( value: message.value, key: message.key, headers: message.headers, topic: message.topic, partition: partition, create_time: message.create_time, ) @cluster.add_target_topics([topic]) compressor = Compressor.new( instrumenter: @instrumenter, ) transaction_manager = TransactionManager.new( cluster: @cluster, logger: @logger, idempotent: false, transactional: false ) operation = ProduceOperation.new( cluster: @cluster, transaction_manager: transaction_manager, buffer: buffer, required_acks: 1, ack_timeout: 10, compressor: compressor, logger: @logger, instrumenter: @instrumenter, ) attempt = 1 begin operation.execute unless buffer.empty? raise DeliveryFailed.new(nil, [message]) end rescue Kafka::Error => e @cluster.mark_as_stale! if attempt >= (retries + 1) raise else attempt += 1 @logger.warn "Error while delivering message, #{e.class}: #{e.message}; retrying after 1s..." sleep 1 retry end end end
ruby
def deliver_message(value, key: nil, headers: {}, topic:, partition: nil, partition_key: nil, retries: 1) create_time = Time.now message = PendingMessage.new( value: value, key: key, headers: headers, topic: topic, partition: partition, partition_key: partition_key, create_time: create_time ) if partition.nil? partition_count = @cluster.partitions_for(topic).count partition = Partitioner.partition_for_key(partition_count, message) end buffer = MessageBuffer.new buffer.write( value: message.value, key: message.key, headers: message.headers, topic: message.topic, partition: partition, create_time: message.create_time, ) @cluster.add_target_topics([topic]) compressor = Compressor.new( instrumenter: @instrumenter, ) transaction_manager = TransactionManager.new( cluster: @cluster, logger: @logger, idempotent: false, transactional: false ) operation = ProduceOperation.new( cluster: @cluster, transaction_manager: transaction_manager, buffer: buffer, required_acks: 1, ack_timeout: 10, compressor: compressor, logger: @logger, instrumenter: @instrumenter, ) attempt = 1 begin operation.execute unless buffer.empty? raise DeliveryFailed.new(nil, [message]) end rescue Kafka::Error => e @cluster.mark_as_stale! if attempt >= (retries + 1) raise else attempt += 1 @logger.warn "Error while delivering message, #{e.class}: #{e.message}; retrying after 1s..." sleep 1 retry end end end
[ "def", "deliver_message", "(", "value", ",", "key", ":", "nil", ",", "headers", ":", "{", "}", ",", "topic", ":", ",", "partition", ":", "nil", ",", "partition_key", ":", "nil", ",", "retries", ":", "1", ")", "create_time", "=", "Time", ".", "now", "message", "=", "PendingMessage", ".", "new", "(", "value", ":", "value", ",", "key", ":", "key", ",", "headers", ":", "headers", ",", "topic", ":", "topic", ",", "partition", ":", "partition", ",", "partition_key", ":", "partition_key", ",", "create_time", ":", "create_time", ")", "if", "partition", ".", "nil?", "partition_count", "=", "@cluster", ".", "partitions_for", "(", "topic", ")", ".", "count", "partition", "=", "Partitioner", ".", "partition_for_key", "(", "partition_count", ",", "message", ")", "end", "buffer", "=", "MessageBuffer", ".", "new", "buffer", ".", "write", "(", "value", ":", "message", ".", "value", ",", "key", ":", "message", ".", "key", ",", "headers", ":", "message", ".", "headers", ",", "topic", ":", "message", ".", "topic", ",", "partition", ":", "partition", ",", "create_time", ":", "message", ".", "create_time", ",", ")", "@cluster", ".", "add_target_topics", "(", "[", "topic", "]", ")", "compressor", "=", "Compressor", ".", "new", "(", "instrumenter", ":", "@instrumenter", ",", ")", "transaction_manager", "=", "TransactionManager", ".", "new", "(", "cluster", ":", "@cluster", ",", "logger", ":", "@logger", ",", "idempotent", ":", "false", ",", "transactional", ":", "false", ")", "operation", "=", "ProduceOperation", ".", "new", "(", "cluster", ":", "@cluster", ",", "transaction_manager", ":", "transaction_manager", ",", "buffer", ":", "buffer", ",", "required_acks", ":", "1", ",", "ack_timeout", ":", "10", ",", "compressor", ":", "compressor", ",", "logger", ":", "@logger", ",", "instrumenter", ":", "@instrumenter", ",", ")", "attempt", "=", "1", "begin", "operation", ".", "execute", "unless", "buffer", ".", "empty?", "raise", "DeliveryFailed", ".", "new", "(", "nil", ",", "[", "message", "]", ")", "end", "rescue", "Kafka", "::", "Error", "=>", "e", "@cluster", ".", "mark_as_stale!", "if", "attempt", ">=", "(", "retries", "+", "1", ")", "raise", "else", "attempt", "+=", "1", "@logger", ".", "warn", "\"Error while delivering message, #{e.class}: #{e.message}; retrying after 1s...\"", "sleep", "1", "retry", "end", "end", "end" ]
Initializes a new Kafka client. @param seed_brokers [Array<String>, String] the list of brokers used to initialize the client. Either an Array of connections, or a comma separated string of connections. A connection can either be a string of "host:port" or a full URI with a scheme. If there's a scheme it's ignored and only host/port are used. @param client_id [String] the identifier for this application. @param logger [Logger] the logger that should be used by the client. @param connect_timeout [Integer, nil] the timeout setting for connecting to brokers. See {BrokerPool#initialize}. @param socket_timeout [Integer, nil] the timeout setting for socket connections. See {BrokerPool#initialize}. @param ssl_ca_cert [String, Array<String>, nil] a PEM encoded CA cert, or an Array of PEM encoded CA certs, to use with an SSL connection. @param ssl_ca_cert_file_path [String, nil] a path on the filesystem to a PEM encoded CA cert to use with an SSL connection. @param ssl_client_cert [String, nil] a PEM encoded client cert to use with an SSL connection. Must be used in combination with ssl_client_cert_key. @param ssl_client_cert_key [String, nil] a PEM encoded client cert key to use with an SSL connection. Must be used in combination with ssl_client_cert. @param ssl_client_cert_key_password [String, nil] the password required to read the ssl_client_cert_key. Must be used in combination with ssl_client_cert_key. @param sasl_gssapi_principal [String, nil] a KRB5 principal @param sasl_gssapi_keytab [String, nil] a KRB5 keytab filepath @param sasl_scram_username [String, nil] SCRAM username @param sasl_scram_password [String, nil] SCRAM password @param sasl_scram_mechanism [String, nil] Scram mechanism, either "sha256" or "sha512" @param sasl_over_ssl [Boolean] whether to enforce SSL with SASL @param sasl_oauth_token_provider [Object, nil] OAuthBearer Token Provider instance that implements method token. See {Sasl::OAuth#initialize} @return [Client] Delivers a single message to the Kafka cluster. **Note:** Only use this API for low-throughput scenarios. If you want to deliver many messages at a high rate, or if you want to configure the way messages are sent, use the {#producer} or {#async_producer} APIs instead. @param value [String, nil] the message value. @param key [String, nil] the message key. @param headers [Hash<String, String>] the headers for the message. @param topic [String] the topic that the message should be written to. @param partition [Integer, nil] the partition that the message should be written to, or `nil` if either `partition_key` is passed or the partition should be chosen at random. @param partition_key [String] a value used to deterministically choose a partition to write to. @param retries [Integer] the number of times to retry the delivery before giving up. @return [nil]
[ "Initializes", "a", "new", "Kafka", "client", "." ]
2a73471b6a607a52dc85c79301ba522acb4566b5
https://github.com/zendesk/ruby-kafka/blob/2a73471b6a607a52dc85c79301ba522acb4566b5/lib/kafka/client.rb#L137-L212
10,976
zendesk/ruby-kafka
lib/kafka/client.rb
Kafka.Client.producer
def producer( compression_codec: nil, compression_threshold: 1, ack_timeout: 5, required_acks: :all, max_retries: 2, retry_backoff: 1, max_buffer_size: 1000, max_buffer_bytesize: 10_000_000, idempotent: false, transactional: false, transactional_id: nil, transactional_timeout: 60 ) cluster = initialize_cluster compressor = Compressor.new( codec_name: compression_codec, threshold: compression_threshold, instrumenter: @instrumenter, ) transaction_manager = TransactionManager.new( cluster: cluster, logger: @logger, idempotent: idempotent, transactional: transactional, transactional_id: transactional_id, transactional_timeout: transactional_timeout, ) Producer.new( cluster: cluster, transaction_manager: transaction_manager, logger: @logger, instrumenter: @instrumenter, compressor: compressor, ack_timeout: ack_timeout, required_acks: required_acks, max_retries: max_retries, retry_backoff: retry_backoff, max_buffer_size: max_buffer_size, max_buffer_bytesize: max_buffer_bytesize, ) end
ruby
def producer( compression_codec: nil, compression_threshold: 1, ack_timeout: 5, required_acks: :all, max_retries: 2, retry_backoff: 1, max_buffer_size: 1000, max_buffer_bytesize: 10_000_000, idempotent: false, transactional: false, transactional_id: nil, transactional_timeout: 60 ) cluster = initialize_cluster compressor = Compressor.new( codec_name: compression_codec, threshold: compression_threshold, instrumenter: @instrumenter, ) transaction_manager = TransactionManager.new( cluster: cluster, logger: @logger, idempotent: idempotent, transactional: transactional, transactional_id: transactional_id, transactional_timeout: transactional_timeout, ) Producer.new( cluster: cluster, transaction_manager: transaction_manager, logger: @logger, instrumenter: @instrumenter, compressor: compressor, ack_timeout: ack_timeout, required_acks: required_acks, max_retries: max_retries, retry_backoff: retry_backoff, max_buffer_size: max_buffer_size, max_buffer_bytesize: max_buffer_bytesize, ) end
[ "def", "producer", "(", "compression_codec", ":", "nil", ",", "compression_threshold", ":", "1", ",", "ack_timeout", ":", "5", ",", "required_acks", ":", ":all", ",", "max_retries", ":", "2", ",", "retry_backoff", ":", "1", ",", "max_buffer_size", ":", "1000", ",", "max_buffer_bytesize", ":", "10_000_000", ",", "idempotent", ":", "false", ",", "transactional", ":", "false", ",", "transactional_id", ":", "nil", ",", "transactional_timeout", ":", "60", ")", "cluster", "=", "initialize_cluster", "compressor", "=", "Compressor", ".", "new", "(", "codec_name", ":", "compression_codec", ",", "threshold", ":", "compression_threshold", ",", "instrumenter", ":", "@instrumenter", ",", ")", "transaction_manager", "=", "TransactionManager", ".", "new", "(", "cluster", ":", "cluster", ",", "logger", ":", "@logger", ",", "idempotent", ":", "idempotent", ",", "transactional", ":", "transactional", ",", "transactional_id", ":", "transactional_id", ",", "transactional_timeout", ":", "transactional_timeout", ",", ")", "Producer", ".", "new", "(", "cluster", ":", "cluster", ",", "transaction_manager", ":", "transaction_manager", ",", "logger", ":", "@logger", ",", "instrumenter", ":", "@instrumenter", ",", "compressor", ":", "compressor", ",", "ack_timeout", ":", "ack_timeout", ",", "required_acks", ":", "required_acks", ",", "max_retries", ":", "max_retries", ",", "retry_backoff", ":", "retry_backoff", ",", "max_buffer_size", ":", "max_buffer_size", ",", "max_buffer_bytesize", ":", "max_buffer_bytesize", ",", ")", "end" ]
Initializes a new Kafka producer. @param ack_timeout [Integer] The number of seconds a broker can wait for replicas to acknowledge a write before responding with a timeout. @param required_acks [Integer, Symbol] The number of replicas that must acknowledge a write, or `:all` if all in-sync replicas must acknowledge. @param max_retries [Integer] the number of retries that should be attempted before giving up sending messages to the cluster. Does not include the original attempt. @param retry_backoff [Integer] the number of seconds to wait between retries. @param max_buffer_size [Integer] the number of messages allowed in the buffer before new writes will raise {BufferOverflow} exceptions. @param max_buffer_bytesize [Integer] the maximum size of the buffer in bytes. attempting to produce messages when the buffer reaches this size will result in {BufferOverflow} being raised. @param compression_codec [Symbol, nil] the name of the compression codec to use, or nil if no compression should be performed. Valid codecs: `:snappy`, `:gzip`, `:lz4`, `:zstd` @param compression_threshold [Integer] the number of messages that needs to be in a message set before it should be compressed. Note that message sets are per-partition rather than per-topic or per-producer. @return [Kafka::Producer] the Kafka producer.
[ "Initializes", "a", "new", "Kafka", "producer", "." ]
2a73471b6a607a52dc85c79301ba522acb4566b5
https://github.com/zendesk/ruby-kafka/blob/2a73471b6a607a52dc85c79301ba522acb4566b5/lib/kafka/client.rb#L244-L287
10,977
zendesk/ruby-kafka
lib/kafka/client.rb
Kafka.Client.async_producer
def async_producer(delivery_interval: 0, delivery_threshold: 0, max_queue_size: 1000, max_retries: -1, retry_backoff: 0, **options) sync_producer = producer(**options) AsyncProducer.new( sync_producer: sync_producer, delivery_interval: delivery_interval, delivery_threshold: delivery_threshold, max_queue_size: max_queue_size, max_retries: max_retries, retry_backoff: retry_backoff, instrumenter: @instrumenter, logger: @logger, ) end
ruby
def async_producer(delivery_interval: 0, delivery_threshold: 0, max_queue_size: 1000, max_retries: -1, retry_backoff: 0, **options) sync_producer = producer(**options) AsyncProducer.new( sync_producer: sync_producer, delivery_interval: delivery_interval, delivery_threshold: delivery_threshold, max_queue_size: max_queue_size, max_retries: max_retries, retry_backoff: retry_backoff, instrumenter: @instrumenter, logger: @logger, ) end
[ "def", "async_producer", "(", "delivery_interval", ":", "0", ",", "delivery_threshold", ":", "0", ",", "max_queue_size", ":", "1000", ",", "max_retries", ":", "-", "1", ",", "retry_backoff", ":", "0", ",", "**", "options", ")", "sync_producer", "=", "producer", "(", "**", "options", ")", "AsyncProducer", ".", "new", "(", "sync_producer", ":", "sync_producer", ",", "delivery_interval", ":", "delivery_interval", ",", "delivery_threshold", ":", "delivery_threshold", ",", "max_queue_size", ":", "max_queue_size", ",", "max_retries", ":", "max_retries", ",", "retry_backoff", ":", "retry_backoff", ",", "instrumenter", ":", "@instrumenter", ",", "logger", ":", "@logger", ",", ")", "end" ]
Creates a new AsyncProducer instance. All parameters allowed by {#producer} can be passed. In addition to this, a few extra parameters can be passed when creating an async producer. @param max_queue_size [Integer] the maximum number of messages allowed in the queue. @param delivery_threshold [Integer] if greater than zero, the number of buffered messages that will automatically trigger a delivery. @param delivery_interval [Integer] if greater than zero, the number of seconds between automatic message deliveries. @see AsyncProducer @return [AsyncProducer]
[ "Creates", "a", "new", "AsyncProducer", "instance", "." ]
2a73471b6a607a52dc85c79301ba522acb4566b5
https://github.com/zendesk/ruby-kafka/blob/2a73471b6a607a52dc85c79301ba522acb4566b5/lib/kafka/client.rb#L303-L316
10,978
zendesk/ruby-kafka
lib/kafka/client.rb
Kafka.Client.consumer
def consumer( group_id:, session_timeout: 30, offset_commit_interval: 10, offset_commit_threshold: 0, heartbeat_interval: 10, offset_retention_time: nil, fetcher_max_queue_size: 100 ) cluster = initialize_cluster instrumenter = DecoratingInstrumenter.new(@instrumenter, { group_id: group_id, }) # The Kafka protocol expects the retention time to be in ms. retention_time = (offset_retention_time && offset_retention_time * 1_000) || -1 group = ConsumerGroup.new( cluster: cluster, logger: @logger, group_id: group_id, session_timeout: session_timeout, retention_time: retention_time, instrumenter: instrumenter, ) fetcher = Fetcher.new( cluster: initialize_cluster, group: group, logger: @logger, instrumenter: instrumenter, max_queue_size: fetcher_max_queue_size ) offset_manager = OffsetManager.new( cluster: cluster, group: group, fetcher: fetcher, logger: @logger, commit_interval: offset_commit_interval, commit_threshold: offset_commit_threshold, offset_retention_time: offset_retention_time ) heartbeat = Heartbeat.new( group: group, interval: heartbeat_interval, instrumenter: instrumenter ) Consumer.new( cluster: cluster, logger: @logger, instrumenter: instrumenter, group: group, offset_manager: offset_manager, fetcher: fetcher, session_timeout: session_timeout, heartbeat: heartbeat, ) end
ruby
def consumer( group_id:, session_timeout: 30, offset_commit_interval: 10, offset_commit_threshold: 0, heartbeat_interval: 10, offset_retention_time: nil, fetcher_max_queue_size: 100 ) cluster = initialize_cluster instrumenter = DecoratingInstrumenter.new(@instrumenter, { group_id: group_id, }) # The Kafka protocol expects the retention time to be in ms. retention_time = (offset_retention_time && offset_retention_time * 1_000) || -1 group = ConsumerGroup.new( cluster: cluster, logger: @logger, group_id: group_id, session_timeout: session_timeout, retention_time: retention_time, instrumenter: instrumenter, ) fetcher = Fetcher.new( cluster: initialize_cluster, group: group, logger: @logger, instrumenter: instrumenter, max_queue_size: fetcher_max_queue_size ) offset_manager = OffsetManager.new( cluster: cluster, group: group, fetcher: fetcher, logger: @logger, commit_interval: offset_commit_interval, commit_threshold: offset_commit_threshold, offset_retention_time: offset_retention_time ) heartbeat = Heartbeat.new( group: group, interval: heartbeat_interval, instrumenter: instrumenter ) Consumer.new( cluster: cluster, logger: @logger, instrumenter: instrumenter, group: group, offset_manager: offset_manager, fetcher: fetcher, session_timeout: session_timeout, heartbeat: heartbeat, ) end
[ "def", "consumer", "(", "group_id", ":", ",", "session_timeout", ":", "30", ",", "offset_commit_interval", ":", "10", ",", "offset_commit_threshold", ":", "0", ",", "heartbeat_interval", ":", "10", ",", "offset_retention_time", ":", "nil", ",", "fetcher_max_queue_size", ":", "100", ")", "cluster", "=", "initialize_cluster", "instrumenter", "=", "DecoratingInstrumenter", ".", "new", "(", "@instrumenter", ",", "{", "group_id", ":", "group_id", ",", "}", ")", "# The Kafka protocol expects the retention time to be in ms.", "retention_time", "=", "(", "offset_retention_time", "&&", "offset_retention_time", "*", "1_000", ")", "||", "-", "1", "group", "=", "ConsumerGroup", ".", "new", "(", "cluster", ":", "cluster", ",", "logger", ":", "@logger", ",", "group_id", ":", "group_id", ",", "session_timeout", ":", "session_timeout", ",", "retention_time", ":", "retention_time", ",", "instrumenter", ":", "instrumenter", ",", ")", "fetcher", "=", "Fetcher", ".", "new", "(", "cluster", ":", "initialize_cluster", ",", "group", ":", "group", ",", "logger", ":", "@logger", ",", "instrumenter", ":", "instrumenter", ",", "max_queue_size", ":", "fetcher_max_queue_size", ")", "offset_manager", "=", "OffsetManager", ".", "new", "(", "cluster", ":", "cluster", ",", "group", ":", "group", ",", "fetcher", ":", "fetcher", ",", "logger", ":", "@logger", ",", "commit_interval", ":", "offset_commit_interval", ",", "commit_threshold", ":", "offset_commit_threshold", ",", "offset_retention_time", ":", "offset_retention_time", ")", "heartbeat", "=", "Heartbeat", ".", "new", "(", "group", ":", "group", ",", "interval", ":", "heartbeat_interval", ",", "instrumenter", ":", "instrumenter", ")", "Consumer", ".", "new", "(", "cluster", ":", "cluster", ",", "logger", ":", "@logger", ",", "instrumenter", ":", "instrumenter", ",", "group", ":", "group", ",", "offset_manager", ":", "offset_manager", ",", "fetcher", ":", "fetcher", ",", "session_timeout", ":", "session_timeout", ",", "heartbeat", ":", "heartbeat", ",", ")", "end" ]
Creates a new Kafka consumer. @param group_id [String] the id of the group that the consumer should join. @param session_timeout [Integer] the number of seconds after which, if a client hasn't contacted the Kafka cluster, it will be kicked out of the group. @param offset_commit_interval [Integer] the interval between offset commits, in seconds. @param offset_commit_threshold [Integer] the number of messages that can be processed before their offsets are committed. If zero, offset commits are not triggered by message processing. @param heartbeat_interval [Integer] the interval between heartbeats; must be less than the session window. @param offset_retention_time [Integer] the time period that committed offsets will be retained, in seconds. Defaults to the broker setting. @param fetcher_max_queue_size [Integer] max number of items in the fetch queue that are stored for further processing. Note, that each item in the queue represents a response from a single broker. @return [Consumer]
[ "Creates", "a", "new", "Kafka", "consumer", "." ]
2a73471b6a607a52dc85c79301ba522acb4566b5
https://github.com/zendesk/ruby-kafka/blob/2a73471b6a607a52dc85c79301ba522acb4566b5/lib/kafka/client.rb#L336-L397
10,979
zendesk/ruby-kafka
lib/kafka/client.rb
Kafka.Client.fetch_messages
def fetch_messages(topic:, partition:, offset: :latest, max_wait_time: 5, min_bytes: 1, max_bytes: 1048576, retries: 1) operation = FetchOperation.new( cluster: @cluster, logger: @logger, min_bytes: min_bytes, max_bytes: max_bytes, max_wait_time: max_wait_time, ) operation.fetch_from_partition(topic, partition, offset: offset, max_bytes: max_bytes) attempt = 1 begin operation.execute.flat_map {|batch| batch.messages } rescue Kafka::Error => e @cluster.mark_as_stale! if attempt >= (retries + 1) raise else attempt += 1 @logger.warn "Error while fetching messages, #{e.class}: #{e.message}; retrying..." retry end end end
ruby
def fetch_messages(topic:, partition:, offset: :latest, max_wait_time: 5, min_bytes: 1, max_bytes: 1048576, retries: 1) operation = FetchOperation.new( cluster: @cluster, logger: @logger, min_bytes: min_bytes, max_bytes: max_bytes, max_wait_time: max_wait_time, ) operation.fetch_from_partition(topic, partition, offset: offset, max_bytes: max_bytes) attempt = 1 begin operation.execute.flat_map {|batch| batch.messages } rescue Kafka::Error => e @cluster.mark_as_stale! if attempt >= (retries + 1) raise else attempt += 1 @logger.warn "Error while fetching messages, #{e.class}: #{e.message}; retrying..." retry end end end
[ "def", "fetch_messages", "(", "topic", ":", ",", "partition", ":", ",", "offset", ":", ":latest", ",", "max_wait_time", ":", "5", ",", "min_bytes", ":", "1", ",", "max_bytes", ":", "1048576", ",", "retries", ":", "1", ")", "operation", "=", "FetchOperation", ".", "new", "(", "cluster", ":", "@cluster", ",", "logger", ":", "@logger", ",", "min_bytes", ":", "min_bytes", ",", "max_bytes", ":", "max_bytes", ",", "max_wait_time", ":", "max_wait_time", ",", ")", "operation", ".", "fetch_from_partition", "(", "topic", ",", "partition", ",", "offset", ":", "offset", ",", "max_bytes", ":", "max_bytes", ")", "attempt", "=", "1", "begin", "operation", ".", "execute", ".", "flat_map", "{", "|", "batch", "|", "batch", ".", "messages", "}", "rescue", "Kafka", "::", "Error", "=>", "e", "@cluster", ".", "mark_as_stale!", "if", "attempt", ">=", "(", "retries", "+", "1", ")", "raise", "else", "attempt", "+=", "1", "@logger", ".", "warn", "\"Error while fetching messages, #{e.class}: #{e.message}; retrying...\"", "retry", "end", "end", "end" ]
Fetches a batch of messages from a single partition. Note that it's possible to get back empty batches. The starting point for the fetch can be configured with the `:offset` argument. If you pass a number, the fetch will start at that offset. However, there are two special Symbol values that can be passed instead: * `:earliest` — the first offset in the partition. * `:latest` — the next offset that will be written to, effectively making the call block until there is a new message in the partition. The Kafka protocol specifies the numeric values of these two options: -2 and -1, respectively. You can also pass in these numbers directly. ## Example When enumerating the messages in a partition, you typically fetch batches sequentially. offset = :earliest loop do messages = kafka.fetch_messages( topic: "my-topic", partition: 42, offset: offset, ) messages.each do |message| puts message.offset, message.key, message.value # Set the next offset that should be read to be the subsequent # offset. offset = message.offset + 1 end end See a working example in `examples/simple-consumer.rb`. @param topic [String] the topic that messages should be fetched from. @param partition [Integer] the partition that messages should be fetched from. @param offset [Integer, Symbol] the offset to start reading from. Default is the latest offset. @param max_wait_time [Integer] the maximum amount of time to wait before the server responds, in seconds. @param min_bytes [Integer] the minimum number of bytes to wait for. If set to zero, the broker will respond immediately, but the response may be empty. The default is 1 byte, which means that the broker will respond as soon as a message is written to the partition. @param max_bytes [Integer] the maximum number of bytes to include in the response message set. Default is 1 MB. You need to set this higher if you expect messages to be larger than this. @return [Array<Kafka::FetchedMessage>] the messages returned from the broker.
[ "Fetches", "a", "batch", "of", "messages", "from", "a", "single", "partition", ".", "Note", "that", "it", "s", "possible", "to", "get", "back", "empty", "batches", "." ]
2a73471b6a607a52dc85c79301ba522acb4566b5
https://github.com/zendesk/ruby-kafka/blob/2a73471b6a607a52dc85c79301ba522acb4566b5/lib/kafka/client.rb#L458-L484
10,980
zendesk/ruby-kafka
lib/kafka/client.rb
Kafka.Client.each_message
def each_message(topic:, start_from_beginning: true, max_wait_time: 5, min_bytes: 1, max_bytes: 1048576, &block) default_offset ||= start_from_beginning ? :earliest : :latest offsets = Hash.new { default_offset } loop do operation = FetchOperation.new( cluster: @cluster, logger: @logger, min_bytes: min_bytes, max_wait_time: max_wait_time, ) @cluster.partitions_for(topic).map(&:partition_id).each do |partition| partition_offset = offsets[partition] operation.fetch_from_partition(topic, partition, offset: partition_offset, max_bytes: max_bytes) end batches = operation.execute batches.each do |batch| batch.messages.each(&block) offsets[batch.partition] = batch.last_offset + 1 unless batch.unknown_last_offset? end end end
ruby
def each_message(topic:, start_from_beginning: true, max_wait_time: 5, min_bytes: 1, max_bytes: 1048576, &block) default_offset ||= start_from_beginning ? :earliest : :latest offsets = Hash.new { default_offset } loop do operation = FetchOperation.new( cluster: @cluster, logger: @logger, min_bytes: min_bytes, max_wait_time: max_wait_time, ) @cluster.partitions_for(topic).map(&:partition_id).each do |partition| partition_offset = offsets[partition] operation.fetch_from_partition(topic, partition, offset: partition_offset, max_bytes: max_bytes) end batches = operation.execute batches.each do |batch| batch.messages.each(&block) offsets[batch.partition] = batch.last_offset + 1 unless batch.unknown_last_offset? end end end
[ "def", "each_message", "(", "topic", ":", ",", "start_from_beginning", ":", "true", ",", "max_wait_time", ":", "5", ",", "min_bytes", ":", "1", ",", "max_bytes", ":", "1048576", ",", "&", "block", ")", "default_offset", "||=", "start_from_beginning", "?", ":earliest", ":", ":latest", "offsets", "=", "Hash", ".", "new", "{", "default_offset", "}", "loop", "do", "operation", "=", "FetchOperation", ".", "new", "(", "cluster", ":", "@cluster", ",", "logger", ":", "@logger", ",", "min_bytes", ":", "min_bytes", ",", "max_wait_time", ":", "max_wait_time", ",", ")", "@cluster", ".", "partitions_for", "(", "topic", ")", ".", "map", "(", ":partition_id", ")", ".", "each", "do", "|", "partition", "|", "partition_offset", "=", "offsets", "[", "partition", "]", "operation", ".", "fetch_from_partition", "(", "topic", ",", "partition", ",", "offset", ":", "partition_offset", ",", "max_bytes", ":", "max_bytes", ")", "end", "batches", "=", "operation", ".", "execute", "batches", ".", "each", "do", "|", "batch", "|", "batch", ".", "messages", ".", "each", "(", "block", ")", "offsets", "[", "batch", ".", "partition", "]", "=", "batch", ".", "last_offset", "+", "1", "unless", "batch", ".", "unknown_last_offset?", "end", "end", "end" ]
Enumerate all messages in a topic. @param topic [String] the topic to consume messages from. @param start_from_beginning [Boolean] whether to start from the beginning of the topic or just subscribe to new messages being produced. @param max_wait_time [Integer] the maximum amount of time to wait before the server responds, in seconds. @param min_bytes [Integer] the minimum number of bytes to wait for. If set to zero, the broker will respond immediately, but the response may be empty. The default is 1 byte, which means that the broker will respond as soon as a message is written to the partition. @param max_bytes [Integer] the maximum number of bytes to include in the response message set. Default is 1 MB. You need to set this higher if you expect messages to be larger than this. @return [nil]
[ "Enumerate", "all", "messages", "in", "a", "topic", "." ]
2a73471b6a607a52dc85c79301ba522acb4566b5
https://github.com/zendesk/ruby-kafka/blob/2a73471b6a607a52dc85c79301ba522acb4566b5/lib/kafka/client.rb#L506-L530
10,981
zendesk/ruby-kafka
lib/kafka/client.rb
Kafka.Client.create_topic
def create_topic(name, num_partitions: 1, replication_factor: 1, timeout: 30, config: {}) @cluster.create_topic( name, num_partitions: num_partitions, replication_factor: replication_factor, timeout: timeout, config: config, ) end
ruby
def create_topic(name, num_partitions: 1, replication_factor: 1, timeout: 30, config: {}) @cluster.create_topic( name, num_partitions: num_partitions, replication_factor: replication_factor, timeout: timeout, config: config, ) end
[ "def", "create_topic", "(", "name", ",", "num_partitions", ":", "1", ",", "replication_factor", ":", "1", ",", "timeout", ":", "30", ",", "config", ":", "{", "}", ")", "@cluster", ".", "create_topic", "(", "name", ",", "num_partitions", ":", "num_partitions", ",", "replication_factor", ":", "replication_factor", ",", "timeout", ":", "timeout", ",", "config", ":", "config", ",", ")", "end" ]
Creates a topic in the cluster. @example Creating a topic with log compaction # Enable log compaction: config = { "cleanup.policy" => "compact" } # Create the topic: kafka.create_topic("dns-mappings", config: config) @param name [String] the name of the topic. @param num_partitions [Integer] the number of partitions that should be created in the topic. @param replication_factor [Integer] the replication factor of the topic. @param timeout [Integer] a duration of time to wait for the topic to be completely created. @param config [Hash] topic configuration entries. See [the Kafka documentation](https://kafka.apache.org/documentation/#topicconfigs) for more information. @raise [Kafka::TopicAlreadyExists] if the topic already exists. @return [nil]
[ "Creates", "a", "topic", "in", "the", "cluster", "." ]
2a73471b6a607a52dc85c79301ba522acb4566b5
https://github.com/zendesk/ruby-kafka/blob/2a73471b6a607a52dc85c79301ba522acb4566b5/lib/kafka/client.rb#L552-L560
10,982
zendesk/ruby-kafka
lib/kafka/client.rb
Kafka.Client.create_partitions_for
def create_partitions_for(name, num_partitions: 1, timeout: 30) @cluster.create_partitions_for(name, num_partitions: num_partitions, timeout: timeout) end
ruby
def create_partitions_for(name, num_partitions: 1, timeout: 30) @cluster.create_partitions_for(name, num_partitions: num_partitions, timeout: timeout) end
[ "def", "create_partitions_for", "(", "name", ",", "num_partitions", ":", "1", ",", "timeout", ":", "30", ")", "@cluster", ".", "create_partitions_for", "(", "name", ",", "num_partitions", ":", "num_partitions", ",", "timeout", ":", "timeout", ")", "end" ]
Create partitions for a topic. @param name [String] the name of the topic. @param num_partitions [Integer] the number of desired partitions for the topic @param timeout [Integer] a duration of time to wait for the new partitions to be added. @return [nil]
[ "Create", "partitions", "for", "a", "topic", "." ]
2a73471b6a607a52dc85c79301ba522acb4566b5
https://github.com/zendesk/ruby-kafka/blob/2a73471b6a607a52dc85c79301ba522acb4566b5/lib/kafka/client.rb#L625-L627
10,983
zendesk/ruby-kafka
lib/kafka/client.rb
Kafka.Client.last_offsets_for
def last_offsets_for(*topics) @cluster.add_target_topics(topics) topics.map {|topic| partition_ids = @cluster.partitions_for(topic).collect(&:partition_id) partition_offsets = @cluster.resolve_offsets(topic, partition_ids, :latest) [topic, partition_offsets.collect { |k, v| [k, v - 1] }.to_h] }.to_h end
ruby
def last_offsets_for(*topics) @cluster.add_target_topics(topics) topics.map {|topic| partition_ids = @cluster.partitions_for(topic).collect(&:partition_id) partition_offsets = @cluster.resolve_offsets(topic, partition_ids, :latest) [topic, partition_offsets.collect { |k, v| [k, v - 1] }.to_h] }.to_h end
[ "def", "last_offsets_for", "(", "*", "topics", ")", "@cluster", ".", "add_target_topics", "(", "topics", ")", "topics", ".", "map", "{", "|", "topic", "|", "partition_ids", "=", "@cluster", ".", "partitions_for", "(", "topic", ")", ".", "collect", "(", ":partition_id", ")", "partition_offsets", "=", "@cluster", ".", "resolve_offsets", "(", "topic", ",", "partition_ids", ",", ":latest", ")", "[", "topic", ",", "partition_offsets", ".", "collect", "{", "|", "k", ",", "v", "|", "[", "k", ",", "v", "-", "1", "]", "}", ".", "to_h", "]", "}", ".", "to_h", "end" ]
Retrieve the offset of the last message in each partition of the specified topics. @param topics [Array<String>] topic names. @return [Hash<String, Hash<Integer, Integer>>] @example last_offsets_for('topic-1', 'topic-2') # => # { # 'topic-1' => { 0 => 100, 1 => 100 }, # 'topic-2' => { 0 => 100, 1 => 100 } # }
[ "Retrieve", "the", "offset", "of", "the", "last", "message", "in", "each", "partition", "of", "the", "specified", "topics", "." ]
2a73471b6a607a52dc85c79301ba522acb4566b5
https://github.com/zendesk/ruby-kafka/blob/2a73471b6a607a52dc85c79301ba522acb4566b5/lib/kafka/client.rb#L688-L695
10,984
zendesk/ruby-kafka
lib/kafka/cluster.rb
Kafka.Cluster.add_target_topics
def add_target_topics(topics) topics = Set.new(topics) unless topics.subset?(@target_topics) new_topics = topics - @target_topics unless new_topics.empty? @logger.info "New topics added to target list: #{new_topics.to_a.join(', ')}" @target_topics.merge(new_topics) refresh_metadata! end end end
ruby
def add_target_topics(topics) topics = Set.new(topics) unless topics.subset?(@target_topics) new_topics = topics - @target_topics unless new_topics.empty? @logger.info "New topics added to target list: #{new_topics.to_a.join(', ')}" @target_topics.merge(new_topics) refresh_metadata! end end end
[ "def", "add_target_topics", "(", "topics", ")", "topics", "=", "Set", ".", "new", "(", "topics", ")", "unless", "topics", ".", "subset?", "(", "@target_topics", ")", "new_topics", "=", "topics", "-", "@target_topics", "unless", "new_topics", ".", "empty?", "@logger", ".", "info", "\"New topics added to target list: #{new_topics.to_a.join(', ')}\"", "@target_topics", ".", "merge", "(", "new_topics", ")", "refresh_metadata!", "end", "end", "end" ]
Initializes a Cluster with a set of seed brokers. The cluster will try to fetch cluster metadata from one of the brokers. @param seed_brokers [Array<URI>] @param broker_pool [Kafka::BrokerPool] @param logger [Logger] Adds a list of topics to the target list. Only the topics on this list will be queried for metadata. @param topics [Array<String>] @return [nil]
[ "Initializes", "a", "Cluster", "with", "a", "set", "of", "seed", "brokers", "." ]
2a73471b6a607a52dc85c79301ba522acb4566b5
https://github.com/zendesk/ruby-kafka/blob/2a73471b6a607a52dc85c79301ba522acb4566b5/lib/kafka/cluster.rb#L42-L55
10,985
zendesk/ruby-kafka
lib/kafka/cluster.rb
Kafka.Cluster.get_transaction_coordinator
def get_transaction_coordinator(transactional_id:) @logger.debug "Getting transaction coordinator for `#{transactional_id}`" refresh_metadata_if_necessary! if transactional_id.nil? # Get a random_broker @logger.debug "Transaction ID is not available. Choose a random broker." return random_broker else get_coordinator(Kafka::Protocol::COORDINATOR_TYPE_TRANSACTION, transactional_id) end end
ruby
def get_transaction_coordinator(transactional_id:) @logger.debug "Getting transaction coordinator for `#{transactional_id}`" refresh_metadata_if_necessary! if transactional_id.nil? # Get a random_broker @logger.debug "Transaction ID is not available. Choose a random broker." return random_broker else get_coordinator(Kafka::Protocol::COORDINATOR_TYPE_TRANSACTION, transactional_id) end end
[ "def", "get_transaction_coordinator", "(", "transactional_id", ":", ")", "@logger", ".", "debug", "\"Getting transaction coordinator for `#{transactional_id}`\"", "refresh_metadata_if_necessary!", "if", "transactional_id", ".", "nil?", "# Get a random_broker", "@logger", ".", "debug", "\"Transaction ID is not available. Choose a random broker.\"", "return", "random_broker", "else", "get_coordinator", "(", "Kafka", "::", "Protocol", "::", "COORDINATOR_TYPE_TRANSACTION", ",", "transactional_id", ")", "end", "end" ]
Finds the broker acting as the coordinator of the given transaction. @param transactional_id: [String] @return [Broker] the broker that's currently coordinator.
[ "Finds", "the", "broker", "acting", "as", "the", "coordinator", "of", "the", "given", "transaction", "." ]
2a73471b6a607a52dc85c79301ba522acb4566b5
https://github.com/zendesk/ruby-kafka/blob/2a73471b6a607a52dc85c79301ba522acb4566b5/lib/kafka/cluster.rb#L128-L140
10,986
zendesk/ruby-kafka
lib/kafka/cluster.rb
Kafka.Cluster.list_topics
def list_topics response = random_broker.fetch_metadata(topics: nil) response.topics.select do |topic| topic.topic_error_code == 0 end.map(&:topic_name) end
ruby
def list_topics response = random_broker.fetch_metadata(topics: nil) response.topics.select do |topic| topic.topic_error_code == 0 end.map(&:topic_name) end
[ "def", "list_topics", "response", "=", "random_broker", ".", "fetch_metadata", "(", "topics", ":", "nil", ")", "response", ".", "topics", ".", "select", "do", "|", "topic", "|", "topic", ".", "topic_error_code", "==", "0", "end", ".", "map", "(", ":topic_name", ")", "end" ]
Lists all topics in the cluster.
[ "Lists", "all", "topics", "in", "the", "cluster", "." ]
2a73471b6a607a52dc85c79301ba522acb4566b5
https://github.com/zendesk/ruby-kafka/blob/2a73471b6a607a52dc85c79301ba522acb4566b5/lib/kafka/cluster.rb#L329-L334
10,987
zendesk/ruby-kafka
lib/kafka/cluster.rb
Kafka.Cluster.fetch_cluster_info
def fetch_cluster_info errors = [] @seed_brokers.shuffle.each do |node| @logger.info "Fetching cluster metadata from #{node}" begin broker = @broker_pool.connect(node.hostname, node.port) cluster_info = broker.fetch_metadata(topics: @target_topics) if cluster_info.brokers.empty? @logger.error "No brokers in cluster" else @logger.info "Discovered cluster metadata; nodes: #{cluster_info.brokers.join(', ')}" @stale = false return cluster_info end rescue Error => e @logger.error "Failed to fetch metadata from #{node}: #{e}" errors << [node, e] ensure broker.disconnect unless broker.nil? end end error_description = errors.map {|node, exception| "- #{node}: #{exception}" }.join("\n") raise ConnectionError, "Could not connect to any of the seed brokers:\n#{error_description}" end
ruby
def fetch_cluster_info errors = [] @seed_brokers.shuffle.each do |node| @logger.info "Fetching cluster metadata from #{node}" begin broker = @broker_pool.connect(node.hostname, node.port) cluster_info = broker.fetch_metadata(topics: @target_topics) if cluster_info.brokers.empty? @logger.error "No brokers in cluster" else @logger.info "Discovered cluster metadata; nodes: #{cluster_info.brokers.join(', ')}" @stale = false return cluster_info end rescue Error => e @logger.error "Failed to fetch metadata from #{node}: #{e}" errors << [node, e] ensure broker.disconnect unless broker.nil? end end error_description = errors.map {|node, exception| "- #{node}: #{exception}" }.join("\n") raise ConnectionError, "Could not connect to any of the seed brokers:\n#{error_description}" end
[ "def", "fetch_cluster_info", "errors", "=", "[", "]", "@seed_brokers", ".", "shuffle", ".", "each", "do", "|", "node", "|", "@logger", ".", "info", "\"Fetching cluster metadata from #{node}\"", "begin", "broker", "=", "@broker_pool", ".", "connect", "(", "node", ".", "hostname", ",", "node", ".", "port", ")", "cluster_info", "=", "broker", ".", "fetch_metadata", "(", "topics", ":", "@target_topics", ")", "if", "cluster_info", ".", "brokers", ".", "empty?", "@logger", ".", "error", "\"No brokers in cluster\"", "else", "@logger", ".", "info", "\"Discovered cluster metadata; nodes: #{cluster_info.brokers.join(', ')}\"", "@stale", "=", "false", "return", "cluster_info", "end", "rescue", "Error", "=>", "e", "@logger", ".", "error", "\"Failed to fetch metadata from #{node}: #{e}\"", "errors", "<<", "[", "node", ",", "e", "]", "ensure", "broker", ".", "disconnect", "unless", "broker", ".", "nil?", "end", "end", "error_description", "=", "errors", ".", "map", "{", "|", "node", ",", "exception", "|", "\"- #{node}: #{exception}\"", "}", ".", "join", "(", "\"\\n\"", ")", "raise", "ConnectionError", ",", "\"Could not connect to any of the seed brokers:\\n#{error_description}\"", "end" ]
Fetches the cluster metadata. This is used to update the partition leadership information, among other things. The methods will go through each node listed in `seed_brokers`, connecting to the first one that is available. This node will be queried for the cluster metadata. @raise [ConnectionError] if none of the nodes in `seed_brokers` are available. @return [Protocol::MetadataResponse] the cluster metadata.
[ "Fetches", "the", "cluster", "metadata", "." ]
2a73471b6a607a52dc85c79301ba522acb4566b5
https://github.com/zendesk/ruby-kafka/blob/2a73471b6a607a52dc85c79301ba522acb4566b5/lib/kafka/cluster.rb#L367-L397
10,988
zendesk/ruby-kafka
lib/kafka/async_producer.rb
Kafka.AsyncProducer.produce
def produce(value, topic:, **options) ensure_threads_running! if @queue.size >= @max_queue_size buffer_overflow topic, "Cannot produce to #{topic}, max queue size (#{@max_queue_size} messages) reached" end args = [value, **options.merge(topic: topic)] @queue << [:produce, args] @instrumenter.instrument("enqueue_message.async_producer", { topic: topic, queue_size: @queue.size, max_queue_size: @max_queue_size, }) nil end
ruby
def produce(value, topic:, **options) ensure_threads_running! if @queue.size >= @max_queue_size buffer_overflow topic, "Cannot produce to #{topic}, max queue size (#{@max_queue_size} messages) reached" end args = [value, **options.merge(topic: topic)] @queue << [:produce, args] @instrumenter.instrument("enqueue_message.async_producer", { topic: topic, queue_size: @queue.size, max_queue_size: @max_queue_size, }) nil end
[ "def", "produce", "(", "value", ",", "topic", ":", ",", "**", "options", ")", "ensure_threads_running!", "if", "@queue", ".", "size", ">=", "@max_queue_size", "buffer_overflow", "topic", ",", "\"Cannot produce to #{topic}, max queue size (#{@max_queue_size} messages) reached\"", "end", "args", "=", "[", "value", ",", "**", "options", ".", "merge", "(", "topic", ":", "topic", ")", "]", "@queue", "<<", "[", ":produce", ",", "args", "]", "@instrumenter", ".", "instrument", "(", "\"enqueue_message.async_producer\"", ",", "{", "topic", ":", "topic", ",", "queue_size", ":", "@queue", ".", "size", ",", "max_queue_size", ":", "@max_queue_size", ",", "}", ")", "nil", "end" ]
Initializes a new AsyncProducer. @param sync_producer [Kafka::Producer] the synchronous producer that should be used in the background. @param max_queue_size [Integer] the maximum number of messages allowed in the queue. @param delivery_threshold [Integer] if greater than zero, the number of buffered messages that will automatically trigger a delivery. @param delivery_interval [Integer] if greater than zero, the number of seconds between automatic message deliveries. Produces a message to the specified topic. @see Kafka::Producer#produce @param (see Kafka::Producer#produce) @raise [BufferOverflow] if the message queue is full. @return [nil]
[ "Initializes", "a", "new", "AsyncProducer", "." ]
2a73471b6a607a52dc85c79301ba522acb4566b5
https://github.com/zendesk/ruby-kafka/blob/2a73471b6a607a52dc85c79301ba522acb4566b5/lib/kafka/async_producer.rb#L105-L123
10,989
zendesk/ruby-kafka
lib/kafka/ssl_socket_with_timeout.rb
Kafka.SSLSocketWithTimeout.write
def write(bytes) loop do written = 0 begin # unlike plain tcp sockets, ssl sockets don't support IO.select # properly. # Instead, timeouts happen on a per write basis, and we have to # catch exceptions from write_nonblock, and gradually build up # our write buffer. written += @ssl_socket.write_nonblock(bytes) rescue Errno::EFAULT => error raise error rescue OpenSSL::SSL::SSLError, Errno::EAGAIN, Errno::EWOULDBLOCK, IO::WaitWritable => error if error.is_a?(OpenSSL::SSL::SSLError) && error.message == 'write would block' if select_with_timeout(@ssl_socket, :write) retry else raise Errno::ETIMEDOUT end else raise error end end # Fast, common case. break if written == bytes.size # This takes advantage of the fact that most ruby implementations # have Copy-On-Write strings. Thusly why requesting a subrange # of data, we actually don't copy data because the new string # simply references a subrange of the original. bytes = bytes[written, bytes.size] end end
ruby
def write(bytes) loop do written = 0 begin # unlike plain tcp sockets, ssl sockets don't support IO.select # properly. # Instead, timeouts happen on a per write basis, and we have to # catch exceptions from write_nonblock, and gradually build up # our write buffer. written += @ssl_socket.write_nonblock(bytes) rescue Errno::EFAULT => error raise error rescue OpenSSL::SSL::SSLError, Errno::EAGAIN, Errno::EWOULDBLOCK, IO::WaitWritable => error if error.is_a?(OpenSSL::SSL::SSLError) && error.message == 'write would block' if select_with_timeout(@ssl_socket, :write) retry else raise Errno::ETIMEDOUT end else raise error end end # Fast, common case. break if written == bytes.size # This takes advantage of the fact that most ruby implementations # have Copy-On-Write strings. Thusly why requesting a subrange # of data, we actually don't copy data because the new string # simply references a subrange of the original. bytes = bytes[written, bytes.size] end end
[ "def", "write", "(", "bytes", ")", "loop", "do", "written", "=", "0", "begin", "# unlike plain tcp sockets, ssl sockets don't support IO.select", "# properly.", "# Instead, timeouts happen on a per write basis, and we have to", "# catch exceptions from write_nonblock, and gradually build up", "# our write buffer.", "written", "+=", "@ssl_socket", ".", "write_nonblock", "(", "bytes", ")", "rescue", "Errno", "::", "EFAULT", "=>", "error", "raise", "error", "rescue", "OpenSSL", "::", "SSL", "::", "SSLError", ",", "Errno", "::", "EAGAIN", ",", "Errno", "::", "EWOULDBLOCK", ",", "IO", "::", "WaitWritable", "=>", "error", "if", "error", ".", "is_a?", "(", "OpenSSL", "::", "SSL", "::", "SSLError", ")", "&&", "error", ".", "message", "==", "'write would block'", "if", "select_with_timeout", "(", "@ssl_socket", ",", ":write", ")", "retry", "else", "raise", "Errno", "::", "ETIMEDOUT", "end", "else", "raise", "error", "end", "end", "# Fast, common case.", "break", "if", "written", "==", "bytes", ".", "size", "# This takes advantage of the fact that most ruby implementations", "# have Copy-On-Write strings. Thusly why requesting a subrange", "# of data, we actually don't copy data because the new string", "# simply references a subrange of the original.", "bytes", "=", "bytes", "[", "written", ",", "bytes", ".", "size", "]", "end", "end" ]
Writes bytes to the socket, possible with a timeout. @param bytes [String] the data that should be written to the socket. @raise [Errno::ETIMEDOUT] if the timeout is exceeded. @return [Integer] the number of bytes written.
[ "Writes", "bytes", "to", "the", "socket", "possible", "with", "a", "timeout", "." ]
2a73471b6a607a52dc85c79301ba522acb4566b5
https://github.com/zendesk/ruby-kafka/blob/2a73471b6a607a52dc85c79301ba522acb4566b5/lib/kafka/ssl_socket_with_timeout.rb#L126-L159
10,990
zendesk/ruby-kafka
lib/kafka/consumer.rb
Kafka.Consumer.subscribe
def subscribe(topic_or_regex, default_offset: nil, start_from_beginning: true, max_bytes_per_partition: 1048576) default_offset ||= start_from_beginning ? :earliest : :latest if topic_or_regex.is_a?(Regexp) cluster_topics.select { |topic| topic =~ topic_or_regex }.each do |topic| subscribe_to_topic(topic, default_offset, start_from_beginning, max_bytes_per_partition) end else subscribe_to_topic(topic_or_regex, default_offset, start_from_beginning, max_bytes_per_partition) end nil end
ruby
def subscribe(topic_or_regex, default_offset: nil, start_from_beginning: true, max_bytes_per_partition: 1048576) default_offset ||= start_from_beginning ? :earliest : :latest if topic_or_regex.is_a?(Regexp) cluster_topics.select { |topic| topic =~ topic_or_regex }.each do |topic| subscribe_to_topic(topic, default_offset, start_from_beginning, max_bytes_per_partition) end else subscribe_to_topic(topic_or_regex, default_offset, start_from_beginning, max_bytes_per_partition) end nil end
[ "def", "subscribe", "(", "topic_or_regex", ",", "default_offset", ":", "nil", ",", "start_from_beginning", ":", "true", ",", "max_bytes_per_partition", ":", "1048576", ")", "default_offset", "||=", "start_from_beginning", "?", ":earliest", ":", ":latest", "if", "topic_or_regex", ".", "is_a?", "(", "Regexp", ")", "cluster_topics", ".", "select", "{", "|", "topic", "|", "topic", "=~", "topic_or_regex", "}", ".", "each", "do", "|", "topic", "|", "subscribe_to_topic", "(", "topic", ",", "default_offset", ",", "start_from_beginning", ",", "max_bytes_per_partition", ")", "end", "else", "subscribe_to_topic", "(", "topic_or_regex", ",", "default_offset", ",", "start_from_beginning", ",", "max_bytes_per_partition", ")", "end", "nil", "end" ]
Subscribes the consumer to a topic. Typically you either want to start reading messages from the very beginning of the topic's partitions or you simply want to wait for new messages to be written. In the former case, set `start_from_beginning` to true (the default); in the latter, set it to false. @param topic_or_regex [String, Regexp] subscribe to single topic with a string or multiple topics matching a regex. @param default_offset [Symbol] whether to start from the beginning or the end of the topic's partitions. Deprecated. @param start_from_beginning [Boolean] whether to start from the beginning of the topic or just subscribe to new messages being produced. This only applies when first consuming a topic partition – once the consumer has checkpointed its progress, it will always resume from the last checkpoint. @param max_bytes_per_partition [Integer] the maximum amount of data fetched from a single partition at a time. @return [nil]
[ "Subscribes", "the", "consumer", "to", "a", "topic", "." ]
2a73471b6a607a52dc85c79301ba522acb4566b5
https://github.com/zendesk/ruby-kafka/blob/2a73471b6a607a52dc85c79301ba522acb4566b5/lib/kafka/consumer.rb#L97-L109
10,991
zendesk/ruby-kafka
lib/kafka/consumer.rb
Kafka.Consumer.pause
def pause(topic, partition, timeout: nil, max_timeout: nil, exponential_backoff: false) if max_timeout && !exponential_backoff raise ArgumentError, "`max_timeout` only makes sense when `exponential_backoff` is enabled" end pause_for(topic, partition).pause!( timeout: timeout, max_timeout: max_timeout, exponential_backoff: exponential_backoff, ) end
ruby
def pause(topic, partition, timeout: nil, max_timeout: nil, exponential_backoff: false) if max_timeout && !exponential_backoff raise ArgumentError, "`max_timeout` only makes sense when `exponential_backoff` is enabled" end pause_for(topic, partition).pause!( timeout: timeout, max_timeout: max_timeout, exponential_backoff: exponential_backoff, ) end
[ "def", "pause", "(", "topic", ",", "partition", ",", "timeout", ":", "nil", ",", "max_timeout", ":", "nil", ",", "exponential_backoff", ":", "false", ")", "if", "max_timeout", "&&", "!", "exponential_backoff", "raise", "ArgumentError", ",", "\"`max_timeout` only makes sense when `exponential_backoff` is enabled\"", "end", "pause_for", "(", "topic", ",", "partition", ")", ".", "pause!", "(", "timeout", ":", "timeout", ",", "max_timeout", ":", "max_timeout", ",", "exponential_backoff", ":", "exponential_backoff", ",", ")", "end" ]
Pause processing of a specific topic partition. When a specific message causes the processor code to fail, it can be a good idea to simply pause the partition until the error can be resolved, allowing the rest of the partitions to continue being processed. If the `timeout` argument is passed, the partition will automatically be resumed when the timeout expires. If `exponential_backoff` is enabled, each subsequent pause will cause the timeout to double until a message from the partition has been successfully processed. @param topic [String] @param partition [Integer] @param timeout [nil, Integer] the number of seconds to pause the partition for, or `nil` if the partition should not be automatically resumed. @param max_timeout [nil, Integer] the maximum number of seconds to pause for, or `nil` if no maximum should be enforced. @param exponential_backoff [Boolean] whether to enable exponential backoff. @return [nil]
[ "Pause", "processing", "of", "a", "specific", "topic", "partition", "." ]
2a73471b6a607a52dc85c79301ba522acb4566b5
https://github.com/zendesk/ruby-kafka/blob/2a73471b6a607a52dc85c79301ba522acb4566b5/lib/kafka/consumer.rb#L141-L151
10,992
zendesk/ruby-kafka
lib/kafka/consumer.rb
Kafka.Consumer.resume
def resume(topic, partition) pause_for(topic, partition).resume! # During re-balancing we might have lost the paused partition. Check if partition is still in group before seek. seek_to_next(topic, partition) if @group.assigned_to?(topic, partition) end
ruby
def resume(topic, partition) pause_for(topic, partition).resume! # During re-balancing we might have lost the paused partition. Check if partition is still in group before seek. seek_to_next(topic, partition) if @group.assigned_to?(topic, partition) end
[ "def", "resume", "(", "topic", ",", "partition", ")", "pause_for", "(", "topic", ",", "partition", ")", ".", "resume!", "# During re-balancing we might have lost the paused partition. Check if partition is still in group before seek.", "seek_to_next", "(", "topic", ",", "partition", ")", "if", "@group", ".", "assigned_to?", "(", "topic", ",", "partition", ")", "end" ]
Resume processing of a topic partition. @see #pause @param topic [String] @param partition [Integer] @return [nil]
[ "Resume", "processing", "of", "a", "topic", "partition", "." ]
2a73471b6a607a52dc85c79301ba522acb4566b5
https://github.com/zendesk/ruby-kafka/blob/2a73471b6a607a52dc85c79301ba522acb4566b5/lib/kafka/consumer.rb#L159-L164
10,993
zendesk/ruby-kafka
lib/kafka/consumer.rb
Kafka.Consumer.paused?
def paused?(topic, partition) pause = pause_for(topic, partition) pause.paused? && !pause.expired? end
ruby
def paused?(topic, partition) pause = pause_for(topic, partition) pause.paused? && !pause.expired? end
[ "def", "paused?", "(", "topic", ",", "partition", ")", "pause", "=", "pause_for", "(", "topic", ",", "partition", ")", "pause", ".", "paused?", "&&", "!", "pause", ".", "expired?", "end" ]
Whether the topic partition is currently paused. @see #pause @param topic [String] @param partition [Integer] @return [Boolean] true if the partition is paused, false otherwise.
[ "Whether", "the", "topic", "partition", "is", "currently", "paused", "." ]
2a73471b6a607a52dc85c79301ba522acb4566b5
https://github.com/zendesk/ruby-kafka/blob/2a73471b6a607a52dc85c79301ba522acb4566b5/lib/kafka/consumer.rb#L172-L175
10,994
zendesk/ruby-kafka
lib/kafka/offset_manager.rb
Kafka.OffsetManager.seek_to_default
def seek_to_default(topic, partition) # Remove any cached offset, in case things have changed broker-side. clear_resolved_offset(topic) offset = resolve_offset(topic, partition) seek_to(topic, partition, offset) end
ruby
def seek_to_default(topic, partition) # Remove any cached offset, in case things have changed broker-side. clear_resolved_offset(topic) offset = resolve_offset(topic, partition) seek_to(topic, partition, offset) end
[ "def", "seek_to_default", "(", "topic", ",", "partition", ")", "# Remove any cached offset, in case things have changed broker-side.", "clear_resolved_offset", "(", "topic", ")", "offset", "=", "resolve_offset", "(", "topic", ",", "partition", ")", "seek_to", "(", "topic", ",", "partition", ",", "offset", ")", "end" ]
Move the consumer's position in the partition back to the configured default offset, either the first or latest in the partition. @param topic [String] the name of the topic. @param partition [Integer] the partition number. @return [nil]
[ "Move", "the", "consumer", "s", "position", "in", "the", "partition", "back", "to", "the", "configured", "default", "offset", "either", "the", "first", "or", "latest", "in", "the", "partition", "." ]
2a73471b6a607a52dc85c79301ba522acb4566b5
https://github.com/zendesk/ruby-kafka/blob/2a73471b6a607a52dc85c79301ba522acb4566b5/lib/kafka/offset_manager.rb#L68-L75
10,995
zendesk/ruby-kafka
lib/kafka/offset_manager.rb
Kafka.OffsetManager.seek_to
def seek_to(topic, partition, offset) @processed_offsets[topic] ||= {} @processed_offsets[topic][partition] = offset @fetcher.seek(topic, partition, offset) end
ruby
def seek_to(topic, partition, offset) @processed_offsets[topic] ||= {} @processed_offsets[topic][partition] = offset @fetcher.seek(topic, partition, offset) end
[ "def", "seek_to", "(", "topic", ",", "partition", ",", "offset", ")", "@processed_offsets", "[", "topic", "]", "||=", "{", "}", "@processed_offsets", "[", "topic", "]", "[", "partition", "]", "=", "offset", "@fetcher", ".", "seek", "(", "topic", ",", "partition", ",", "offset", ")", "end" ]
Move the consumer's position in the partition to the specified offset. @param topic [String] the name of the topic. @param partition [Integer] the partition number. @param offset [Integer] the offset that the consumer position should be moved to. @return [nil]
[ "Move", "the", "consumer", "s", "position", "in", "the", "partition", "to", "the", "specified", "offset", "." ]
2a73471b6a607a52dc85c79301ba522acb4566b5
https://github.com/zendesk/ruby-kafka/blob/2a73471b6a607a52dc85c79301ba522acb4566b5/lib/kafka/offset_manager.rb#L83-L88
10,996
zendesk/ruby-kafka
lib/kafka/offset_manager.rb
Kafka.OffsetManager.next_offset_for
def next_offset_for(topic, partition) offset = @processed_offsets.fetch(topic, {}).fetch(partition) { committed_offset_for(topic, partition) } # A negative offset means that no offset has been committed, so we need to # resolve the default offset for the topic. if offset < 0 resolve_offset(topic, partition) else # The next offset is the last offset. offset end end
ruby
def next_offset_for(topic, partition) offset = @processed_offsets.fetch(topic, {}).fetch(partition) { committed_offset_for(topic, partition) } # A negative offset means that no offset has been committed, so we need to # resolve the default offset for the topic. if offset < 0 resolve_offset(topic, partition) else # The next offset is the last offset. offset end end
[ "def", "next_offset_for", "(", "topic", ",", "partition", ")", "offset", "=", "@processed_offsets", ".", "fetch", "(", "topic", ",", "{", "}", ")", ".", "fetch", "(", "partition", ")", "{", "committed_offset_for", "(", "topic", ",", "partition", ")", "}", "# A negative offset means that no offset has been committed, so we need to", "# resolve the default offset for the topic.", "if", "offset", "<", "0", "resolve_offset", "(", "topic", ",", "partition", ")", "else", "# The next offset is the last offset.", "offset", "end", "end" ]
Return the next offset that should be fetched for the specified partition. @param topic [String] the name of the topic. @param partition [Integer] the partition number. @return [Integer] the next offset that should be fetched.
[ "Return", "the", "next", "offset", "that", "should", "be", "fetched", "for", "the", "specified", "partition", "." ]
2a73471b6a607a52dc85c79301ba522acb4566b5
https://github.com/zendesk/ruby-kafka/blob/2a73471b6a607a52dc85c79301ba522acb4566b5/lib/kafka/offset_manager.rb#L95-L108
10,997
zendesk/ruby-kafka
lib/kafka/offset_manager.rb
Kafka.OffsetManager.commit_offsets
def commit_offsets(recommit = false) offsets = offsets_to_commit(recommit) unless offsets.empty? @logger.debug "Committing offsets#{recommit ? ' with recommit' : ''}: #{prettify_offsets(offsets)}" @group.commit_offsets(offsets) @last_commit = Time.now @last_recommit = Time.now if recommit @uncommitted_offsets = 0 @committed_offsets = nil end end
ruby
def commit_offsets(recommit = false) offsets = offsets_to_commit(recommit) unless offsets.empty? @logger.debug "Committing offsets#{recommit ? ' with recommit' : ''}: #{prettify_offsets(offsets)}" @group.commit_offsets(offsets) @last_commit = Time.now @last_recommit = Time.now if recommit @uncommitted_offsets = 0 @committed_offsets = nil end end
[ "def", "commit_offsets", "(", "recommit", "=", "false", ")", "offsets", "=", "offsets_to_commit", "(", "recommit", ")", "unless", "offsets", ".", "empty?", "@logger", ".", "debug", "\"Committing offsets#{recommit ? ' with recommit' : ''}: #{prettify_offsets(offsets)}\"", "@group", ".", "commit_offsets", "(", "offsets", ")", "@last_commit", "=", "Time", ".", "now", "@last_recommit", "=", "Time", ".", "now", "if", "recommit", "@uncommitted_offsets", "=", "0", "@committed_offsets", "=", "nil", "end", "end" ]
Commit offsets of messages that have been marked as processed. If `recommit` is set to true, we will also commit the existing positions even if no messages have been processed on a partition. This is done in order to avoid the offset information expiring in cases where messages are very rare -- it's essentially a keep-alive. @param recommit [Boolean] whether to recommit offsets that have already been committed. @return [nil]
[ "Commit", "offsets", "of", "messages", "that", "have", "been", "marked", "as", "processed", "." ]
2a73471b6a607a52dc85c79301ba522acb4566b5
https://github.com/zendesk/ruby-kafka/blob/2a73471b6a607a52dc85c79301ba522acb4566b5/lib/kafka/offset_manager.rb#L120-L133
10,998
zendesk/ruby-kafka
lib/kafka/offset_manager.rb
Kafka.OffsetManager.clear_offsets_excluding
def clear_offsets_excluding(excluded) # Clear all offsets that aren't in `excluded`. @processed_offsets.each do |topic, partitions| partitions.keep_if do |partition, _| excluded.fetch(topic, []).include?(partition) end end # Clear the cached commits from the brokers. @committed_offsets = nil @resolved_offsets.clear end
ruby
def clear_offsets_excluding(excluded) # Clear all offsets that aren't in `excluded`. @processed_offsets.each do |topic, partitions| partitions.keep_if do |partition, _| excluded.fetch(topic, []).include?(partition) end end # Clear the cached commits from the brokers. @committed_offsets = nil @resolved_offsets.clear end
[ "def", "clear_offsets_excluding", "(", "excluded", ")", "# Clear all offsets that aren't in `excluded`.", "@processed_offsets", ".", "each", "do", "|", "topic", ",", "partitions", "|", "partitions", ".", "keep_if", "do", "|", "partition", ",", "_", "|", "excluded", ".", "fetch", "(", "topic", ",", "[", "]", ")", ".", "include?", "(", "partition", ")", "end", "end", "# Clear the cached commits from the brokers.", "@committed_offsets", "=", "nil", "@resolved_offsets", ".", "clear", "end" ]
Clear stored offset information for all partitions except those specified in `excluded`. offset_manager.clear_offsets_excluding("my-topic" => [1, 2, 3]) @return [nil]
[ "Clear", "stored", "offset", "information", "for", "all", "partitions", "except", "those", "specified", "in", "excluded", "." ]
2a73471b6a607a52dc85c79301ba522acb4566b5
https://github.com/zendesk/ruby-kafka/blob/2a73471b6a607a52dc85c79301ba522acb4566b5/lib/kafka/offset_manager.rb#L163-L174
10,999
zendesk/ruby-kafka
lib/kafka/connection.rb
Kafka.Connection.send_request
def send_request(request) api_name = Protocol.api_name(request.api_key) # Default notification payload. notification = { broker_host: @host, api: api_name, request_size: 0, response_size: 0, } raise IdleConnection if idle? @logger.push_tags(api_name) @instrumenter.instrument("request.connection", notification) do open unless open? @correlation_id += 1 @logger.debug "Sending #{api_name} API request #{@correlation_id} to #{to_s}" write_request(request, notification) response_class = request.response_class response = wait_for_response(response_class, notification) unless response_class.nil? @last_request = Time.now response end rescue SystemCallError, EOFError, IOError => e close raise ConnectionError, "Connection error #{e.class}: #{e}" ensure @logger.pop_tags end
ruby
def send_request(request) api_name = Protocol.api_name(request.api_key) # Default notification payload. notification = { broker_host: @host, api: api_name, request_size: 0, response_size: 0, } raise IdleConnection if idle? @logger.push_tags(api_name) @instrumenter.instrument("request.connection", notification) do open unless open? @correlation_id += 1 @logger.debug "Sending #{api_name} API request #{@correlation_id} to #{to_s}" write_request(request, notification) response_class = request.response_class response = wait_for_response(response_class, notification) unless response_class.nil? @last_request = Time.now response end rescue SystemCallError, EOFError, IOError => e close raise ConnectionError, "Connection error #{e.class}: #{e}" ensure @logger.pop_tags end
[ "def", "send_request", "(", "request", ")", "api_name", "=", "Protocol", ".", "api_name", "(", "request", ".", "api_key", ")", "# Default notification payload.", "notification", "=", "{", "broker_host", ":", "@host", ",", "api", ":", "api_name", ",", "request_size", ":", "0", ",", "response_size", ":", "0", ",", "}", "raise", "IdleConnection", "if", "idle?", "@logger", ".", "push_tags", "(", "api_name", ")", "@instrumenter", ".", "instrument", "(", "\"request.connection\"", ",", "notification", ")", "do", "open", "unless", "open?", "@correlation_id", "+=", "1", "@logger", ".", "debug", "\"Sending #{api_name} API request #{@correlation_id} to #{to_s}\"", "write_request", "(", "request", ",", "notification", ")", "response_class", "=", "request", ".", "response_class", "response", "=", "wait_for_response", "(", "response_class", ",", "notification", ")", "unless", "response_class", ".", "nil?", "@last_request", "=", "Time", ".", "now", "response", "end", "rescue", "SystemCallError", ",", "EOFError", ",", "IOError", "=>", "e", "close", "raise", "ConnectionError", ",", "\"Connection error #{e.class}: #{e}\"", "ensure", "@logger", ".", "pop_tags", "end" ]
Sends a request over the connection. @param request [#encode, #response_class] the request that should be encoded and written. @return [Object] the response.
[ "Sends", "a", "request", "over", "the", "connection", "." ]
2a73471b6a607a52dc85c79301ba522acb4566b5
https://github.com/zendesk/ruby-kafka/blob/2a73471b6a607a52dc85c79301ba522acb4566b5/lib/kafka/connection.rb#L83-L119