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
16,600
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.browse
def browse(page_or_query_parameters = nil, hits_per_page = nil, request_options = {}, &block) params = {} if page_or_query_parameters.is_a?(Hash) params.merge!(page_or_query_parameters) else params[:page] = page_or_query_parameters unless page_or_query_parameters.nil? end if hits_per_page.is_a?(Hash) params.merge!(hits_per_page) else params[:hitsPerPage] = hits_per_page unless hits_per_page.nil? end if block_given? IndexBrowser.new(client, name, params).browse(request_options, &block) else params[:page] ||= 0 params[:hitsPerPage] ||= 1000 client.get(Protocol.browse_uri(name, params), :read, request_options) end end
ruby
def browse(page_or_query_parameters = nil, hits_per_page = nil, request_options = {}, &block) params = {} if page_or_query_parameters.is_a?(Hash) params.merge!(page_or_query_parameters) else params[:page] = page_or_query_parameters unless page_or_query_parameters.nil? end if hits_per_page.is_a?(Hash) params.merge!(hits_per_page) else params[:hitsPerPage] = hits_per_page unless hits_per_page.nil? end if block_given? IndexBrowser.new(client, name, params).browse(request_options, &block) else params[:page] ||= 0 params[:hitsPerPage] ||= 1000 client.get(Protocol.browse_uri(name, params), :read, request_options) end end
[ "def", "browse", "(", "page_or_query_parameters", "=", "nil", ",", "hits_per_page", "=", "nil", ",", "request_options", "=", "{", "}", ",", "&", "block", ")", "params", "=", "{", "}", "if", "page_or_query_parameters", ".", "is_a?", "(", "Hash", ")", "params", ".", "merge!", "(", "page_or_query_parameters", ")", "else", "params", "[", ":page", "]", "=", "page_or_query_parameters", "unless", "page_or_query_parameters", ".", "nil?", "end", "if", "hits_per_page", ".", "is_a?", "(", "Hash", ")", "params", ".", "merge!", "(", "hits_per_page", ")", "else", "params", "[", ":hitsPerPage", "]", "=", "hits_per_page", "unless", "hits_per_page", ".", "nil?", "end", "if", "block_given?", "IndexBrowser", ".", "new", "(", "client", ",", "name", ",", "params", ")", ".", "browse", "(", "request_options", ",", "block", ")", "else", "params", "[", ":page", "]", "||=", "0", "params", "[", ":hitsPerPage", "]", "||=", "1000", "client", ".", "get", "(", "Protocol", ".", "browse_uri", "(", "name", ",", "params", ")", ",", ":read", ",", "request_options", ")", "end", "end" ]
Browse all index content @param queryParameters The hash of query parameters to use to browse To browse from a specific cursor, just add a ":cursor" parameters @param queryParameters An optional second parameters hash here for backward-compatibility (which will be merged with the first) @param request_options contains extra parameters to send with your query @DEPRECATED: @param page Pagination parameter used to select the page to retrieve. @param hits_per_page Pagination parameter used to select the number of hits per page. Defaults to 1000.
[ "Browse", "all", "index", "content" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L203-L223
16,601
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.browse_from
def browse_from(cursor, hits_per_page = 1000, request_options = {}) client.post(Protocol.browse_uri(name), { :cursor => cursor, :hitsPerPage => hits_per_page }.to_json, :read, request_options) end
ruby
def browse_from(cursor, hits_per_page = 1000, request_options = {}) client.post(Protocol.browse_uri(name), { :cursor => cursor, :hitsPerPage => hits_per_page }.to_json, :read, request_options) end
[ "def", "browse_from", "(", "cursor", ",", "hits_per_page", "=", "1000", ",", "request_options", "=", "{", "}", ")", "client", ".", "post", "(", "Protocol", ".", "browse_uri", "(", "name", ")", ",", "{", ":cursor", "=>", "cursor", ",", ":hitsPerPage", "=>", "hits_per_page", "}", ".", "to_json", ",", ":read", ",", "request_options", ")", "end" ]
Browse a single page from a specific cursor @param request_options contains extra parameters to send with your query
[ "Browse", "a", "single", "page", "from", "a", "specific", "cursor" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L230-L232
16,602
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.get_object
def get_object(objectID, attributes_to_retrieve = nil, request_options = {}) attributes_to_retrieve = attributes_to_retrieve.join(',') if attributes_to_retrieve.is_a?(Array) if attributes_to_retrieve.nil? client.get(Protocol.object_uri(name, objectID, nil), :read, request_options) else client.get(Protocol.object_uri(name, objectID, { :attributes => attributes_to_retrieve }), :read, request_options) end end
ruby
def get_object(objectID, attributes_to_retrieve = nil, request_options = {}) attributes_to_retrieve = attributes_to_retrieve.join(',') if attributes_to_retrieve.is_a?(Array) if attributes_to_retrieve.nil? client.get(Protocol.object_uri(name, objectID, nil), :read, request_options) else client.get(Protocol.object_uri(name, objectID, { :attributes => attributes_to_retrieve }), :read, request_options) end end
[ "def", "get_object", "(", "objectID", ",", "attributes_to_retrieve", "=", "nil", ",", "request_options", "=", "{", "}", ")", "attributes_to_retrieve", "=", "attributes_to_retrieve", ".", "join", "(", "','", ")", "if", "attributes_to_retrieve", ".", "is_a?", "(", "Array", ")", "if", "attributes_to_retrieve", ".", "nil?", "client", ".", "get", "(", "Protocol", ".", "object_uri", "(", "name", ",", "objectID", ",", "nil", ")", ",", ":read", ",", "request_options", ")", "else", "client", ".", "get", "(", "Protocol", ".", "object_uri", "(", "name", ",", "objectID", ",", "{", ":attributes", "=>", "attributes_to_retrieve", "}", ")", ",", ":read", ",", "request_options", ")", "end", "end" ]
Get an object from this index @param objectID the unique identifier of the object to retrieve @param attributes_to_retrieve (optional) if set, contains the list of attributes to retrieve as an array of strings of a string separated by "," @param request_options contains extra parameters to send with your query
[ "Get", "an", "object", "from", "this", "index" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L241-L248
16,603
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.get_objects
def get_objects(objectIDs, attributes_to_retrieve = nil, request_options = {}) attributes_to_retrieve = attributes_to_retrieve.join(',') if attributes_to_retrieve.is_a?(Array) requests = objectIDs.map do |objectID| req = { :indexName => name, :objectID => objectID.to_s } req[:attributesToRetrieve] = attributes_to_retrieve unless attributes_to_retrieve.nil? req end client.post(Protocol.objects_uri, { :requests => requests }.to_json, :read, request_options)['results'] end
ruby
def get_objects(objectIDs, attributes_to_retrieve = nil, request_options = {}) attributes_to_retrieve = attributes_to_retrieve.join(',') if attributes_to_retrieve.is_a?(Array) requests = objectIDs.map do |objectID| req = { :indexName => name, :objectID => objectID.to_s } req[:attributesToRetrieve] = attributes_to_retrieve unless attributes_to_retrieve.nil? req end client.post(Protocol.objects_uri, { :requests => requests }.to_json, :read, request_options)['results'] end
[ "def", "get_objects", "(", "objectIDs", ",", "attributes_to_retrieve", "=", "nil", ",", "request_options", "=", "{", "}", ")", "attributes_to_retrieve", "=", "attributes_to_retrieve", ".", "join", "(", "','", ")", "if", "attributes_to_retrieve", ".", "is_a?", "(", "Array", ")", "requests", "=", "objectIDs", ".", "map", "do", "|", "objectID", "|", "req", "=", "{", ":indexName", "=>", "name", ",", ":objectID", "=>", "objectID", ".", "to_s", "}", "req", "[", ":attributesToRetrieve", "]", "=", "attributes_to_retrieve", "unless", "attributes_to_retrieve", ".", "nil?", "req", "end", "client", ".", "post", "(", "Protocol", ".", "objects_uri", ",", "{", ":requests", "=>", "requests", "}", ".", "to_json", ",", ":read", ",", "request_options", ")", "[", "'results'", "]", "end" ]
Get a list of objects from this index @param objectIDs the array of unique identifier of the objects to retrieve @param attributes_to_retrieve (optional) if set, contains the list of attributes to retrieve as an array of strings of a string separated by "," @param request_options contains extra parameters to send with your query
[ "Get", "a", "list", "of", "objects", "from", "this", "index" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L257-L265
16,604
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.save_object
def save_object(object, objectID = nil, request_options = {}) client.put(Protocol.object_uri(name, get_objectID(object, objectID)), object.to_json, :write, request_options) end
ruby
def save_object(object, objectID = nil, request_options = {}) client.put(Protocol.object_uri(name, get_objectID(object, objectID)), object.to_json, :write, request_options) end
[ "def", "save_object", "(", "object", ",", "objectID", "=", "nil", ",", "request_options", "=", "{", "}", ")", "client", ".", "put", "(", "Protocol", ".", "object_uri", "(", "name", ",", "get_objectID", "(", "object", ",", "objectID", ")", ")", ",", "object", ".", "to_json", ",", ":write", ",", "request_options", ")", "end" ]
Override the content of an object @param object the object to save @param objectID the associated objectID, if nil 'object' must contain an 'objectID' key @param request_options contains extra parameters to send with your query
[ "Override", "the", "content", "of", "an", "object" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L297-L299
16,605
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.save_object!
def save_object!(object, objectID = nil, request_options = {}) res = save_object(object, objectID, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
ruby
def save_object!(object, objectID = nil, request_options = {}) res = save_object(object, objectID, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
[ "def", "save_object!", "(", "object", ",", "objectID", "=", "nil", ",", "request_options", "=", "{", "}", ")", "res", "=", "save_object", "(", "object", ",", "objectID", ",", "request_options", ")", "wait_task", "(", "res", "[", "'taskID'", "]", ",", "WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY", ",", "request_options", ")", "res", "end" ]
Override the content of object and wait end of indexing @param object the object to save @param objectID the associated objectID, if nil 'object' must contain an 'objectID' key @param request_options contains extra parameters to send with your query
[ "Override", "the", "content", "of", "object", "and", "wait", "end", "of", "indexing" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L308-L312
16,606
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.save_objects!
def save_objects!(objects, request_options = {}) res = save_objects(objects, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
ruby
def save_objects!(objects, request_options = {}) res = save_objects(objects, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
[ "def", "save_objects!", "(", "objects", ",", "request_options", "=", "{", "}", ")", "res", "=", "save_objects", "(", "objects", ",", "request_options", ")", "wait_task", "(", "res", "[", "'taskID'", "]", ",", "WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY", ",", "request_options", ")", "res", "end" ]
Override the content of several objects and wait end of indexing @param objects the array of objects to save, each object must contain an objectID attribute @param request_options contains extra parameters to send with your query
[ "Override", "the", "content", "of", "several", "objects", "and", "wait", "end", "of", "indexing" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L330-L334
16,607
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.replace_all_objects
def replace_all_objects(objects, request_options = {}) safe = request_options[:safe] || request_options['safe'] || false request_options.delete(:safe) request_options.delete('safe') tmp_index = @client.init_index(@name + '_tmp_' + rand(10000000).to_s) responses = [] scope = ['settings', 'synonyms', 'rules'] res = @client.copy_index(@name, tmp_index.name, scope, request_options) responses << res if safe wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) end batch = [] batch_size = 1000 count = 0 objects.each do |object| batch << object count += 1 if count == batch_size res = tmp_index.add_objects(batch, request_options) responses << res batch = [] count = 0 end end if batch.any? res = tmp_index.add_objects(batch, request_options) responses << res end if safe responses.each do |res| tmp_index.wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) end end res = @client.move_index(tmp_index.name, @name, request_options) responses << res if safe wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) end responses end
ruby
def replace_all_objects(objects, request_options = {}) safe = request_options[:safe] || request_options['safe'] || false request_options.delete(:safe) request_options.delete('safe') tmp_index = @client.init_index(@name + '_tmp_' + rand(10000000).to_s) responses = [] scope = ['settings', 'synonyms', 'rules'] res = @client.copy_index(@name, tmp_index.name, scope, request_options) responses << res if safe wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) end batch = [] batch_size = 1000 count = 0 objects.each do |object| batch << object count += 1 if count == batch_size res = tmp_index.add_objects(batch, request_options) responses << res batch = [] count = 0 end end if batch.any? res = tmp_index.add_objects(batch, request_options) responses << res end if safe responses.each do |res| tmp_index.wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) end end res = @client.move_index(tmp_index.name, @name, request_options) responses << res if safe wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) end responses end
[ "def", "replace_all_objects", "(", "objects", ",", "request_options", "=", "{", "}", ")", "safe", "=", "request_options", "[", ":safe", "]", "||", "request_options", "[", "'safe'", "]", "||", "false", "request_options", ".", "delete", "(", ":safe", ")", "request_options", ".", "delete", "(", "'safe'", ")", "tmp_index", "=", "@client", ".", "init_index", "(", "@name", "+", "'_tmp_'", "+", "rand", "(", "10000000", ")", ".", "to_s", ")", "responses", "=", "[", "]", "scope", "=", "[", "'settings'", ",", "'synonyms'", ",", "'rules'", "]", "res", "=", "@client", ".", "copy_index", "(", "@name", ",", "tmp_index", ".", "name", ",", "scope", ",", "request_options", ")", "responses", "<<", "res", "if", "safe", "wait_task", "(", "res", "[", "'taskID'", "]", ",", "WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY", ",", "request_options", ")", "end", "batch", "=", "[", "]", "batch_size", "=", "1000", "count", "=", "0", "objects", ".", "each", "do", "|", "object", "|", "batch", "<<", "object", "count", "+=", "1", "if", "count", "==", "batch_size", "res", "=", "tmp_index", ".", "add_objects", "(", "batch", ",", "request_options", ")", "responses", "<<", "res", "batch", "=", "[", "]", "count", "=", "0", "end", "end", "if", "batch", ".", "any?", "res", "=", "tmp_index", ".", "add_objects", "(", "batch", ",", "request_options", ")", "responses", "<<", "res", "end", "if", "safe", "responses", ".", "each", "do", "|", "res", "|", "tmp_index", ".", "wait_task", "(", "res", "[", "'taskID'", "]", ",", "WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY", ",", "request_options", ")", "end", "end", "res", "=", "@client", ".", "move_index", "(", "tmp_index", ".", "name", ",", "@name", ",", "request_options", ")", "responses", "<<", "res", "if", "safe", "wait_task", "(", "res", "[", "'taskID'", "]", ",", "WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY", ",", "request_options", ")", "end", "responses", "end" ]
Override the current objects by the given array of objects and wait end of indexing. Settings, synonyms and query rules are untouched. The objects are replaced without any downtime. @param objects the array of objects to save @param request_options contains extra parameters to send with your query
[ "Override", "the", "current", "objects", "by", "the", "given", "array", "of", "objects", "and", "wait", "end", "of", "indexing", ".", "Settings", "synonyms", "and", "query", "rules", "are", "untouched", ".", "The", "objects", "are", "replaced", "without", "any", "downtime", "." ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L343-L394
16,608
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.partial_update_objects
def partial_update_objects(objects, create_if_not_exits = true, request_options = {}) if create_if_not_exits batch(build_batch('partialUpdateObject', objects, true), request_options) else batch(build_batch('partialUpdateObjectNoCreate', objects, true), request_options) end end
ruby
def partial_update_objects(objects, create_if_not_exits = true, request_options = {}) if create_if_not_exits batch(build_batch('partialUpdateObject', objects, true), request_options) else batch(build_batch('partialUpdateObjectNoCreate', objects, true), request_options) end end
[ "def", "partial_update_objects", "(", "objects", ",", "create_if_not_exits", "=", "true", ",", "request_options", "=", "{", "}", ")", "if", "create_if_not_exits", "batch", "(", "build_batch", "(", "'partialUpdateObject'", ",", "objects", ",", "true", ")", ",", "request_options", ")", "else", "batch", "(", "build_batch", "(", "'partialUpdateObjectNoCreate'", ",", "objects", ",", "true", ")", ",", "request_options", ")", "end", "end" ]
Partially override the content of several objects @param objects an array of objects to update (each object must contains a objectID attribute) @param create_if_not_exits a boolean, if true create the objects if they don't exist @param request_options contains extra parameters to send with your query
[ "Partially", "override", "the", "content", "of", "several", "objects" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L425-L431
16,609
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.partial_update_objects!
def partial_update_objects!(objects, create_if_not_exits = true, request_options = {}) res = partial_update_objects(objects, create_if_not_exits, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
ruby
def partial_update_objects!(objects, create_if_not_exits = true, request_options = {}) res = partial_update_objects(objects, create_if_not_exits, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
[ "def", "partial_update_objects!", "(", "objects", ",", "create_if_not_exits", "=", "true", ",", "request_options", "=", "{", "}", ")", "res", "=", "partial_update_objects", "(", "objects", ",", "create_if_not_exits", ",", "request_options", ")", "wait_task", "(", "res", "[", "'taskID'", "]", ",", "WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY", ",", "request_options", ")", "res", "end" ]
Partially override the content of several objects and wait end of indexing @param objects an array of objects to update (each object must contains a objectID attribute) @param create_if_not_exits a boolean, if true create the objects if they don't exist @param request_options contains extra parameters to send with your query
[ "Partially", "override", "the", "content", "of", "several", "objects", "and", "wait", "end", "of", "indexing" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L440-L444
16,610
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.delete_object
def delete_object(objectID, request_options = {}) raise ArgumentError.new('objectID must not be blank') if objectID.nil? || objectID == '' client.delete(Protocol.object_uri(name, objectID), :write, request_options) end
ruby
def delete_object(objectID, request_options = {}) raise ArgumentError.new('objectID must not be blank') if objectID.nil? || objectID == '' client.delete(Protocol.object_uri(name, objectID), :write, request_options) end
[ "def", "delete_object", "(", "objectID", ",", "request_options", "=", "{", "}", ")", "raise", "ArgumentError", ".", "new", "(", "'objectID must not be blank'", ")", "if", "objectID", ".", "nil?", "||", "objectID", "==", "''", "client", ".", "delete", "(", "Protocol", ".", "object_uri", "(", "name", ",", "objectID", ")", ",", ":write", ",", "request_options", ")", "end" ]
Delete an object from the index @param objectID the unique identifier of object to delete @param request_options contains extra parameters to send with your query
[ "Delete", "an", "object", "from", "the", "index" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L466-L469
16,611
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.delete_object!
def delete_object!(objectID, request_options = {}) res = delete_object(objectID, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
ruby
def delete_object!(objectID, request_options = {}) res = delete_object(objectID, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
[ "def", "delete_object!", "(", "objectID", ",", "request_options", "=", "{", "}", ")", "res", "=", "delete_object", "(", "objectID", ",", "request_options", ")", "wait_task", "(", "res", "[", "'taskID'", "]", ",", "WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY", ",", "request_options", ")", "res", "end" ]
Delete an object from the index and wait end of indexing @param objectID the unique identifier of object to delete @param request_options contains extra parameters to send with your query
[ "Delete", "an", "object", "from", "the", "index", "and", "wait", "end", "of", "indexing" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L477-L481
16,612
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.delete_objects
def delete_objects(objects, request_options = {}) check_array(objects) batch(build_batch('deleteObject', objects.map { |objectID| { :objectID => objectID } }, false), request_options) end
ruby
def delete_objects(objects, request_options = {}) check_array(objects) batch(build_batch('deleteObject', objects.map { |objectID| { :objectID => objectID } }, false), request_options) end
[ "def", "delete_objects", "(", "objects", ",", "request_options", "=", "{", "}", ")", "check_array", "(", "objects", ")", "batch", "(", "build_batch", "(", "'deleteObject'", ",", "objects", ".", "map", "{", "|", "objectID", "|", "{", ":objectID", "=>", "objectID", "}", "}", ",", "false", ")", ",", "request_options", ")", "end" ]
Delete several objects @param objects an array of objectIDs @param request_options contains extra parameters to send with your query
[ "Delete", "several", "objects" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L489-L492
16,613
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.delete_objects!
def delete_objects!(objects, request_options = {}) res = delete_objects(objects, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
ruby
def delete_objects!(objects, request_options = {}) res = delete_objects(objects, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
[ "def", "delete_objects!", "(", "objects", ",", "request_options", "=", "{", "}", ")", "res", "=", "delete_objects", "(", "objects", ",", "request_options", ")", "wait_task", "(", "res", "[", "'taskID'", "]", ",", "WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY", ",", "request_options", ")", "res", "end" ]
Delete several objects and wait end of indexing @param objects an array of objectIDs @param request_options contains extra parameters to send with your query
[ "Delete", "several", "objects", "and", "wait", "end", "of", "indexing" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L500-L504
16,614
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.delete_by_query
def delete_by_query(query, params = nil, request_options = {}) raise ArgumentError.new('query cannot be nil, use the `clear` method to wipe the entire index') if query.nil? && params.nil? params = sanitized_delete_by_query_params(params) params[:query] = query params[:hitsPerPage] = 1000 params[:distinct] = false params[:attributesToRetrieve] = ['objectID'] params[:cursor] = '' ids = [] while params[:cursor] != nil result = browse(params, nil, request_options) params[:cursor] = result['cursor'] hits = result['hits'] break if hits.empty? ids += hits.map { |hit| hit['objectID'] } end delete_objects(ids, request_options) end
ruby
def delete_by_query(query, params = nil, request_options = {}) raise ArgumentError.new('query cannot be nil, use the `clear` method to wipe the entire index') if query.nil? && params.nil? params = sanitized_delete_by_query_params(params) params[:query] = query params[:hitsPerPage] = 1000 params[:distinct] = false params[:attributesToRetrieve] = ['objectID'] params[:cursor] = '' ids = [] while params[:cursor] != nil result = browse(params, nil, request_options) params[:cursor] = result['cursor'] hits = result['hits'] break if hits.empty? ids += hits.map { |hit| hit['objectID'] } end delete_objects(ids, request_options) end
[ "def", "delete_by_query", "(", "query", ",", "params", "=", "nil", ",", "request_options", "=", "{", "}", ")", "raise", "ArgumentError", ".", "new", "(", "'query cannot be nil, use the `clear` method to wipe the entire index'", ")", "if", "query", ".", "nil?", "&&", "params", ".", "nil?", "params", "=", "sanitized_delete_by_query_params", "(", "params", ")", "params", "[", ":query", "]", "=", "query", "params", "[", ":hitsPerPage", "]", "=", "1000", "params", "[", ":distinct", "]", "=", "false", "params", "[", ":attributesToRetrieve", "]", "=", "[", "'objectID'", "]", "params", "[", ":cursor", "]", "=", "''", "ids", "=", "[", "]", "while", "params", "[", ":cursor", "]", "!=", "nil", "result", "=", "browse", "(", "params", ",", "nil", ",", "request_options", ")", "params", "[", ":cursor", "]", "=", "result", "[", "'cursor'", "]", "hits", "=", "result", "[", "'hits'", "]", "break", "if", "hits", ".", "empty?", "ids", "+=", "hits", ".", "map", "{", "|", "hit", "|", "hit", "[", "'objectID'", "]", "}", "end", "delete_objects", "(", "ids", ",", "request_options", ")", "end" ]
Delete all objects matching a query This method retrieves all objects synchronously but deletes in batch asynchronously @param query the query string @param params the optional query parameters @param request_options contains extra parameters to send with your query
[ "Delete", "all", "objects", "matching", "a", "query", "This", "method", "retrieves", "all", "objects", "synchronously", "but", "deletes", "in", "batch", "asynchronously" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L515-L538
16,615
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.delete_by_query!
def delete_by_query!(query, params = nil, request_options = {}) res = delete_by_query(query, params, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) if res res end
ruby
def delete_by_query!(query, params = nil, request_options = {}) res = delete_by_query(query, params, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) if res res end
[ "def", "delete_by_query!", "(", "query", ",", "params", "=", "nil", ",", "request_options", "=", "{", "}", ")", "res", "=", "delete_by_query", "(", "query", ",", "params", ",", "request_options", ")", "wait_task", "(", "res", "[", "'taskID'", "]", ",", "WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY", ",", "request_options", ")", "if", "res", "res", "end" ]
Delete all objects matching a query and wait end of indexing @param query the query string @param params the optional query parameters @param request_options contains extra parameters to send with your query
[ "Delete", "all", "objects", "matching", "a", "query", "and", "wait", "end", "of", "indexing" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L547-L551
16,616
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.clear!
def clear!(request_options = {}) res = clear(request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
ruby
def clear!(request_options = {}) res = clear(request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
[ "def", "clear!", "(", "request_options", "=", "{", "}", ")", "res", "=", "clear", "(", "request_options", ")", "wait_task", "(", "res", "[", "'taskID'", "]", ",", "WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY", ",", "request_options", ")", "res", "end" ]
Delete the index content and wait end of indexing
[ "Delete", "the", "index", "content", "and", "wait", "end", "of", "indexing" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L591-L595
16,617
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.set_settings
def set_settings(new_settings, options = {}, request_options = {}) client.put(Protocol.settings_uri(name, options), new_settings.to_json, :write, request_options) end
ruby
def set_settings(new_settings, options = {}, request_options = {}) client.put(Protocol.settings_uri(name, options), new_settings.to_json, :write, request_options) end
[ "def", "set_settings", "(", "new_settings", ",", "options", "=", "{", "}", ",", "request_options", "=", "{", "}", ")", "client", ".", "put", "(", "Protocol", ".", "settings_uri", "(", "name", ",", "options", ")", ",", "new_settings", ".", "to_json", ",", ":write", ",", "request_options", ")", "end" ]
Set settings for this index
[ "Set", "settings", "for", "this", "index" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L601-L603
16,618
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.set_settings!
def set_settings!(new_settings, options = {}, request_options = {}) res = set_settings(new_settings, options, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
ruby
def set_settings!(new_settings, options = {}, request_options = {}) res = set_settings(new_settings, options, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
[ "def", "set_settings!", "(", "new_settings", ",", "options", "=", "{", "}", ",", "request_options", "=", "{", "}", ")", "res", "=", "set_settings", "(", "new_settings", ",", "options", ",", "request_options", ")", "wait_task", "(", "res", "[", "'taskID'", "]", ",", "WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY", ",", "request_options", ")", "res", "end" ]
Set settings for this index and wait end of indexing
[ "Set", "settings", "for", "this", "index", "and", "wait", "end", "of", "indexing" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L608-L612
16,619
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.get_settings
def get_settings(options = {}, request_options = {}) options['getVersion'] = 2 if !options[:getVersion] && !options['getVersion'] client.get(Protocol.settings_uri(name, options).to_s, :read, request_options) end
ruby
def get_settings(options = {}, request_options = {}) options['getVersion'] = 2 if !options[:getVersion] && !options['getVersion'] client.get(Protocol.settings_uri(name, options).to_s, :read, request_options) end
[ "def", "get_settings", "(", "options", "=", "{", "}", ",", "request_options", "=", "{", "}", ")", "options", "[", "'getVersion'", "]", "=", "2", "if", "!", "options", "[", ":getVersion", "]", "&&", "!", "options", "[", "'getVersion'", "]", "client", ".", "get", "(", "Protocol", ".", "settings_uri", "(", "name", ",", "options", ")", ".", "to_s", ",", ":read", ",", "request_options", ")", "end" ]
Get settings of this index
[ "Get", "settings", "of", "this", "index" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L617-L620
16,620
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.get_api_key
def get_api_key(key, request_options = {}) client.get(Protocol.index_key_uri(name, key), :read, request_options) end
ruby
def get_api_key(key, request_options = {}) client.get(Protocol.index_key_uri(name, key), :read, request_options) end
[ "def", "get_api_key", "(", "key", ",", "request_options", "=", "{", "}", ")", "client", ".", "get", "(", "Protocol", ".", "index_key_uri", "(", "name", ",", "key", ")", ",", ":read", ",", "request_options", ")", "end" ]
Get ACL of a user key Deprecated: Please us `client.get_api_key` instead.
[ "Get", "ACL", "of", "a", "user", "key" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L634-L636
16,621
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.delete_api_key
def delete_api_key(key, request_options = {}) client.delete(Protocol.index_key_uri(name, key), :write, request_options) end
ruby
def delete_api_key(key, request_options = {}) client.delete(Protocol.index_key_uri(name, key), :write, request_options) end
[ "def", "delete_api_key", "(", "key", ",", "request_options", "=", "{", "}", ")", "client", ".", "delete", "(", "Protocol", ".", "index_key_uri", "(", "name", ",", "key", ")", ",", ":write", ",", "request_options", ")", "end" ]
Delete an existing user key Deprecated: Please use `client.delete_api_key` instead
[ "Delete", "an", "existing", "user", "key" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L723-L725
16,622
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.batch
def batch(request, request_options = {}) client.post(Protocol.batch_uri(name), request.to_json, :batch, request_options) end
ruby
def batch(request, request_options = {}) client.post(Protocol.batch_uri(name), request.to_json, :batch, request_options) end
[ "def", "batch", "(", "request", ",", "request_options", "=", "{", "}", ")", "client", ".", "post", "(", "Protocol", ".", "batch_uri", "(", "name", ")", ",", "request", ".", "to_json", ",", ":batch", ",", "request_options", ")", "end" ]
Send a batch request
[ "Send", "a", "batch", "request" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L730-L732
16,623
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.batch!
def batch!(request, request_options = {}) res = batch(request, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
ruby
def batch!(request, request_options = {}) res = batch(request, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
[ "def", "batch!", "(", "request", ",", "request_options", "=", "{", "}", ")", "res", "=", "batch", "(", "request", ",", "request_options", ")", "wait_task", "(", "res", "[", "'taskID'", "]", ",", "WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY", ",", "request_options", ")", "res", "end" ]
Send a batch request and wait the end of the indexing
[ "Send", "a", "batch", "request", "and", "wait", "the", "end", "of", "the", "indexing" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L737-L741
16,624
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.search_for_facet_values
def search_for_facet_values(facet_name, facet_query, search_parameters = {}, request_options = {}) params = search_parameters.clone params['facetQuery'] = facet_query client.post(Protocol.search_facet_uri(name, facet_name), params.to_json, :read, request_options) end
ruby
def search_for_facet_values(facet_name, facet_query, search_parameters = {}, request_options = {}) params = search_parameters.clone params['facetQuery'] = facet_query client.post(Protocol.search_facet_uri(name, facet_name), params.to_json, :read, request_options) end
[ "def", "search_for_facet_values", "(", "facet_name", ",", "facet_query", ",", "search_parameters", "=", "{", "}", ",", "request_options", "=", "{", "}", ")", "params", "=", "search_parameters", ".", "clone", "params", "[", "'facetQuery'", "]", "=", "facet_query", "client", ".", "post", "(", "Protocol", ".", "search_facet_uri", "(", "name", ",", "facet_name", ")", ",", "params", ".", "to_json", ",", ":read", ",", "request_options", ")", "end" ]
Search for facet values @param facet_name Name of the facet to search. It must have been declared in the index's`attributesForFaceting` setting with the `searchable()` modifier. @param facet_query Text to search for in the facet's values @param search_parameters An optional query to take extra search parameters into account. These parameters apply to index objects like in a regular search query. Only facet values contained in the matched objects will be returned. @param request_options contains extra parameters to send with your query
[ "Search", "for", "facet", "values" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L754-L758
16,625
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.search_disjunctive_faceting
def search_disjunctive_faceting(query, disjunctive_facets, params = {}, refinements = {}, request_options = {}) raise ArgumentError.new('Argument "disjunctive_facets" must be a String or an Array') unless disjunctive_facets.is_a?(String) || disjunctive_facets.is_a?(Array) raise ArgumentError.new('Argument "refinements" must be a Hash of Arrays') if !refinements.is_a?(Hash) || !refinements.select { |k, v| !v.is_a?(Array) }.empty? # extract disjunctive facets & associated refinements disjunctive_facets = disjunctive_facets.split(',') if disjunctive_facets.is_a?(String) disjunctive_refinements = {} refinements.each do |k, v| disjunctive_refinements[k] = v if disjunctive_facets.include?(k) || disjunctive_facets.include?(k.to_s) end # build queries queries = [] ## hits + regular facets query filters = [] refinements.to_a.each do |k, values| r = values.map { |v| "#{k}:#{v}" } if disjunctive_refinements[k.to_s] || disjunctive_refinements[k.to_sym] # disjunctive refinements are ORed filters << r else # regular refinements are ANDed filters += r end end queries << params.merge({ :index_name => self.name, :query => query, :facetFilters => filters }) ## one query per disjunctive facet (use all refinements but the current one + hitsPerPage=1 + single facet) disjunctive_facets.each do |disjunctive_facet| filters = [] refinements.each do |k, values| if k.to_s != disjunctive_facet.to_s r = values.map { |v| "#{k}:#{v}" } if disjunctive_refinements[k.to_s] || disjunctive_refinements[k.to_sym] # disjunctive refinements are ORed filters << r else # regular refinements are ANDed filters += r end end end queries << params.merge({ :index_name => self.name, :query => query, :page => 0, :hitsPerPage => 1, :attributesToRetrieve => [], :attributesToHighlight => [], :attributesToSnippet => [], :facets => disjunctive_facet, :facetFilters => filters, :analytics => false }) end answers = client.multiple_queries(queries, { :request_options => request_options }) # aggregate answers ## first answer stores the hits + regular facets aggregated_answer = answers['results'][0] ## others store the disjunctive facets aggregated_answer['disjunctiveFacets'] = {} answers['results'].each_with_index do |a, i| next if i == 0 a['facets'].each do |facet, values| ## add the facet to the disjunctive facet hash aggregated_answer['disjunctiveFacets'][facet] = values ## concatenate missing refinements (disjunctive_refinements[facet.to_s] || disjunctive_refinements[facet.to_sym] || []).each do |r| if aggregated_answer['disjunctiveFacets'][facet][r].nil? aggregated_answer['disjunctiveFacets'][facet][r] = 0 end end end end aggregated_answer end
ruby
def search_disjunctive_faceting(query, disjunctive_facets, params = {}, refinements = {}, request_options = {}) raise ArgumentError.new('Argument "disjunctive_facets" must be a String or an Array') unless disjunctive_facets.is_a?(String) || disjunctive_facets.is_a?(Array) raise ArgumentError.new('Argument "refinements" must be a Hash of Arrays') if !refinements.is_a?(Hash) || !refinements.select { |k, v| !v.is_a?(Array) }.empty? # extract disjunctive facets & associated refinements disjunctive_facets = disjunctive_facets.split(',') if disjunctive_facets.is_a?(String) disjunctive_refinements = {} refinements.each do |k, v| disjunctive_refinements[k] = v if disjunctive_facets.include?(k) || disjunctive_facets.include?(k.to_s) end # build queries queries = [] ## hits + regular facets query filters = [] refinements.to_a.each do |k, values| r = values.map { |v| "#{k}:#{v}" } if disjunctive_refinements[k.to_s] || disjunctive_refinements[k.to_sym] # disjunctive refinements are ORed filters << r else # regular refinements are ANDed filters += r end end queries << params.merge({ :index_name => self.name, :query => query, :facetFilters => filters }) ## one query per disjunctive facet (use all refinements but the current one + hitsPerPage=1 + single facet) disjunctive_facets.each do |disjunctive_facet| filters = [] refinements.each do |k, values| if k.to_s != disjunctive_facet.to_s r = values.map { |v| "#{k}:#{v}" } if disjunctive_refinements[k.to_s] || disjunctive_refinements[k.to_sym] # disjunctive refinements are ORed filters << r else # regular refinements are ANDed filters += r end end end queries << params.merge({ :index_name => self.name, :query => query, :page => 0, :hitsPerPage => 1, :attributesToRetrieve => [], :attributesToHighlight => [], :attributesToSnippet => [], :facets => disjunctive_facet, :facetFilters => filters, :analytics => false }) end answers = client.multiple_queries(queries, { :request_options => request_options }) # aggregate answers ## first answer stores the hits + regular facets aggregated_answer = answers['results'][0] ## others store the disjunctive facets aggregated_answer['disjunctiveFacets'] = {} answers['results'].each_with_index do |a, i| next if i == 0 a['facets'].each do |facet, values| ## add the facet to the disjunctive facet hash aggregated_answer['disjunctiveFacets'][facet] = values ## concatenate missing refinements (disjunctive_refinements[facet.to_s] || disjunctive_refinements[facet.to_sym] || []).each do |r| if aggregated_answer['disjunctiveFacets'][facet][r].nil? aggregated_answer['disjunctiveFacets'][facet][r] = 0 end end end end aggregated_answer end
[ "def", "search_disjunctive_faceting", "(", "query", ",", "disjunctive_facets", ",", "params", "=", "{", "}", ",", "refinements", "=", "{", "}", ",", "request_options", "=", "{", "}", ")", "raise", "ArgumentError", ".", "new", "(", "'Argument \"disjunctive_facets\" must be a String or an Array'", ")", "unless", "disjunctive_facets", ".", "is_a?", "(", "String", ")", "||", "disjunctive_facets", ".", "is_a?", "(", "Array", ")", "raise", "ArgumentError", ".", "new", "(", "'Argument \"refinements\" must be a Hash of Arrays'", ")", "if", "!", "refinements", ".", "is_a?", "(", "Hash", ")", "||", "!", "refinements", ".", "select", "{", "|", "k", ",", "v", "|", "!", "v", ".", "is_a?", "(", "Array", ")", "}", ".", "empty?", "# extract disjunctive facets & associated refinements", "disjunctive_facets", "=", "disjunctive_facets", ".", "split", "(", "','", ")", "if", "disjunctive_facets", ".", "is_a?", "(", "String", ")", "disjunctive_refinements", "=", "{", "}", "refinements", ".", "each", "do", "|", "k", ",", "v", "|", "disjunctive_refinements", "[", "k", "]", "=", "v", "if", "disjunctive_facets", ".", "include?", "(", "k", ")", "||", "disjunctive_facets", ".", "include?", "(", "k", ".", "to_s", ")", "end", "# build queries", "queries", "=", "[", "]", "## hits + regular facets query", "filters", "=", "[", "]", "refinements", ".", "to_a", ".", "each", "do", "|", "k", ",", "values", "|", "r", "=", "values", ".", "map", "{", "|", "v", "|", "\"#{k}:#{v}\"", "}", "if", "disjunctive_refinements", "[", "k", ".", "to_s", "]", "||", "disjunctive_refinements", "[", "k", ".", "to_sym", "]", "# disjunctive refinements are ORed", "filters", "<<", "r", "else", "# regular refinements are ANDed", "filters", "+=", "r", "end", "end", "queries", "<<", "params", ".", "merge", "(", "{", ":index_name", "=>", "self", ".", "name", ",", ":query", "=>", "query", ",", ":facetFilters", "=>", "filters", "}", ")", "## one query per disjunctive facet (use all refinements but the current one + hitsPerPage=1 + single facet)", "disjunctive_facets", ".", "each", "do", "|", "disjunctive_facet", "|", "filters", "=", "[", "]", "refinements", ".", "each", "do", "|", "k", ",", "values", "|", "if", "k", ".", "to_s", "!=", "disjunctive_facet", ".", "to_s", "r", "=", "values", ".", "map", "{", "|", "v", "|", "\"#{k}:#{v}\"", "}", "if", "disjunctive_refinements", "[", "k", ".", "to_s", "]", "||", "disjunctive_refinements", "[", "k", ".", "to_sym", "]", "# disjunctive refinements are ORed", "filters", "<<", "r", "else", "# regular refinements are ANDed", "filters", "+=", "r", "end", "end", "end", "queries", "<<", "params", ".", "merge", "(", "{", ":index_name", "=>", "self", ".", "name", ",", ":query", "=>", "query", ",", ":page", "=>", "0", ",", ":hitsPerPage", "=>", "1", ",", ":attributesToRetrieve", "=>", "[", "]", ",", ":attributesToHighlight", "=>", "[", "]", ",", ":attributesToSnippet", "=>", "[", "]", ",", ":facets", "=>", "disjunctive_facet", ",", ":facetFilters", "=>", "filters", ",", ":analytics", "=>", "false", "}", ")", "end", "answers", "=", "client", ".", "multiple_queries", "(", "queries", ",", "{", ":request_options", "=>", "request_options", "}", ")", "# aggregate answers", "## first answer stores the hits + regular facets", "aggregated_answer", "=", "answers", "[", "'results'", "]", "[", "0", "]", "## others store the disjunctive facets", "aggregated_answer", "[", "'disjunctiveFacets'", "]", "=", "{", "}", "answers", "[", "'results'", "]", ".", "each_with_index", "do", "|", "a", ",", "i", "|", "next", "if", "i", "==", "0", "a", "[", "'facets'", "]", ".", "each", "do", "|", "facet", ",", "values", "|", "## add the facet to the disjunctive facet hash", "aggregated_answer", "[", "'disjunctiveFacets'", "]", "[", "facet", "]", "=", "values", "## concatenate missing refinements", "(", "disjunctive_refinements", "[", "facet", ".", "to_s", "]", "||", "disjunctive_refinements", "[", "facet", ".", "to_sym", "]", "||", "[", "]", ")", ".", "each", "do", "|", "r", "|", "if", "aggregated_answer", "[", "'disjunctiveFacets'", "]", "[", "facet", "]", "[", "r", "]", ".", "nil?", "aggregated_answer", "[", "'disjunctiveFacets'", "]", "[", "facet", "]", "[", "r", "]", "=", "0", "end", "end", "end", "end", "aggregated_answer", "end" ]
Perform a search with disjunctive facets generating as many queries as number of disjunctive facets @param query the query @param disjunctive_facets the array of disjunctive facets @param params a hash representing the regular query parameters @param refinements a hash ("string" -> ["array", "of", "refined", "values"]) representing the current refinements ex: { "my_facet1" => ["my_value1", ["my_value2"], "my_disjunctive_facet1" => ["my_value1", "my_value2"] } @param request_options contains extra parameters to send with your query
[ "Perform", "a", "search", "with", "disjunctive", "facets", "generating", "as", "many", "queries", "as", "number", "of", "disjunctive", "facets" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L773-L849
16,626
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.get_synonym
def get_synonym(objectID, request_options = {}) client.get(Protocol.synonym_uri(name, objectID), :read, request_options) end
ruby
def get_synonym(objectID, request_options = {}) client.get(Protocol.synonym_uri(name, objectID), :read, request_options) end
[ "def", "get_synonym", "(", "objectID", ",", "request_options", "=", "{", "}", ")", "client", ".", "get", "(", "Protocol", ".", "synonym_uri", "(", "name", ",", "objectID", ")", ",", ":read", ",", "request_options", ")", "end" ]
Get a synonym @param objectID the synonym objectID @param request_options contains extra parameters to send with your query
[ "Get", "a", "synonym" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L886-L888
16,627
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.delete_synonym!
def delete_synonym!(objectID, forward_to_replicas = false, request_options = {}) res = delete_synonym(objectID, forward_to_replicas, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
ruby
def delete_synonym!(objectID, forward_to_replicas = false, request_options = {}) res = delete_synonym(objectID, forward_to_replicas, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
[ "def", "delete_synonym!", "(", "objectID", ",", "forward_to_replicas", "=", "false", ",", "request_options", "=", "{", "}", ")", "res", "=", "delete_synonym", "(", "objectID", ",", "forward_to_replicas", ",", "request_options", ")", "wait_task", "(", "res", "[", "'taskID'", "]", ",", "WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY", ",", "request_options", ")", "res", "end" ]
Delete a synonym and wait the end of indexing @param objectID the synonym objectID @param forward_to_replicas should we forward the delete to replica indices @param request_options contains extra parameters to send with your query
[ "Delete", "a", "synonym", "and", "wait", "the", "end", "of", "indexing" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L908-L912
16,628
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.save_synonym
def save_synonym(objectID, synonym, forward_to_replicas = false, request_options = {}) client.put("#{Protocol.synonym_uri(name, objectID)}?forwardToReplicas=#{forward_to_replicas}", synonym.to_json, :write, request_options) end
ruby
def save_synonym(objectID, synonym, forward_to_replicas = false, request_options = {}) client.put("#{Protocol.synonym_uri(name, objectID)}?forwardToReplicas=#{forward_to_replicas}", synonym.to_json, :write, request_options) end
[ "def", "save_synonym", "(", "objectID", ",", "synonym", ",", "forward_to_replicas", "=", "false", ",", "request_options", "=", "{", "}", ")", "client", ".", "put", "(", "\"#{Protocol.synonym_uri(name, objectID)}?forwardToReplicas=#{forward_to_replicas}\"", ",", "synonym", ".", "to_json", ",", ":write", ",", "request_options", ")", "end" ]
Save a synonym @param objectID the synonym objectID @param synonym the synonym @param forward_to_replicas should we forward the delete to replica indices @param request_options contains extra parameters to send with your query
[ "Save", "a", "synonym" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L922-L924
16,629
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.save_synonym!
def save_synonym!(objectID, synonym, forward_to_replicas = false, request_options = {}) res = save_synonym(objectID, synonym, forward_to_replicas, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
ruby
def save_synonym!(objectID, synonym, forward_to_replicas = false, request_options = {}) res = save_synonym(objectID, synonym, forward_to_replicas, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
[ "def", "save_synonym!", "(", "objectID", ",", "synonym", ",", "forward_to_replicas", "=", "false", ",", "request_options", "=", "{", "}", ")", "res", "=", "save_synonym", "(", "objectID", ",", "synonym", ",", "forward_to_replicas", ",", "request_options", ")", "wait_task", "(", "res", "[", "'taskID'", "]", ",", "WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY", ",", "request_options", ")", "res", "end" ]
Save a synonym and wait the end of indexing @param objectID the synonym objectID @param synonym the synonym @param forward_to_replicas should we forward the delete to replica indices @param request_options contains extra parameters to send with your query
[ "Save", "a", "synonym", "and", "wait", "the", "end", "of", "indexing" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L934-L938
16,630
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.clear_synonyms!
def clear_synonyms!(forward_to_replicas = false, request_options = {}) res = clear_synonyms(forward_to_replicas, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
ruby
def clear_synonyms!(forward_to_replicas = false, request_options = {}) res = clear_synonyms(forward_to_replicas, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
[ "def", "clear_synonyms!", "(", "forward_to_replicas", "=", "false", ",", "request_options", "=", "{", "}", ")", "res", "=", "clear_synonyms", "(", "forward_to_replicas", ",", "request_options", ")", "wait_task", "(", "res", "[", "'taskID'", "]", ",", "WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY", ",", "request_options", ")", "res", "end" ]
Clear all synonyms and wait the end of indexing @param forward_to_replicas should we forward the delete to replica indices @param request_options contains extra parameters to send with your query
[ "Clear", "all", "synonyms", "and", "wait", "the", "end", "of", "indexing" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L956-L960
16,631
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.replace_all_synonyms
def replace_all_synonyms(synonyms, request_options = {}) forward_to_replicas = request_options[:forwardToReplicas] || request_options['forwardToReplicas'] || false batch_synonyms(synonyms, forward_to_replicas, true, request_options) end
ruby
def replace_all_synonyms(synonyms, request_options = {}) forward_to_replicas = request_options[:forwardToReplicas] || request_options['forwardToReplicas'] || false batch_synonyms(synonyms, forward_to_replicas, true, request_options) end
[ "def", "replace_all_synonyms", "(", "synonyms", ",", "request_options", "=", "{", "}", ")", "forward_to_replicas", "=", "request_options", "[", ":forwardToReplicas", "]", "||", "request_options", "[", "'forwardToReplicas'", "]", "||", "false", "batch_synonyms", "(", "synonyms", ",", "forward_to_replicas", ",", "true", ",", "request_options", ")", "end" ]
Replace synonyms in the index by the given array of synonyms @param synonyms the array of synonyms to add @param request_options contains extra parameters to send with your query
[ "Replace", "synonyms", "in", "the", "index", "by", "the", "given", "array", "of", "synonyms" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L994-L997
16,632
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.replace_all_synonyms!
def replace_all_synonyms!(synonyms, request_options = {}) res = replace_all_synonyms(synonyms, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
ruby
def replace_all_synonyms!(synonyms, request_options = {}) res = replace_all_synonyms(synonyms, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
[ "def", "replace_all_synonyms!", "(", "synonyms", ",", "request_options", "=", "{", "}", ")", "res", "=", "replace_all_synonyms", "(", "synonyms", ",", "request_options", ")", "wait_task", "(", "res", "[", "'taskID'", "]", ",", "WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY", ",", "request_options", ")", "res", "end" ]
Replace synonyms in the index by the given array of synonyms and wait the end of indexing @param synonyms the array of synonyms to add @param request_options contains extra parameters to send with your query
[ "Replace", "synonyms", "in", "the", "index", "by", "the", "given", "array", "of", "synonyms", "and", "wait", "the", "end", "of", "indexing" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L1005-L1009
16,633
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.export_synonyms
def export_synonyms(hits_per_page = 100, request_options = {}, &_block) res = [] page = 0 loop do curr = search_synonyms('', { :hitsPerPage => hits_per_page, :page => page }, request_options)['hits'] curr.each do |synonym| res << synonym yield synonym if block_given? end break if curr.size < hits_per_page page += 1 end res end
ruby
def export_synonyms(hits_per_page = 100, request_options = {}, &_block) res = [] page = 0 loop do curr = search_synonyms('', { :hitsPerPage => hits_per_page, :page => page }, request_options)['hits'] curr.each do |synonym| res << synonym yield synonym if block_given? end break if curr.size < hits_per_page page += 1 end res end
[ "def", "export_synonyms", "(", "hits_per_page", "=", "100", ",", "request_options", "=", "{", "}", ",", "&", "_block", ")", "res", "=", "[", "]", "page", "=", "0", "loop", "do", "curr", "=", "search_synonyms", "(", "''", ",", "{", ":hitsPerPage", "=>", "hits_per_page", ",", ":page", "=>", "page", "}", ",", "request_options", ")", "[", "'hits'", "]", "curr", ".", "each", "do", "|", "synonym", "|", "res", "<<", "synonym", "yield", "synonym", "if", "block_given?", "end", "break", "if", "curr", ".", "size", "<", "hits_per_page", "page", "+=", "1", "end", "res", "end" ]
Export the full list of synonyms Accepts an optional block to which it will pass each synonym Also returns an array with all the synonyms @param hits_per_page Amount of synonyms to retrieve on each internal request - Optional - Default: 100 @param request_options contains extra parameters to send with your query - Optional
[ "Export", "the", "full", "list", "of", "synonyms", "Accepts", "an", "optional", "block", "to", "which", "it", "will", "pass", "each", "synonym", "Also", "returns", "an", "array", "with", "all", "the", "synonyms" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L1019-L1032
16,634
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.get_rule
def get_rule(objectID, request_options = {}) client.get(Protocol.rule_uri(name, objectID), :read, request_options) end
ruby
def get_rule(objectID, request_options = {}) client.get(Protocol.rule_uri(name, objectID), :read, request_options) end
[ "def", "get_rule", "(", "objectID", ",", "request_options", "=", "{", "}", ")", "client", ".", "get", "(", "Protocol", ".", "rule_uri", "(", "name", ",", "objectID", ")", ",", ":read", ",", "request_options", ")", "end" ]
Get a rule @param objectID the rule objectID @param request_options contains extra parameters to send with your query
[ "Get", "a", "rule" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L1062-L1064
16,635
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.delete_rule!
def delete_rule!(objectID, forward_to_replicas = false, request_options = {}) res = delete_rule(objectID, forward_to_replicas, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) return res end
ruby
def delete_rule!(objectID, forward_to_replicas = false, request_options = {}) res = delete_rule(objectID, forward_to_replicas, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) return res end
[ "def", "delete_rule!", "(", "objectID", ",", "forward_to_replicas", "=", "false", ",", "request_options", "=", "{", "}", ")", "res", "=", "delete_rule", "(", "objectID", ",", "forward_to_replicas", ",", "request_options", ")", "wait_task", "(", "res", "[", "'taskID'", "]", ",", "WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY", ",", "request_options", ")", "return", "res", "end" ]
Delete a rule and wait the end of indexing @param objectID the rule objectID @param forward_to_replicas should we forward the delete to replica indices @param request_options contains extra parameters to send with your query
[ "Delete", "a", "rule", "and", "wait", "the", "end", "of", "indexing" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L1084-L1088
16,636
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.save_rule
def save_rule(objectID, rule, forward_to_replicas = false, request_options = {}) raise ArgumentError.new('objectID must not be blank') if objectID.nil? || objectID == '' client.put("#{Protocol.rule_uri(name, objectID)}?forwardToReplicas=#{forward_to_replicas}", rule.to_json, :write, request_options) end
ruby
def save_rule(objectID, rule, forward_to_replicas = false, request_options = {}) raise ArgumentError.new('objectID must not be blank') if objectID.nil? || objectID == '' client.put("#{Protocol.rule_uri(name, objectID)}?forwardToReplicas=#{forward_to_replicas}", rule.to_json, :write, request_options) end
[ "def", "save_rule", "(", "objectID", ",", "rule", ",", "forward_to_replicas", "=", "false", ",", "request_options", "=", "{", "}", ")", "raise", "ArgumentError", ".", "new", "(", "'objectID must not be blank'", ")", "if", "objectID", ".", "nil?", "||", "objectID", "==", "''", "client", ".", "put", "(", "\"#{Protocol.rule_uri(name, objectID)}?forwardToReplicas=#{forward_to_replicas}\"", ",", "rule", ".", "to_json", ",", ":write", ",", "request_options", ")", "end" ]
Save a rule @param objectID the rule objectID @param rule the rule @param forward_to_replicas should we forward the delete to replica indices @param request_options contains extra parameters to send with your query
[ "Save", "a", "rule" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L1098-L1101
16,637
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.save_rule!
def save_rule!(objectID, rule, forward_to_replicas = false, request_options = {}) res = save_rule(objectID, rule, forward_to_replicas, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) return res end
ruby
def save_rule!(objectID, rule, forward_to_replicas = false, request_options = {}) res = save_rule(objectID, rule, forward_to_replicas, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) return res end
[ "def", "save_rule!", "(", "objectID", ",", "rule", ",", "forward_to_replicas", "=", "false", ",", "request_options", "=", "{", "}", ")", "res", "=", "save_rule", "(", "objectID", ",", "rule", ",", "forward_to_replicas", ",", "request_options", ")", "wait_task", "(", "res", "[", "'taskID'", "]", ",", "WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY", ",", "request_options", ")", "return", "res", "end" ]
Save a rule and wait the end of indexing @param objectID the rule objectID @param rule the rule @param forward_to_replicas should we forward the delete to replica indices @param request_options contains extra parameters to send with your query
[ "Save", "a", "rule", "and", "wait", "the", "end", "of", "indexing" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L1111-L1115
16,638
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.clear_rules!
def clear_rules!(forward_to_replicas = false, request_options = {}) res = clear_rules(forward_to_replicas, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) return res end
ruby
def clear_rules!(forward_to_replicas = false, request_options = {}) res = clear_rules(forward_to_replicas, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) return res end
[ "def", "clear_rules!", "(", "forward_to_replicas", "=", "false", ",", "request_options", "=", "{", "}", ")", "res", "=", "clear_rules", "(", "forward_to_replicas", ",", "request_options", ")", "wait_task", "(", "res", "[", "'taskID'", "]", ",", "WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY", ",", "request_options", ")", "return", "res", "end" ]
Clear all rules and wait the end of indexing @param forward_to_replicas should we forward the delete to replica indices @param request_options contains extra parameters to send with your query
[ "Clear", "all", "rules", "and", "wait", "the", "end", "of", "indexing" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L1133-L1137
16,639
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.replace_all_rules
def replace_all_rules(rules, request_options = {}) forward_to_replicas = request_options[:forwardToReplicas] || request_options['forwardToReplicas'] || false batch_rules(rules, forward_to_replicas, true, request_options) end
ruby
def replace_all_rules(rules, request_options = {}) forward_to_replicas = request_options[:forwardToReplicas] || request_options['forwardToReplicas'] || false batch_rules(rules, forward_to_replicas, true, request_options) end
[ "def", "replace_all_rules", "(", "rules", ",", "request_options", "=", "{", "}", ")", "forward_to_replicas", "=", "request_options", "[", ":forwardToReplicas", "]", "||", "request_options", "[", "'forwardToReplicas'", "]", "||", "false", "batch_rules", "(", "rules", ",", "forward_to_replicas", ",", "true", ",", "request_options", ")", "end" ]
Replace rules in the index by the given array of rules @param rules the array of rules to add @param request_options contains extra parameters to send with your query
[ "Replace", "rules", "in", "the", "index", "by", "the", "given", "array", "of", "rules" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L1171-L1174
16,640
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.replace_all_rules!
def replace_all_rules!(rules, request_options = {}) res = replace_all_rules(rules, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
ruby
def replace_all_rules!(rules, request_options = {}) res = replace_all_rules(rules, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
[ "def", "replace_all_rules!", "(", "rules", ",", "request_options", "=", "{", "}", ")", "res", "=", "replace_all_rules", "(", "rules", ",", "request_options", ")", "wait_task", "(", "res", "[", "'taskID'", "]", ",", "WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY", ",", "request_options", ")", "res", "end" ]
Replace rules in the index by the given array of rules and wait the end of indexing @param rules the array of rules to add @param request_options contains extra parameters to send with your query
[ "Replace", "rules", "in", "the", "index", "by", "the", "given", "array", "of", "rules", "and", "wait", "the", "end", "of", "indexing" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L1182-L1186
16,641
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.export_rules
def export_rules(hits_per_page = 100, request_options = {}, &_block) res = [] page = 0 loop do curr = search_rules('', { :hits_per_page => hits_per_page, :page => page }, request_options)['hits'] curr.each do |rule| res << rule yield rule if block_given? end break if curr.size < hits_per_page page += 1 end res end
ruby
def export_rules(hits_per_page = 100, request_options = {}, &_block) res = [] page = 0 loop do curr = search_rules('', { :hits_per_page => hits_per_page, :page => page }, request_options)['hits'] curr.each do |rule| res << rule yield rule if block_given? end break if curr.size < hits_per_page page += 1 end res end
[ "def", "export_rules", "(", "hits_per_page", "=", "100", ",", "request_options", "=", "{", "}", ",", "&", "_block", ")", "res", "=", "[", "]", "page", "=", "0", "loop", "do", "curr", "=", "search_rules", "(", "''", ",", "{", ":hits_per_page", "=>", "hits_per_page", ",", ":page", "=>", "page", "}", ",", "request_options", ")", "[", "'hits'", "]", "curr", ".", "each", "do", "|", "rule", "|", "res", "<<", "rule", "yield", "rule", "if", "block_given?", "end", "break", "if", "curr", ".", "size", "<", "hits_per_page", "page", "+=", "1", "end", "res", "end" ]
Export the full list of rules Accepts an optional block to which it will pass each rule Also returns an array with all the rules @param hits_per_page Amount of rules to retrieve on each internal request - Optional - Default: 100 @param request_options contains extra parameters to send with your query - Optional
[ "Export", "the", "full", "list", "of", "rules", "Accepts", "an", "optional", "block", "to", "which", "it", "will", "pass", "each", "rule", "Also", "returns", "an", "array", "with", "all", "the", "rules" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L1196-L1209
16,642
goco-inc/graphql-activerecord
lib/graphql/models/attribute_loader.rb
GraphQL::Models.AttributeLoader.hash_to_condition
def hash_to_condition(table, hash) conditions = hash.map do |attr, value| if value.is_a?(Array) && value.size > 1 table[attr].in(value) elsif value.is_a?(Array) table[attr].eq(value[0]) else table[attr].eq(value) end end conditions.reduce { |memo, cond| memo.and(cond) } end
ruby
def hash_to_condition(table, hash) conditions = hash.map do |attr, value| if value.is_a?(Array) && value.size > 1 table[attr].in(value) elsif value.is_a?(Array) table[attr].eq(value[0]) else table[attr].eq(value) end end conditions.reduce { |memo, cond| memo.and(cond) } end
[ "def", "hash_to_condition", "(", "table", ",", "hash", ")", "conditions", "=", "hash", ".", "map", "do", "|", "attr", ",", "value", "|", "if", "value", ".", "is_a?", "(", "Array", ")", "&&", "value", ".", "size", ">", "1", "table", "[", "attr", "]", ".", "in", "(", "value", ")", "elsif", "value", ".", "is_a?", "(", "Array", ")", "table", "[", "attr", "]", ".", "eq", "(", "value", "[", "0", "]", ")", "else", "table", "[", "attr", "]", ".", "eq", "(", "value", ")", "end", "end", "conditions", ".", "reduce", "{", "|", "memo", ",", "cond", "|", "memo", ".", "and", "(", "cond", ")", "}", "end" ]
Converts a hash into arel conditions
[ "Converts", "a", "hash", "into", "arel", "conditions" ]
2567f558fda3f7dadafe62b845e18cc307c9dd34
https://github.com/goco-inc/graphql-activerecord/blob/2567f558fda3f7dadafe62b845e18cc307c9dd34/lib/graphql/models/attribute_loader.rb#L71-L83
16,643
activerecord-hackery/squeel
lib/squeel/dsl.rb
Squeel.DSL.method_missing
def method_missing(method_id, *args) super if method_id == :to_ary if args.empty? Nodes::Stub.new method_id elsif (args.size == 1) && (Class === args[0]) Nodes::Join.new(method_id, InnerJoin, args[0]) else Nodes::Function.new method_id, args end end
ruby
def method_missing(method_id, *args) super if method_id == :to_ary if args.empty? Nodes::Stub.new method_id elsif (args.size == 1) && (Class === args[0]) Nodes::Join.new(method_id, InnerJoin, args[0]) else Nodes::Function.new method_id, args end end
[ "def", "method_missing", "(", "method_id", ",", "*", "args", ")", "super", "if", "method_id", "==", ":to_ary", "if", "args", ".", "empty?", "Nodes", "::", "Stub", ".", "new", "method_id", "elsif", "(", "args", ".", "size", "==", "1", ")", "&&", "(", "Class", "===", "args", "[", "0", "]", ")", "Nodes", "::", "Join", ".", "new", "(", "method_id", ",", "InnerJoin", ",", "args", "[", "0", "]", ")", "else", "Nodes", "::", "Function", ".", "new", "method_id", ",", "args", "end", "end" ]
Node generation inside DSL blocks. @overload node_name Creates a Stub. Method calls chained from this Stub will determine what type of node we eventually end up with. @return [Nodes::Stub] A stub with the name of the method @overload node_name(klass) Creates a Join with a polymorphic class matching the given parameter @param [Class] klass The polymorphic class of the join node @return [Nodes::Join] A join node with the name of the method and the given class @overload node_name(first_arg, *other_args) Creates a Function with the given arguments becoming the function's arguments @param first_arg The first argument @param *other_args Optional additional arguments @return [Nodes::Function] A function node for the given method name with the given arguments
[ "Node", "generation", "inside", "DSL", "blocks", "." ]
5542266d502db8022e14105f9dfb455a79d6fc4a
https://github.com/activerecord-hackery/squeel/blob/5542266d502db8022e14105f9dfb455a79d6fc4a/lib/squeel/dsl.rb#L107-L117
16,644
markevans/dragonfly
lib/dragonfly/job.rb
Dragonfly.Job.initialize_copy
def initialize_copy(other) @steps = other.steps.map do |step| step.class.new(self, *step.args) end @content = other.content.dup @url_attributes = other.url_attributes.dup end
ruby
def initialize_copy(other) @steps = other.steps.map do |step| step.class.new(self, *step.args) end @content = other.content.dup @url_attributes = other.url_attributes.dup end
[ "def", "initialize_copy", "(", "other", ")", "@steps", "=", "other", ".", "steps", ".", "map", "do", "|", "step", "|", "step", ".", "class", ".", "new", "(", "self", ",", "step", ".", "args", ")", "end", "@content", "=", "other", ".", "content", ".", "dup", "@url_attributes", "=", "other", ".", "url_attributes", ".", "dup", "end" ]
Used by 'dup' and 'clone'
[ "Used", "by", "dup", "and", "clone" ]
2516f24557dc32c4ab147db7c878c5be3f5e57f0
https://github.com/markevans/dragonfly/blob/2516f24557dc32c4ab147db7c878c5be3f5e57f0/lib/dragonfly/job.rb#L90-L96
16,645
markevans/dragonfly
lib/dragonfly/content.rb
Dragonfly.Content.update
def update(obj, meta=nil) meta ||= {} self.temp_object = TempObject.new(obj, meta['name']) self.meta['name'] ||= temp_object.name if temp_object.name clear_analyser_cache add_meta(obj.meta) if obj.respond_to?(:meta) add_meta(meta) self end
ruby
def update(obj, meta=nil) meta ||= {} self.temp_object = TempObject.new(obj, meta['name']) self.meta['name'] ||= temp_object.name if temp_object.name clear_analyser_cache add_meta(obj.meta) if obj.respond_to?(:meta) add_meta(meta) self end
[ "def", "update", "(", "obj", ",", "meta", "=", "nil", ")", "meta", "||=", "{", "}", "self", ".", "temp_object", "=", "TempObject", ".", "new", "(", "obj", ",", "meta", "[", "'name'", "]", ")", "self", ".", "meta", "[", "'name'", "]", "||=", "temp_object", ".", "name", "if", "temp_object", ".", "name", "clear_analyser_cache", "add_meta", "(", "obj", ".", "meta", ")", "if", "obj", ".", "respond_to?", "(", ":meta", ")", "add_meta", "(", "meta", ")", "self", "end" ]
Update the content @param obj [String, Pathname, Tempfile, File, Content, TempObject] can be any of these types @param meta [Hash] - should be json-like, i.e. contain no types other than String, Number, Boolean @return [Content] self
[ "Update", "the", "content" ]
2516f24557dc32c4ab147db7c878c5be3f5e57f0
https://github.com/markevans/dragonfly/blob/2516f24557dc32c4ab147db7c878c5be3f5e57f0/lib/dragonfly/content.rb#L114-L122
16,646
markevans/dragonfly
lib/dragonfly/content.rb
Dragonfly.Content.shell_eval
def shell_eval(opts={}) should_escape = opts[:escape] != false command = yield(should_escape ? shell.escape(path) : path) run command, :escape => should_escape end
ruby
def shell_eval(opts={}) should_escape = opts[:escape] != false command = yield(should_escape ? shell.escape(path) : path) run command, :escape => should_escape end
[ "def", "shell_eval", "(", "opts", "=", "{", "}", ")", "should_escape", "=", "opts", "[", ":escape", "]", "!=", "false", "command", "=", "yield", "(", "should_escape", "?", "shell", ".", "escape", "(", "path", ")", ":", "path", ")", "run", "command", ",", ":escape", "=>", "should_escape", "end" ]
Analyse the content using a shell command @param opts [Hash] passing :escape => false doesn't shell-escape each word @example content.shell_eval do |path| "file --mime-type #{path}" end # ===> "beach.jpg: image/jpeg"
[ "Analyse", "the", "content", "using", "a", "shell", "command" ]
2516f24557dc32c4ab147db7c878c5be3f5e57f0
https://github.com/markevans/dragonfly/blob/2516f24557dc32c4ab147db7c878c5be3f5e57f0/lib/dragonfly/content.rb#L138-L142
16,647
markevans/dragonfly
lib/dragonfly/content.rb
Dragonfly.Content.shell_generate
def shell_generate(opts={}) ext = opts[:ext] || self.ext should_escape = opts[:escape] != false tempfile = Utils.new_tempfile(ext) new_path = should_escape ? shell.escape(tempfile.path) : tempfile.path command = yield(new_path) run(command, :escape => should_escape) update(tempfile) end
ruby
def shell_generate(opts={}) ext = opts[:ext] || self.ext should_escape = opts[:escape] != false tempfile = Utils.new_tempfile(ext) new_path = should_escape ? shell.escape(tempfile.path) : tempfile.path command = yield(new_path) run(command, :escape => should_escape) update(tempfile) end
[ "def", "shell_generate", "(", "opts", "=", "{", "}", ")", "ext", "=", "opts", "[", ":ext", "]", "||", "self", ".", "ext", "should_escape", "=", "opts", "[", ":escape", "]", "!=", "false", "tempfile", "=", "Utils", ".", "new_tempfile", "(", "ext", ")", "new_path", "=", "should_escape", "?", "shell", ".", "escape", "(", "tempfile", ".", "path", ")", ":", "tempfile", ".", "path", "command", "=", "yield", "(", "new_path", ")", "run", "(", "command", ",", ":escape", "=>", "should_escape", ")", "update", "(", "tempfile", ")", "end" ]
Set the content using a shell command @param opts [Hash] :ext sets the file extension of the new path and :escape => false doesn't shell-escape each word @example content.shell_generate do |path| "/usr/local/bin/generate_text gumfry -o #{path}" end @return [Content] self
[ "Set", "the", "content", "using", "a", "shell", "command" ]
2516f24557dc32c4ab147db7c878c5be3f5e57f0
https://github.com/markevans/dragonfly/blob/2516f24557dc32c4ab147db7c878c5be3f5e57f0/lib/dragonfly/content.rb#L151-L159
16,648
dwbutler/logstash-logger
lib/logstash-logger/multi_logger.rb
LogStashLogger.MultiLogger.method_missing
def method_missing(name, *args, &block) @loggers.each do |logger| if logger.respond_to?(name) logger.send(name, args, &block) end end end
ruby
def method_missing(name, *args, &block) @loggers.each do |logger| if logger.respond_to?(name) logger.send(name, args, &block) end end end
[ "def", "method_missing", "(", "name", ",", "*", "args", ",", "&", "block", ")", "@loggers", ".", "each", "do", "|", "logger", "|", "if", "logger", ".", "respond_to?", "(", "name", ")", "logger", ".", "send", "(", "name", ",", "args", ",", "block", ")", "end", "end", "end" ]
Any method not defined on standard Logger class, just send it on to anyone who will listen
[ "Any", "method", "not", "defined", "on", "standard", "Logger", "class", "just", "send", "it", "on", "to", "anyone", "who", "will", "listen" ]
b8f5403c44150f10d15b01133f8b6d1e9eb31806
https://github.com/dwbutler/logstash-logger/blob/b8f5403c44150f10d15b01133f8b6d1e9eb31806/lib/logstash-logger/multi_logger.rb#L70-L76
16,649
dwbutler/logstash-logger
lib/logstash-logger/buffer.rb
LogStashLogger.Buffer.buffer_initialize
def buffer_initialize(options={}) if ! self.class.method_defined?(:flush) raise ArgumentError, "Any class including Stud::Buffer must define a flush() method." end @buffer_config = { :max_items => options[:max_items] || 50, :max_interval => options[:max_interval] || 5, :logger => options[:logger] || nil, :autoflush => options.fetch(:autoflush, true), :has_on_flush_error => self.class.method_defined?(:on_flush_error), :has_on_full_buffer_receive => self.class.method_defined?(:on_full_buffer_receive), :drop_messages_on_flush_error => options.fetch(:drop_messages_on_flush_error, false), :drop_messages_on_full_buffer => options.fetch(:drop_messages_on_full_buffer, false), :flush_at_exit => options.fetch(:flush_at_exit, false) } if @buffer_config[:flush_at_exit] at_exit { buffer_flush(final: true) } end reset_buffer end
ruby
def buffer_initialize(options={}) if ! self.class.method_defined?(:flush) raise ArgumentError, "Any class including Stud::Buffer must define a flush() method." end @buffer_config = { :max_items => options[:max_items] || 50, :max_interval => options[:max_interval] || 5, :logger => options[:logger] || nil, :autoflush => options.fetch(:autoflush, true), :has_on_flush_error => self.class.method_defined?(:on_flush_error), :has_on_full_buffer_receive => self.class.method_defined?(:on_full_buffer_receive), :drop_messages_on_flush_error => options.fetch(:drop_messages_on_flush_error, false), :drop_messages_on_full_buffer => options.fetch(:drop_messages_on_full_buffer, false), :flush_at_exit => options.fetch(:flush_at_exit, false) } if @buffer_config[:flush_at_exit] at_exit { buffer_flush(final: true) } end reset_buffer end
[ "def", "buffer_initialize", "(", "options", "=", "{", "}", ")", "if", "!", "self", ".", "class", ".", "method_defined?", "(", ":flush", ")", "raise", "ArgumentError", ",", "\"Any class including Stud::Buffer must define a flush() method.\"", "end", "@buffer_config", "=", "{", ":max_items", "=>", "options", "[", ":max_items", "]", "||", "50", ",", ":max_interval", "=>", "options", "[", ":max_interval", "]", "||", "5", ",", ":logger", "=>", "options", "[", ":logger", "]", "||", "nil", ",", ":autoflush", "=>", "options", ".", "fetch", "(", ":autoflush", ",", "true", ")", ",", ":has_on_flush_error", "=>", "self", ".", "class", ".", "method_defined?", "(", ":on_flush_error", ")", ",", ":has_on_full_buffer_receive", "=>", "self", ".", "class", ".", "method_defined?", "(", ":on_full_buffer_receive", ")", ",", ":drop_messages_on_flush_error", "=>", "options", ".", "fetch", "(", ":drop_messages_on_flush_error", ",", "false", ")", ",", ":drop_messages_on_full_buffer", "=>", "options", ".", "fetch", "(", ":drop_messages_on_full_buffer", ",", "false", ")", ",", ":flush_at_exit", "=>", "options", ".", "fetch", "(", ":flush_at_exit", ",", "false", ")", "}", "if", "@buffer_config", "[", ":flush_at_exit", "]", "at_exit", "{", "buffer_flush", "(", "final", ":", "true", ")", "}", "end", "reset_buffer", "end" ]
Initialize the buffer. Call directly from your constructor if you wish to set some non-default options. Otherwise buffer_initialize will be called automatically during the first buffer_receive call. Options: * :max_items, Max number of items to buffer before flushing. Default 50. * :max_interval, Max number of seconds to wait between flushes. Default 5. * :logger, A logger to write log messages to. No default. Optional. * :autoflush, Whether to immediately flush all inbound messages. Default true. * :drop_messages_on_flush_error, Whether to drop messages when there is a flush error. Default false. * :drop_messages_on_full_buffer, Whether to drop messages when the buffer is full. Default false. @param [Hash] options
[ "Initialize", "the", "buffer", "." ]
b8f5403c44150f10d15b01133f8b6d1e9eb31806
https://github.com/dwbutler/logstash-logger/blob/b8f5403c44150f10d15b01133f8b6d1e9eb31806/lib/logstash-logger/buffer.rb#L85-L107
16,650
dwbutler/logstash-logger
lib/logstash-logger/buffer.rb
LogStashLogger.Buffer.buffer_receive
def buffer_receive(event, group=nil) buffer_initialize if ! @buffer_state # block if we've accumulated too many events while buffer_full? do on_full_buffer_receive( :pending => @buffer_state[:pending_count], :outgoing => @buffer_state[:outgoing_count] ) if @buffer_config[:has_on_full_buffer_receive] if @buffer_config[:drop_messages_on_full_buffer] reset_buffer else sleep 0.1 end end @buffer_state[:pending_mutex].synchronize do @buffer_state[:pending_items][group] << event @buffer_state[:pending_count] += 1 end if @buffer_config[:autoflush] buffer_flush(force: true) end end
ruby
def buffer_receive(event, group=nil) buffer_initialize if ! @buffer_state # block if we've accumulated too many events while buffer_full? do on_full_buffer_receive( :pending => @buffer_state[:pending_count], :outgoing => @buffer_state[:outgoing_count] ) if @buffer_config[:has_on_full_buffer_receive] if @buffer_config[:drop_messages_on_full_buffer] reset_buffer else sleep 0.1 end end @buffer_state[:pending_mutex].synchronize do @buffer_state[:pending_items][group] << event @buffer_state[:pending_count] += 1 end if @buffer_config[:autoflush] buffer_flush(force: true) end end
[ "def", "buffer_receive", "(", "event", ",", "group", "=", "nil", ")", "buffer_initialize", "if", "!", "@buffer_state", "# block if we've accumulated too many events", "while", "buffer_full?", "do", "on_full_buffer_receive", "(", ":pending", "=>", "@buffer_state", "[", ":pending_count", "]", ",", ":outgoing", "=>", "@buffer_state", "[", ":outgoing_count", "]", ")", "if", "@buffer_config", "[", ":has_on_full_buffer_receive", "]", "if", "@buffer_config", "[", ":drop_messages_on_full_buffer", "]", "reset_buffer", "else", "sleep", "0.1", "end", "end", "@buffer_state", "[", ":pending_mutex", "]", ".", "synchronize", "do", "@buffer_state", "[", ":pending_items", "]", "[", "group", "]", "<<", "event", "@buffer_state", "[", ":pending_count", "]", "+=", "1", "end", "if", "@buffer_config", "[", ":autoflush", "]", "buffer_flush", "(", "force", ":", "true", ")", "end", "end" ]
Save an event for later delivery Events are grouped by the (optional) group parameter you provide. Groups of events, plus the group name, are later passed to +flush+. This call will block if +:max_items+ has been reached. @see Stud::Buffer The overview has more information on grouping and flushing. @param event An item to buffer for flushing later. @param group Optional grouping key. All events with the same key will be passed to +flush+ together, along with the grouping key itself.
[ "Save", "an", "event", "for", "later", "delivery" ]
b8f5403c44150f10d15b01133f8b6d1e9eb31806
https://github.com/dwbutler/logstash-logger/blob/b8f5403c44150f10d15b01133f8b6d1e9eb31806/lib/logstash-logger/buffer.rb#L157-L182
16,651
dwbutler/logstash-logger
lib/logstash-logger/buffer.rb
LogStashLogger.Buffer.buffer_flush
def buffer_flush(options={}) force = options[:force] || options[:final] final = options[:final] # final flush will wait for lock, so we are sure to flush out all buffered events if options[:final] @buffer_state[:flush_mutex].lock elsif ! @buffer_state[:flush_mutex].try_lock # failed to get lock, another flush already in progress return 0 end items_flushed = 0 begin time_since_last_flush = (Time.now - @buffer_state[:last_flush]) return 0 if @buffer_state[:pending_count] == 0 return 0 if (!force) && (@buffer_state[:pending_count] < @buffer_config[:max_items]) && (time_since_last_flush < @buffer_config[:max_interval]) @buffer_state[:pending_mutex].synchronize do @buffer_state[:outgoing_items] = @buffer_state[:pending_items] @buffer_state[:outgoing_count] = @buffer_state[:pending_count] buffer_clear_pending end @buffer_config[:logger].debug do debug_output = { :outgoing_count => @buffer_state[:outgoing_count], :time_since_last_flush => time_since_last_flush, :outgoing_events => @buffer_state[:outgoing_items], :batch_timeout => @buffer_config[:max_interval], :force => force, :final => final } "Flushing output: #{debug_output}" end if @buffer_config[:logger] @buffer_state[:outgoing_items].each do |group, events| begin if group.nil? flush(events,final) else flush(events, group, final) end @buffer_state[:outgoing_items].delete(group) events_size = events.size @buffer_state[:outgoing_count] -= events_size items_flushed += events_size @buffer_state[:last_flush] = Time.now rescue => e @buffer_config[:logger].warn do warn_output = { :outgoing_count => @buffer_state[:outgoing_count], :exception => e.class.name, :backtrace => e.backtrace } "Failed to flush outgoing items: #{warn_output}" end if @buffer_config[:logger] if @buffer_config[:has_on_flush_error] on_flush_error e end if @buffer_config[:drop_messages_on_flush_error] reset_buffer else cancel_flush end end end ensure @buffer_state[:flush_mutex].unlock end return items_flushed end
ruby
def buffer_flush(options={}) force = options[:force] || options[:final] final = options[:final] # final flush will wait for lock, so we are sure to flush out all buffered events if options[:final] @buffer_state[:flush_mutex].lock elsif ! @buffer_state[:flush_mutex].try_lock # failed to get lock, another flush already in progress return 0 end items_flushed = 0 begin time_since_last_flush = (Time.now - @buffer_state[:last_flush]) return 0 if @buffer_state[:pending_count] == 0 return 0 if (!force) && (@buffer_state[:pending_count] < @buffer_config[:max_items]) && (time_since_last_flush < @buffer_config[:max_interval]) @buffer_state[:pending_mutex].synchronize do @buffer_state[:outgoing_items] = @buffer_state[:pending_items] @buffer_state[:outgoing_count] = @buffer_state[:pending_count] buffer_clear_pending end @buffer_config[:logger].debug do debug_output = { :outgoing_count => @buffer_state[:outgoing_count], :time_since_last_flush => time_since_last_flush, :outgoing_events => @buffer_state[:outgoing_items], :batch_timeout => @buffer_config[:max_interval], :force => force, :final => final } "Flushing output: #{debug_output}" end if @buffer_config[:logger] @buffer_state[:outgoing_items].each do |group, events| begin if group.nil? flush(events,final) else flush(events, group, final) end @buffer_state[:outgoing_items].delete(group) events_size = events.size @buffer_state[:outgoing_count] -= events_size items_flushed += events_size @buffer_state[:last_flush] = Time.now rescue => e @buffer_config[:logger].warn do warn_output = { :outgoing_count => @buffer_state[:outgoing_count], :exception => e.class.name, :backtrace => e.backtrace } "Failed to flush outgoing items: #{warn_output}" end if @buffer_config[:logger] if @buffer_config[:has_on_flush_error] on_flush_error e end if @buffer_config[:drop_messages_on_flush_error] reset_buffer else cancel_flush end end end ensure @buffer_state[:flush_mutex].unlock end return items_flushed end
[ "def", "buffer_flush", "(", "options", "=", "{", "}", ")", "force", "=", "options", "[", ":force", "]", "||", "options", "[", ":final", "]", "final", "=", "options", "[", ":final", "]", "# final flush will wait for lock, so we are sure to flush out all buffered events", "if", "options", "[", ":final", "]", "@buffer_state", "[", ":flush_mutex", "]", ".", "lock", "elsif", "!", "@buffer_state", "[", ":flush_mutex", "]", ".", "try_lock", "# failed to get lock, another flush already in progress", "return", "0", "end", "items_flushed", "=", "0", "begin", "time_since_last_flush", "=", "(", "Time", ".", "now", "-", "@buffer_state", "[", ":last_flush", "]", ")", "return", "0", "if", "@buffer_state", "[", ":pending_count", "]", "==", "0", "return", "0", "if", "(", "!", "force", ")", "&&", "(", "@buffer_state", "[", ":pending_count", "]", "<", "@buffer_config", "[", ":max_items", "]", ")", "&&", "(", "time_since_last_flush", "<", "@buffer_config", "[", ":max_interval", "]", ")", "@buffer_state", "[", ":pending_mutex", "]", ".", "synchronize", "do", "@buffer_state", "[", ":outgoing_items", "]", "=", "@buffer_state", "[", ":pending_items", "]", "@buffer_state", "[", ":outgoing_count", "]", "=", "@buffer_state", "[", ":pending_count", "]", "buffer_clear_pending", "end", "@buffer_config", "[", ":logger", "]", ".", "debug", "do", "debug_output", "=", "{", ":outgoing_count", "=>", "@buffer_state", "[", ":outgoing_count", "]", ",", ":time_since_last_flush", "=>", "time_since_last_flush", ",", ":outgoing_events", "=>", "@buffer_state", "[", ":outgoing_items", "]", ",", ":batch_timeout", "=>", "@buffer_config", "[", ":max_interval", "]", ",", ":force", "=>", "force", ",", ":final", "=>", "final", "}", "\"Flushing output: #{debug_output}\"", "end", "if", "@buffer_config", "[", ":logger", "]", "@buffer_state", "[", ":outgoing_items", "]", ".", "each", "do", "|", "group", ",", "events", "|", "begin", "if", "group", ".", "nil?", "flush", "(", "events", ",", "final", ")", "else", "flush", "(", "events", ",", "group", ",", "final", ")", "end", "@buffer_state", "[", ":outgoing_items", "]", ".", "delete", "(", "group", ")", "events_size", "=", "events", ".", "size", "@buffer_state", "[", ":outgoing_count", "]", "-=", "events_size", "items_flushed", "+=", "events_size", "@buffer_state", "[", ":last_flush", "]", "=", "Time", ".", "now", "rescue", "=>", "e", "@buffer_config", "[", ":logger", "]", ".", "warn", "do", "warn_output", "=", "{", ":outgoing_count", "=>", "@buffer_state", "[", ":outgoing_count", "]", ",", ":exception", "=>", "e", ".", "class", ".", "name", ",", ":backtrace", "=>", "e", ".", "backtrace", "}", "\"Failed to flush outgoing items: #{warn_output}\"", "end", "if", "@buffer_config", "[", ":logger", "]", "if", "@buffer_config", "[", ":has_on_flush_error", "]", "on_flush_error", "e", "end", "if", "@buffer_config", "[", ":drop_messages_on_flush_error", "]", "reset_buffer", "else", "cancel_flush", "end", "end", "end", "ensure", "@buffer_state", "[", ":flush_mutex", "]", ".", "unlock", "end", "return", "items_flushed", "end" ]
Try to flush events. Returns immediately if flushing is not necessary/possible at the moment: * :max_items have not been accumulated * :max_interval seconds have not elapased since the last flush * another flush is in progress <code>buffer_flush(:force => true)</code> will cause a flush to occur even if +:max_items+ or +:max_interval+ have not been reached. A forced flush will still return immediately (without flushing) if another flush is currently in progress. <code>buffer_flush(:final => true)</code> is identical to <code>buffer_flush(:force => true)</code>, except that if another flush is already in progress, <code>buffer_flush(:final => true)</code> will block/wait for the other flush to finish before proceeding. @param [Hash] options Optional. May be <code>{:force => true}</code> or <code>{:final => true}</code>. @return [Fixnum] The number of items successfully passed to +flush+.
[ "Try", "to", "flush", "events", "." ]
b8f5403c44150f10d15b01133f8b6d1e9eb31806
https://github.com/dwbutler/logstash-logger/blob/b8f5403c44150f10d15b01133f8b6d1e9eb31806/lib/logstash-logger/buffer.rb#L202-L284
16,652
dkubb/axiom
lib/axiom/relation.rb
Axiom.Relation.each
def each return to_enum unless block_given? seen = {} tuples.each do |tuple| tuple = Tuple.coerce(header, tuple) yield seen[tuple] = tuple unless seen.key?(tuple) end self end
ruby
def each return to_enum unless block_given? seen = {} tuples.each do |tuple| tuple = Tuple.coerce(header, tuple) yield seen[tuple] = tuple unless seen.key?(tuple) end self end
[ "def", "each", "return", "to_enum", "unless", "block_given?", "seen", "=", "{", "}", "tuples", ".", "each", "do", "|", "tuple", "|", "tuple", "=", "Tuple", ".", "coerce", "(", "header", ",", "tuple", ")", "yield", "seen", "[", "tuple", "]", "=", "tuple", "unless", "seen", ".", "key?", "(", "tuple", ")", "end", "self", "end" ]
Iterate over each tuple in the set @example relation = Relation.new(header, tuples) relation.each { |tuple| ... } @yield [tuple] @yieldparam [Tuple] tuple each tuple in the set @return [self] @api public
[ "Iterate", "over", "each", "tuple", "in", "the", "set" ]
2476a75ed04d8a86d7a4dd30b306bac7fe2e8edc
https://github.com/dkubb/axiom/blob/2476a75ed04d8a86d7a4dd30b306bac7fe2e8edc/lib/axiom/relation.rb#L120-L128
16,653
dkubb/axiom
lib/axiom/relation.rb
Axiom.Relation.replace
def replace(other) other = coerce(other) delete(difference(other)).insert(other.difference(self)) end
ruby
def replace(other) other = coerce(other) delete(difference(other)).insert(other.difference(self)) end
[ "def", "replace", "(", "other", ")", "other", "=", "coerce", "(", "other", ")", "delete", "(", "difference", "(", "other", ")", ")", ".", "insert", "(", "other", ".", "difference", "(", "self", ")", ")", "end" ]
Return a relation that represents a replacement of a relation Delete the tuples from the relation that are not in the other relation, then insert only new tuples. @example replacement = relation.delete(other) @param [Enumerable] other @return [Relation::Operation::Insertion] @api public
[ "Return", "a", "relation", "that", "represents", "a", "replacement", "of", "a", "relation" ]
2476a75ed04d8a86d7a4dd30b306bac7fe2e8edc
https://github.com/dkubb/axiom/blob/2476a75ed04d8a86d7a4dd30b306bac7fe2e8edc/lib/axiom/relation.rb#L143-L146
16,654
dkubb/axiom
lib/axiom/support/aliasable.rb
Axiom.Aliasable.define_inheritable_alias_method
def define_inheritable_alias_method(new_method, original_method) define_method(new_method) do |*args, &block| public_send(original_method, *args, &block) end end
ruby
def define_inheritable_alias_method(new_method, original_method) define_method(new_method) do |*args, &block| public_send(original_method, *args, &block) end end
[ "def", "define_inheritable_alias_method", "(", "new_method", ",", "original_method", ")", "define_method", "(", "new_method", ")", "do", "|", "*", "args", ",", "&", "block", "|", "public_send", "(", "original_method", ",", "args", ",", "block", ")", "end", "end" ]
Create a new method alias for the original method @param [Symbol] new_method @param [Symbol] original_method @return [undefined] @api private
[ "Create", "a", "new", "method", "alias", "for", "the", "original", "method" ]
2476a75ed04d8a86d7a4dd30b306bac7fe2e8edc
https://github.com/dkubb/axiom/blob/2476a75ed04d8a86d7a4dd30b306bac7fe2e8edc/lib/axiom/support/aliasable.rb#L35-L39
16,655
dkubb/axiom
lib/axiom/tuple.rb
Axiom.Tuple.extend
def extend(header, extensions) join( header, extensions.map { |extension| Function.extract_value(extension, self) } ) end
ruby
def extend(header, extensions) join( header, extensions.map { |extension| Function.extract_value(extension, self) } ) end
[ "def", "extend", "(", "header", ",", "extensions", ")", "join", "(", "header", ",", "extensions", ".", "map", "{", "|", "extension", "|", "Function", ".", "extract_value", "(", "extension", ",", "self", ")", "}", ")", "end" ]
Extend a tuple with function results @example new_tuple = tuple.extend(header, [func1, func2]) @param [Header] header the attributes to include in the tuple @param [Array<Object>] extensions the functions to extend the tuple with @return [Tuple] @api public
[ "Extend", "a", "tuple", "with", "function", "results" ]
2476a75ed04d8a86d7a4dd30b306bac7fe2e8edc
https://github.com/dkubb/axiom/blob/2476a75ed04d8a86d7a4dd30b306bac7fe2e8edc/lib/axiom/tuple.rb#L94-L99
16,656
dkubb/axiom
lib/axiom/tuple.rb
Axiom.Tuple.predicate
def predicate header.reduce(Function::Proposition::Tautology.instance) do |predicate, attribute| predicate.and(attribute.eq(attribute.call(self))) end end
ruby
def predicate header.reduce(Function::Proposition::Tautology.instance) do |predicate, attribute| predicate.and(attribute.eq(attribute.call(self))) end end
[ "def", "predicate", "header", ".", "reduce", "(", "Function", "::", "Proposition", "::", "Tautology", ".", "instance", ")", "do", "|", "predicate", ",", "attribute", "|", "predicate", ".", "and", "(", "attribute", ".", "eq", "(", "attribute", ".", "call", "(", "self", ")", ")", ")", "end", "end" ]
Return the predicate matching the tuple @return [Function] @api private
[ "Return", "the", "predicate", "matching", "the", "tuple" ]
2476a75ed04d8a86d7a4dd30b306bac7fe2e8edc
https://github.com/dkubb/axiom/blob/2476a75ed04d8a86d7a4dd30b306bac7fe2e8edc/lib/axiom/tuple.rb#L137-L141
16,657
jasonlong/geo_pattern
lib/geo_pattern/geo_pattern_task.rb
GeoPattern.GeoPatternTask.run_task
def run_task(_verbose) data.each do |path, string| opts = {} path = File.expand_path(path) if string.is_a?(Hash) input = string[:input] opts[:patterns] = string[:patterns] if string.key? :patterns opts[:color] = string[:color] if string.key? :color opts[:base_color] = string[:base_color] if string.key? :base_color else raise 'Invalid data structure for Rake Task' end pattern = GeoPattern.generate(input, opts) logger.info "Creating pattern at \"#{path}\"." FileUtils.mkdir_p File.dirname(path) File.write(path, pattern.to_svg) end end
ruby
def run_task(_verbose) data.each do |path, string| opts = {} path = File.expand_path(path) if string.is_a?(Hash) input = string[:input] opts[:patterns] = string[:patterns] if string.key? :patterns opts[:color] = string[:color] if string.key? :color opts[:base_color] = string[:base_color] if string.key? :base_color else raise 'Invalid data structure for Rake Task' end pattern = GeoPattern.generate(input, opts) logger.info "Creating pattern at \"#{path}\"." FileUtils.mkdir_p File.dirname(path) File.write(path, pattern.to_svg) end end
[ "def", "run_task", "(", "_verbose", ")", "data", ".", "each", "do", "|", "path", ",", "string", "|", "opts", "=", "{", "}", "path", "=", "File", ".", "expand_path", "(", "path", ")", "if", "string", ".", "is_a?", "(", "Hash", ")", "input", "=", "string", "[", ":input", "]", "opts", "[", ":patterns", "]", "=", "string", "[", ":patterns", "]", "if", "string", ".", "key?", ":patterns", "opts", "[", ":color", "]", "=", "string", "[", ":color", "]", "if", "string", ".", "key?", ":color", "opts", "[", ":base_color", "]", "=", "string", "[", ":base_color", "]", "if", "string", ".", "key?", ":base_color", "else", "raise", "'Invalid data structure for Rake Task'", "end", "pattern", "=", "GeoPattern", ".", "generate", "(", "input", ",", "opts", ")", "logger", ".", "info", "\"Creating pattern at \\\"#{path}\\\".\"", "FileUtils", ".", "mkdir_p", "File", ".", "dirname", "(", "path", ")", "File", ".", "write", "(", "path", ",", "pattern", ".", "to_svg", ")", "end", "end" ]
Create a new geo pattern task @param [Hash] data The data which should be used to generate patterns @param [Array] allowed_patterns The allowed_patterns @see RakeTask For other arguments accepted @private
[ "Create", "a", "new", "geo", "pattern", "task" ]
62d3222c7394f0f02ab7f4705219d616c5a72b7e
https://github.com/jasonlong/geo_pattern/blob/62d3222c7394f0f02ab7f4705219d616c5a72b7e/lib/geo_pattern/geo_pattern_task.rb#L37-L57
16,658
jasonlong/geo_pattern
lib/geo_pattern/rake_task.rb
GeoPattern.RakeTask.include
def include(modules) modules = Array(modules) modules.each { |m| self.class.include m } end
ruby
def include(modules) modules = Array(modules) modules.each { |m| self.class.include m } end
[ "def", "include", "(", "modules", ")", "modules", "=", "Array", "(", "modules", ")", "modules", ".", "each", "{", "|", "m", "|", "self", ".", "class", ".", "include", "m", "}", "end" ]
Include module in instance
[ "Include", "module", "in", "instance" ]
62d3222c7394f0f02ab7f4705219d616c5a72b7e
https://github.com/jasonlong/geo_pattern/blob/62d3222c7394f0f02ab7f4705219d616c5a72b7e/lib/geo_pattern/rake_task.rb#L101-L105
16,659
kontena/kontena
cli/lib/kontena/cli/master/login_command.rb
Kontena::Cli::Master.LoginCommand.authentication_path
def authentication_path(local_port: nil, invite_code: nil, expires_in: nil, remote: false) auth_url_params = {} if remote auth_url_params[:redirect_uri] = "/code" elsif local_port auth_url_params[:redirect_uri] = "http://localhost:#{local_port}/cb" else raise ArgumentError, "Local port not defined and not performing remote login" end auth_url_params[:invite_code] = invite_code if invite_code auth_url_params[:expires_in] = expires_in if expires_in "/authenticate?#{URI.encode_www_form(auth_url_params)}" end
ruby
def authentication_path(local_port: nil, invite_code: nil, expires_in: nil, remote: false) auth_url_params = {} if remote auth_url_params[:redirect_uri] = "/code" elsif local_port auth_url_params[:redirect_uri] = "http://localhost:#{local_port}/cb" else raise ArgumentError, "Local port not defined and not performing remote login" end auth_url_params[:invite_code] = invite_code if invite_code auth_url_params[:expires_in] = expires_in if expires_in "/authenticate?#{URI.encode_www_form(auth_url_params)}" end
[ "def", "authentication_path", "(", "local_port", ":", "nil", ",", "invite_code", ":", "nil", ",", "expires_in", ":", "nil", ",", "remote", ":", "false", ")", "auth_url_params", "=", "{", "}", "if", "remote", "auth_url_params", "[", ":redirect_uri", "]", "=", "\"/code\"", "elsif", "local_port", "auth_url_params", "[", ":redirect_uri", "]", "=", "\"http://localhost:#{local_port}/cb\"", "else", "raise", "ArgumentError", ",", "\"Local port not defined and not performing remote login\"", "end", "auth_url_params", "[", ":invite_code", "]", "=", "invite_code", "if", "invite_code", "auth_url_params", "[", ":expires_in", "]", "=", "expires_in", "if", "expires_in", "\"/authenticate?#{URI.encode_www_form(auth_url_params)}\"", "end" ]
Build a path for master authentication @param local_port [Fixnum] tcp port where localhost webserver is listening @param invite_code [String] an invitation code generated when user was invited @param expires_in [Fixnum] expiration time for the requested access token @param remote [Boolean] true when performing a login where the code is displayed on the web page @return [String]
[ "Build", "a", "path", "for", "master", "authentication" ]
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/cli/master/login_command.rb#L126-L138
16,660
kontena/kontena
cli/lib/kontena/cli/master/login_command.rb
Kontena::Cli::Master.LoginCommand.authentication_url_from_master
def authentication_url_from_master(master_url, auth_params) client = Kontena::Client.new(master_url) vspinner "Sending authentication request to receive an authorization URL" do response = client.request( http_method: :get, path: authentication_path(auth_params), expects: [501, 400, 302, 403], auth: false ) if client.last_response.status == 302 client.last_response.headers['Location'] elsif response.kind_of?(Hash) exit_with_error [response['error'], response['error_description']].compact.join(' : ') elsif response.kind_of?(String) && response.length > 1 exit_with_error response else exit_with_error "Invalid response to authentication request : HTTP#{client.last_response.status} #{client.last_response.body if debug?}" end end end
ruby
def authentication_url_from_master(master_url, auth_params) client = Kontena::Client.new(master_url) vspinner "Sending authentication request to receive an authorization URL" do response = client.request( http_method: :get, path: authentication_path(auth_params), expects: [501, 400, 302, 403], auth: false ) if client.last_response.status == 302 client.last_response.headers['Location'] elsif response.kind_of?(Hash) exit_with_error [response['error'], response['error_description']].compact.join(' : ') elsif response.kind_of?(String) && response.length > 1 exit_with_error response else exit_with_error "Invalid response to authentication request : HTTP#{client.last_response.status} #{client.last_response.body if debug?}" end end end
[ "def", "authentication_url_from_master", "(", "master_url", ",", "auth_params", ")", "client", "=", "Kontena", "::", "Client", ".", "new", "(", "master_url", ")", "vspinner", "\"Sending authentication request to receive an authorization URL\"", "do", "response", "=", "client", ".", "request", "(", "http_method", ":", ":get", ",", "path", ":", "authentication_path", "(", "auth_params", ")", ",", "expects", ":", "[", "501", ",", "400", ",", "302", ",", "403", "]", ",", "auth", ":", "false", ")", "if", "client", ".", "last_response", ".", "status", "==", "302", "client", ".", "last_response", ".", "headers", "[", "'Location'", "]", "elsif", "response", ".", "kind_of?", "(", "Hash", ")", "exit_with_error", "[", "response", "[", "'error'", "]", ",", "response", "[", "'error_description'", "]", "]", ".", "compact", ".", "join", "(", "' : '", ")", "elsif", "response", ".", "kind_of?", "(", "String", ")", "&&", "response", ".", "length", ">", "1", "exit_with_error", "response", "else", "exit_with_error", "\"Invalid response to authentication request : HTTP#{client.last_response.status} #{client.last_response.body if debug?}\"", "end", "end", "end" ]
Request a redirect to the authentication url from master @param master_url [String] master root url @param auth_params [Hash] auth parameters (keyword arguments of #authentication_path) @return [String] url to begin authentication web flow
[ "Request", "a", "redirect", "to", "the", "authentication", "url", "from", "master" ]
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/cli/master/login_command.rb#L145-L165
16,661
kontena/kontena
cli/lib/kontena/cli/master/login_command.rb
Kontena::Cli::Master.LoginCommand.select_a_server
def select_a_server(name, url) # no url, no name, try to use current master if url.nil? && name.nil? if config.current_master return config.current_master else exit_with_error 'URL not specified and current master not selected' end end if name && url exact_match = config.find_server_by(url: url, name: name) return exact_match if exact_match # found an exact match, going to use that one. name_match = config.find_server(name) if name_match #found a server with the provided name, set the provided url to it and return name_match.url = url return name_match else # nothing found, create new. return Kontena::Cli::Config::Server.new(name: name, url: url) end elsif name # only --name provided, try to find a server with that name name_match = config.find_server(name) if name_match && name_match.url return name_match else exit_with_error "Master #{name} was found from config, but it does not have an URL and no URL was provided on command line" end elsif url # only url provided if url =~ /^https?:\/\// # url is actually an url url_match = config.find_server_by(url: url) if url_match return url_match else return Kontena::Cli::Config::Server.new(url: url, name: nil) end else name_match = config.find_server(url) if name_match unless name_match.url exit_with_error "Master #{url} was found from config, but it does not have an URL and no URL was provided on command line" end return name_match else exit_with_error "Can't find a master with name #{name} from configuration" end end end end
ruby
def select_a_server(name, url) # no url, no name, try to use current master if url.nil? && name.nil? if config.current_master return config.current_master else exit_with_error 'URL not specified and current master not selected' end end if name && url exact_match = config.find_server_by(url: url, name: name) return exact_match if exact_match # found an exact match, going to use that one. name_match = config.find_server(name) if name_match #found a server with the provided name, set the provided url to it and return name_match.url = url return name_match else # nothing found, create new. return Kontena::Cli::Config::Server.new(name: name, url: url) end elsif name # only --name provided, try to find a server with that name name_match = config.find_server(name) if name_match && name_match.url return name_match else exit_with_error "Master #{name} was found from config, but it does not have an URL and no URL was provided on command line" end elsif url # only url provided if url =~ /^https?:\/\// # url is actually an url url_match = config.find_server_by(url: url) if url_match return url_match else return Kontena::Cli::Config::Server.new(url: url, name: nil) end else name_match = config.find_server(url) if name_match unless name_match.url exit_with_error "Master #{url} was found from config, but it does not have an URL and no URL was provided on command line" end return name_match else exit_with_error "Can't find a master with name #{name} from configuration" end end end end
[ "def", "select_a_server", "(", "name", ",", "url", ")", "# no url, no name, try to use current master", "if", "url", ".", "nil?", "&&", "name", ".", "nil?", "if", "config", ".", "current_master", "return", "config", ".", "current_master", "else", "exit_with_error", "'URL not specified and current master not selected'", "end", "end", "if", "name", "&&", "url", "exact_match", "=", "config", ".", "find_server_by", "(", "url", ":", "url", ",", "name", ":", "name", ")", "return", "exact_match", "if", "exact_match", "# found an exact match, going to use that one.", "name_match", "=", "config", ".", "find_server", "(", "name", ")", "if", "name_match", "#found a server with the provided name, set the provided url to it and return", "name_match", ".", "url", "=", "url", "return", "name_match", "else", "# nothing found, create new.", "return", "Kontena", "::", "Cli", "::", "Config", "::", "Server", ".", "new", "(", "name", ":", "name", ",", "url", ":", "url", ")", "end", "elsif", "name", "# only --name provided, try to find a server with that name", "name_match", "=", "config", ".", "find_server", "(", "name", ")", "if", "name_match", "&&", "name_match", ".", "url", "return", "name_match", "else", "exit_with_error", "\"Master #{name} was found from config, but it does not have an URL and no URL was provided on command line\"", "end", "elsif", "url", "# only url provided", "if", "url", "=~", "/", "\\/", "\\/", "/", "# url is actually an url", "url_match", "=", "config", ".", "find_server_by", "(", "url", ":", "url", ")", "if", "url_match", "return", "url_match", "else", "return", "Kontena", "::", "Cli", "::", "Config", "::", "Server", ".", "new", "(", "url", ":", "url", ",", "name", ":", "nil", ")", "end", "else", "name_match", "=", "config", ".", "find_server", "(", "url", ")", "if", "name_match", "unless", "name_match", ".", "url", "exit_with_error", "\"Master #{url} was found from config, but it does not have an URL and no URL was provided on command line\"", "end", "return", "name_match", "else", "exit_with_error", "\"Can't find a master with name #{name} from configuration\"", "end", "end", "end", "end" ]
Figure out or create a server based on url or name. No name or url provided: try to use current_master A name provided with --name but no url defined: try to find a server by name from config An URL starting with 'http' provided: try to find a server by url from config An URL not starting with 'http' provided: try to find a server by name An URL and a name provided - If a server is found by name: use entry and update URL to the provided url - Else create a new entry with the url and name @param name [String] master name @param url [String] master url or name @return [Kontena::Cli::Config::Server]
[ "Figure", "out", "or", "create", "a", "server", "based", "on", "url", "or", "name", "." ]
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/cli/master/login_command.rb#L273-L328
16,662
kontena/kontena
agent/lib/kontena/network_adapters/weave.rb
Kontena::NetworkAdapters.Weave.ensure_exposed
def ensure_exposed(cidr) # configure new address # these will be added alongside any existing addresses if @executor_pool.expose(cidr) info "Exposed host node at cidr=#{cidr}" else error "Failed to expose host node at cidr=#{cidr}" end # cleanup any old addresses @executor_pool.ps('weave:expose') do |name, mac, *cidrs| cidrs.each do |exposed_cidr| if exposed_cidr != cidr warn "Migrating host node from cidr=#{exposed_cidr}" @executor_pool.hide(exposed_cidr) end end end end
ruby
def ensure_exposed(cidr) # configure new address # these will be added alongside any existing addresses if @executor_pool.expose(cidr) info "Exposed host node at cidr=#{cidr}" else error "Failed to expose host node at cidr=#{cidr}" end # cleanup any old addresses @executor_pool.ps('weave:expose') do |name, mac, *cidrs| cidrs.each do |exposed_cidr| if exposed_cidr != cidr warn "Migrating host node from cidr=#{exposed_cidr}" @executor_pool.hide(exposed_cidr) end end end end
[ "def", "ensure_exposed", "(", "cidr", ")", "# configure new address", "# these will be added alongside any existing addresses", "if", "@executor_pool", ".", "expose", "(", "cidr", ")", "info", "\"Exposed host node at cidr=#{cidr}\"", "else", "error", "\"Failed to expose host node at cidr=#{cidr}\"", "end", "# cleanup any old addresses", "@executor_pool", ".", "ps", "(", "'weave:expose'", ")", "do", "|", "name", ",", "mac", ",", "*", "cidrs", "|", "cidrs", ".", "each", "do", "|", "exposed_cidr", "|", "if", "exposed_cidr", "!=", "cidr", "warn", "\"Migrating host node from cidr=#{exposed_cidr}\"", "@executor_pool", ".", "hide", "(", "exposed_cidr", ")", "end", "end", "end", "end" ]
Ensure that the host weave bridge is exposed using the given CIDR address, and only the given CIDR address @param [String] cidr '10.81.0.X/16'
[ "Ensure", "that", "the", "host", "weave", "bridge", "is", "exposed", "using", "the", "given", "CIDR", "address", "and", "only", "the", "given", "CIDR", "address" ]
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/network_adapters/weave.rb#L162-L180
16,663
kontena/kontena
agent/lib/kontena/network_adapters/weave.rb
Kontena::NetworkAdapters.Weave.get_containers
def get_containers containers = { } @executor_pool.ps() do |id, mac, *cidrs| next if id == 'weave:expose' containers[id] = cidrs end containers end
ruby
def get_containers containers = { } @executor_pool.ps() do |id, mac, *cidrs| next if id == 'weave:expose' containers[id] = cidrs end containers end
[ "def", "get_containers", "containers", "=", "{", "}", "@executor_pool", ".", "ps", "(", ")", "do", "|", "id", ",", "mac", ",", "*", "cidrs", "|", "next", "if", "id", "==", "'weave:expose'", "containers", "[", "id", "]", "=", "cidrs", "end", "containers", "end" ]
Inspect current state of attached containers @return [Hash<String, String>] container_id[0..12] => [overlay_cidr]
[ "Inspect", "current", "state", "of", "attached", "containers" ]
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/network_adapters/weave.rb#L285-L295
16,664
kontena/kontena
agent/lib/kontena/network_adapters/weave.rb
Kontena::NetworkAdapters.Weave.migrate_container
def migrate_container(container_id, cidr, attached_cidrs) # first remove any existing addresses # this is required, since weave will not attach if the address already exists, but with a different netmask attached_cidrs.each do |attached_cidr| if cidr != attached_cidr warn "Migrate container=#{container_id} from cidr=#{attached_cidr}" @executor_pool.detach(container_id, attached_cidr) end end # attach with the correct address self.attach_container(container_id, cidr) end
ruby
def migrate_container(container_id, cidr, attached_cidrs) # first remove any existing addresses # this is required, since weave will not attach if the address already exists, but with a different netmask attached_cidrs.each do |attached_cidr| if cidr != attached_cidr warn "Migrate container=#{container_id} from cidr=#{attached_cidr}" @executor_pool.detach(container_id, attached_cidr) end end # attach with the correct address self.attach_container(container_id, cidr) end
[ "def", "migrate_container", "(", "container_id", ",", "cidr", ",", "attached_cidrs", ")", "# first remove any existing addresses", "# this is required, since weave will not attach if the address already exists, but with a different netmask", "attached_cidrs", ".", "each", "do", "|", "attached_cidr", "|", "if", "cidr", "!=", "attached_cidr", "warn", "\"Migrate container=#{container_id} from cidr=#{attached_cidr}\"", "@executor_pool", ".", "detach", "(", "container_id", ",", "attached_cidr", ")", "end", "end", "# attach with the correct address", "self", ".", "attach_container", "(", "container_id", ",", "cidr", ")", "end" ]
Attach container to weave with given CIDR address, first detaching any existing mismatching addresses @param [String] container_id @param [String] overlay_cidr '10.81.X.Y/16' @param [Array<String>] migrate_cidrs ['10.81.X.Y/19']
[ "Attach", "container", "to", "weave", "with", "given", "CIDR", "address", "first", "detaching", "any", "existing", "mismatching", "addresses" ]
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/network_adapters/weave.rb#L312-L324
16,665
kontena/kontena
agent/lib/kontena/network_adapters/weave.rb
Kontena::NetworkAdapters.Weave.remove_container
def remove_container(container_id, overlay_network, overlay_cidr) info "Remove container=#{container_id} from network=#{overlay_network} at cidr=#{overlay_cidr}" @ipam_client.release_address(overlay_network, overlay_cidr) rescue IpamError => error # Cleanup will take care of these later on warn "Failed to release container=#{container_id} from network=#{overlay_network} at cidr=#{overlay_cidr}: #{error}" end
ruby
def remove_container(container_id, overlay_network, overlay_cidr) info "Remove container=#{container_id} from network=#{overlay_network} at cidr=#{overlay_cidr}" @ipam_client.release_address(overlay_network, overlay_cidr) rescue IpamError => error # Cleanup will take care of these later on warn "Failed to release container=#{container_id} from network=#{overlay_network} at cidr=#{overlay_cidr}: #{error}" end
[ "def", "remove_container", "(", "container_id", ",", "overlay_network", ",", "overlay_cidr", ")", "info", "\"Remove container=#{container_id} from network=#{overlay_network} at cidr=#{overlay_cidr}\"", "@ipam_client", ".", "release_address", "(", "overlay_network", ",", "overlay_cidr", ")", "rescue", "IpamError", "=>", "error", "# Cleanup will take care of these later on", "warn", "\"Failed to release container=#{container_id} from network=#{overlay_network} at cidr=#{overlay_cidr}: #{error}\"", "end" ]
Remove container from weave network @param [String] container_id may not exist anymore @param [Hash] labels Docker container labels
[ "Remove", "container", "from", "weave", "network" ]
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/network_adapters/weave.rb#L330-L337
16,666
kontena/kontena
agent/lib/kontena/workers/weave_worker.rb
Kontena::Workers.WeaveWorker.start_container
def start_container(container) overlay_cidr = container.overlay_cidr if overlay_cidr wait_weave_running? register_container_dns(container) if container.service_container? attach_overlay(container) else debug "skip start for container=#{container.name} without overlay_cidr" end rescue Docker::Error::NotFoundError debug "skip start for missing container=#{container.id}" rescue => exc error "failed to start container: #{exc.class.name}: #{exc.message}" error exc.backtrace.join("\n") end
ruby
def start_container(container) overlay_cidr = container.overlay_cidr if overlay_cidr wait_weave_running? register_container_dns(container) if container.service_container? attach_overlay(container) else debug "skip start for container=#{container.name} without overlay_cidr" end rescue Docker::Error::NotFoundError debug "skip start for missing container=#{container.id}" rescue => exc error "failed to start container: #{exc.class.name}: #{exc.message}" error exc.backtrace.join("\n") end
[ "def", "start_container", "(", "container", ")", "overlay_cidr", "=", "container", ".", "overlay_cidr", "if", "overlay_cidr", "wait_weave_running?", "register_container_dns", "(", "container", ")", "if", "container", ".", "service_container?", "attach_overlay", "(", "container", ")", "else", "debug", "\"skip start for container=#{container.name} without overlay_cidr\"", "end", "rescue", "Docker", "::", "Error", "::", "NotFoundError", "debug", "\"skip start for missing container=#{container.id}\"", "rescue", "=>", "exc", "error", "\"failed to start container: #{exc.class.name}: #{exc.message}\"", "error", "exc", ".", "backtrace", ".", "join", "(", "\"\\n\"", ")", "end" ]
Ensure weave network for container @param [Docker::Container] container
[ "Ensure", "weave", "network", "for", "container" ]
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/workers/weave_worker.rb#L86-L102
16,667
kontena/kontena
cli/lib/kontena/plugin_manager.rb
Kontena.PluginManager.init
def init ENV["GEM_HOME"] = Common.install_dir Gem.paths = ENV Common.use_dummy_ui unless Kontena.debug? plugins true end
ruby
def init ENV["GEM_HOME"] = Common.install_dir Gem.paths = ENV Common.use_dummy_ui unless Kontena.debug? plugins true end
[ "def", "init", "ENV", "[", "\"GEM_HOME\"", "]", "=", "Common", ".", "install_dir", "Gem", ".", "paths", "=", "ENV", "Common", ".", "use_dummy_ui", "unless", "Kontena", ".", "debug?", "plugins", "true", "end" ]
Initialize plugin manager
[ "Initialize", "plugin", "manager" ]
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/plugin_manager.rb#L11-L17
16,668
kontena/kontena
agent/lib/kontena/logging.rb
Kontena.Logging.debug
def debug(message = nil, &block) logger.add(Logger::DEBUG, message, self.logging_prefix, &block) end
ruby
def debug(message = nil, &block) logger.add(Logger::DEBUG, message, self.logging_prefix, &block) end
[ "def", "debug", "(", "message", "=", "nil", ",", "&", "block", ")", "logger", ".", "add", "(", "Logger", "::", "DEBUG", ",", "message", ",", "self", ".", "logging_prefix", ",", "block", ")", "end" ]
Send a debug message @param message [String] @yield optionally set the message using a block
[ "Send", "a", "debug", "message" ]
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/logging.rb#L32-L34
16,669
kontena/kontena
agent/lib/kontena/logging.rb
Kontena.Logging.info
def info(message = nil, &block) logger.add(Logger::INFO, message, self.logging_prefix, &block) end
ruby
def info(message = nil, &block) logger.add(Logger::INFO, message, self.logging_prefix, &block) end
[ "def", "info", "(", "message", "=", "nil", ",", "&", "block", ")", "logger", ".", "add", "(", "Logger", "::", "INFO", ",", "message", ",", "self", ".", "logging_prefix", ",", "block", ")", "end" ]
Send a info message @param message [String] @yield optionally set the message using a block
[ "Send", "a", "info", "message" ]
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/logging.rb#L39-L41
16,670
kontena/kontena
agent/lib/kontena/logging.rb
Kontena.Logging.warn
def warn(message = nil, &block) logger.add(Logger::WARN, message, self.logging_prefix, &block) end
ruby
def warn(message = nil, &block) logger.add(Logger::WARN, message, self.logging_prefix, &block) end
[ "def", "warn", "(", "message", "=", "nil", ",", "&", "block", ")", "logger", ".", "add", "(", "Logger", "::", "WARN", ",", "message", ",", "self", ".", "logging_prefix", ",", "block", ")", "end" ]
Send a warning message @param message [String] @yield optionally set the message using a block
[ "Send", "a", "warning", "message" ]
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/logging.rb#L46-L48
16,671
kontena/kontena
agent/lib/kontena/logging.rb
Kontena.Logging.error
def error(message = nil, &block) logger.add(Logger::ERROR, message, self.logging_prefix, &block) end
ruby
def error(message = nil, &block) logger.add(Logger::ERROR, message, self.logging_prefix, &block) end
[ "def", "error", "(", "message", "=", "nil", ",", "&", "block", ")", "logger", ".", "add", "(", "Logger", "::", "ERROR", ",", "message", ",", "self", ".", "logging_prefix", ",", "block", ")", "end" ]
Send an error message @param message [String] @yield optionally set the message using a block
[ "Send", "an", "error", "message" ]
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/logging.rb#L53-L55
16,672
kontena/kontena
server/lib/mutations/command_errors.rb
Mutations.Command.add_error
def add_error(key, error, message = nil) if error.is_a? Symbol error = ErrorAtom.new(key, error, message: message) elsif error.is_a?(Mutations::ErrorAtom) || error.is_a?(Mutations::ErrorArray) || error.is_a?(Mutations::ErrorHash) else raise ArgumentError.new("Invalid error of kind #{error.class}") end @errors ||= ErrorHash.new @errors.tap do |errs| path = key.to_s.split(".") last = path.pop inner = path.inject(errs) do |cur_errors,part| cur_errors[part.to_sym] ||= ErrorHash.new end inner[last] = error end end
ruby
def add_error(key, error, message = nil) if error.is_a? Symbol error = ErrorAtom.new(key, error, message: message) elsif error.is_a?(Mutations::ErrorAtom) || error.is_a?(Mutations::ErrorArray) || error.is_a?(Mutations::ErrorHash) else raise ArgumentError.new("Invalid error of kind #{error.class}") end @errors ||= ErrorHash.new @errors.tap do |errs| path = key.to_s.split(".") last = path.pop inner = path.inject(errs) do |cur_errors,part| cur_errors[part.to_sym] ||= ErrorHash.new end inner[last] = error end end
[ "def", "add_error", "(", "key", ",", "error", ",", "message", "=", "nil", ")", "if", "error", ".", "is_a?", "Symbol", "error", "=", "ErrorAtom", ".", "new", "(", "key", ",", "error", ",", "message", ":", "message", ")", "elsif", "error", ".", "is_a?", "(", "Mutations", "::", "ErrorAtom", ")", "||", "error", ".", "is_a?", "(", "Mutations", "::", "ErrorArray", ")", "||", "error", ".", "is_a?", "(", "Mutations", "::", "ErrorHash", ")", "else", "raise", "ArgumentError", ".", "new", "(", "\"Invalid error of kind #{error.class}\"", ")", "end", "@errors", "||=", "ErrorHash", ".", "new", "@errors", ".", "tap", "do", "|", "errs", "|", "path", "=", "key", ".", "to_s", ".", "split", "(", "\".\"", ")", "last", "=", "path", ".", "pop", "inner", "=", "path", ".", "inject", "(", "errs", ")", "do", "|", "cur_errors", ",", "part", "|", "cur_errors", "[", "part", ".", "to_sym", "]", "||=", "ErrorHash", ".", "new", "end", "inner", "[", "last", "]", "=", "error", "end", "end" ]
Add error for a key @param key [Symbol] :foo @param key [String] 'foo.bar' @param error [Symbol] :not_found @param error [Mutations:ErrorAtom, Mutations::ErrorArray, Mutations::ErrorHash]
[ "Add", "error", "for", "a", "key" ]
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/server/lib/mutations/command_errors.rb#L13-L31
16,673
kontena/kontena
cli/lib/kontena/cli/helpers/exec_helper.rb
Kontena::Cli::Helpers.ExecHelper.websocket_exec_write_thread
def websocket_exec_write_thread(ws, tty: nil) Thread.new do begin if tty console_height, console_width = TTY::Screen.size websocket_exec_write(ws, 'tty_size' => { width: console_width, height: console_height }) end read_stdin(tty: tty) do |stdin| logger.debug "websocket exec stdin with encoding=#{stdin.encoding}: #{stdin.inspect}" websocket_exec_write(ws, 'stdin' => stdin) end websocket_exec_write(ws, 'stdin' => nil) # EOF rescue => exc logger.error exc ws.close(1001, "stdin read #{exc.class}: #{exc}") end end end
ruby
def websocket_exec_write_thread(ws, tty: nil) Thread.new do begin if tty console_height, console_width = TTY::Screen.size websocket_exec_write(ws, 'tty_size' => { width: console_width, height: console_height }) end read_stdin(tty: tty) do |stdin| logger.debug "websocket exec stdin with encoding=#{stdin.encoding}: #{stdin.inspect}" websocket_exec_write(ws, 'stdin' => stdin) end websocket_exec_write(ws, 'stdin' => nil) # EOF rescue => exc logger.error exc ws.close(1001, "stdin read #{exc.class}: #{exc}") end end end
[ "def", "websocket_exec_write_thread", "(", "ws", ",", "tty", ":", "nil", ")", "Thread", ".", "new", "do", "begin", "if", "tty", "console_height", ",", "console_width", "=", "TTY", "::", "Screen", ".", "size", "websocket_exec_write", "(", "ws", ",", "'tty_size'", "=>", "{", "width", ":", "console_width", ",", "height", ":", "console_height", "}", ")", "end", "read_stdin", "(", "tty", ":", "tty", ")", "do", "|", "stdin", "|", "logger", ".", "debug", "\"websocket exec stdin with encoding=#{stdin.encoding}: #{stdin.inspect}\"", "websocket_exec_write", "(", "ws", ",", "'stdin'", "=>", "stdin", ")", "end", "websocket_exec_write", "(", "ws", ",", "'stdin'", "=>", "nil", ")", "# EOF", "rescue", "=>", "exc", "logger", ".", "error", "exc", "ws", ".", "close", "(", "1001", ",", "\"stdin read #{exc.class}: #{exc}\"", ")", "end", "end", "end" ]
Start thread to read from stdin, and write to websocket. Closes websocket on stdin read errors. @param ws [Kontena::Websocket::Client] @param tty [Boolean] @return [Thread]
[ "Start", "thread", "to", "read", "from", "stdin", "and", "write", "to", "websocket", ".", "Closes", "websocket", "on", "stdin", "read", "errors", "." ]
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/cli/helpers/exec_helper.rb#L107-L126
16,674
kontena/kontena
cli/lib/kontena/cli/helpers/exec_helper.rb
Kontena::Cli::Helpers.ExecHelper.websocket_exec
def websocket_exec(path, cmd, interactive: false, shell: false, tty: false) exit_status = nil write_thread = nil query = {} query[:interactive] = interactive if interactive query[:shell] = shell if shell query[:tty] = tty if tty server = require_current_master url = websocket_url(path, query) token = require_token options = WEBSOCKET_CLIENT_OPTIONS.dup options[:headers] = { 'Authorization' => "Bearer #{token.access_token}" } options[:ssl_params] = { verify_mode: ENV['SSL_IGNORE_ERRORS'].to_s == 'true' ? OpenSSL::SSL::VERIFY_NONE : OpenSSL::SSL::VERIFY_PEER, ca_file: server.ssl_cert_path, } options[:ssl_hostname] = server.ssl_subject_cn logger.debug { "websocket exec connect... #{url}" } # we do not expect CloseError, because the server will send an 'exit' message first, # and we return before seeing the close frame # TODO: handle HTTP 404 errors Kontena::Websocket::Client.connect(url, **options) do |ws| logger.debug { "websocket exec open" } # first frame contains exec command websocket_exec_write(ws, 'cmd' => cmd) if interactive # start new thread to write from stdin to websocket write_thread = websocket_exec_write_thread(ws, tty: tty) end # blocks reading from websocket, returns with exec exit code exit_status = websocket_exec_read(ws) fail ws.close_reason unless exit_status end rescue Kontena::Websocket::Error => exc exit_with_error(exc) rescue => exc logger.error { "websocket exec error: #{exc}" } raise else logger.debug { "websocket exec exit: #{exit_status}"} return exit_status ensure if write_thread write_thread.kill write_thread.join end end
ruby
def websocket_exec(path, cmd, interactive: false, shell: false, tty: false) exit_status = nil write_thread = nil query = {} query[:interactive] = interactive if interactive query[:shell] = shell if shell query[:tty] = tty if tty server = require_current_master url = websocket_url(path, query) token = require_token options = WEBSOCKET_CLIENT_OPTIONS.dup options[:headers] = { 'Authorization' => "Bearer #{token.access_token}" } options[:ssl_params] = { verify_mode: ENV['SSL_IGNORE_ERRORS'].to_s == 'true' ? OpenSSL::SSL::VERIFY_NONE : OpenSSL::SSL::VERIFY_PEER, ca_file: server.ssl_cert_path, } options[:ssl_hostname] = server.ssl_subject_cn logger.debug { "websocket exec connect... #{url}" } # we do not expect CloseError, because the server will send an 'exit' message first, # and we return before seeing the close frame # TODO: handle HTTP 404 errors Kontena::Websocket::Client.connect(url, **options) do |ws| logger.debug { "websocket exec open" } # first frame contains exec command websocket_exec_write(ws, 'cmd' => cmd) if interactive # start new thread to write from stdin to websocket write_thread = websocket_exec_write_thread(ws, tty: tty) end # blocks reading from websocket, returns with exec exit code exit_status = websocket_exec_read(ws) fail ws.close_reason unless exit_status end rescue Kontena::Websocket::Error => exc exit_with_error(exc) rescue => exc logger.error { "websocket exec error: #{exc}" } raise else logger.debug { "websocket exec exit: #{exit_status}"} return exit_status ensure if write_thread write_thread.kill write_thread.join end end
[ "def", "websocket_exec", "(", "path", ",", "cmd", ",", "interactive", ":", "false", ",", "shell", ":", "false", ",", "tty", ":", "false", ")", "exit_status", "=", "nil", "write_thread", "=", "nil", "query", "=", "{", "}", "query", "[", ":interactive", "]", "=", "interactive", "if", "interactive", "query", "[", ":shell", "]", "=", "shell", "if", "shell", "query", "[", ":tty", "]", "=", "tty", "if", "tty", "server", "=", "require_current_master", "url", "=", "websocket_url", "(", "path", ",", "query", ")", "token", "=", "require_token", "options", "=", "WEBSOCKET_CLIENT_OPTIONS", ".", "dup", "options", "[", ":headers", "]", "=", "{", "'Authorization'", "=>", "\"Bearer #{token.access_token}\"", "}", "options", "[", ":ssl_params", "]", "=", "{", "verify_mode", ":", "ENV", "[", "'SSL_IGNORE_ERRORS'", "]", ".", "to_s", "==", "'true'", "?", "OpenSSL", "::", "SSL", "::", "VERIFY_NONE", ":", "OpenSSL", "::", "SSL", "::", "VERIFY_PEER", ",", "ca_file", ":", "server", ".", "ssl_cert_path", ",", "}", "options", "[", ":ssl_hostname", "]", "=", "server", ".", "ssl_subject_cn", "logger", ".", "debug", "{", "\"websocket exec connect... #{url}\"", "}", "# we do not expect CloseError, because the server will send an 'exit' message first,", "# and we return before seeing the close frame", "# TODO: handle HTTP 404 errors", "Kontena", "::", "Websocket", "::", "Client", ".", "connect", "(", "url", ",", "**", "options", ")", "do", "|", "ws", "|", "logger", ".", "debug", "{", "\"websocket exec open\"", "}", "# first frame contains exec command", "websocket_exec_write", "(", "ws", ",", "'cmd'", "=>", "cmd", ")", "if", "interactive", "# start new thread to write from stdin to websocket", "write_thread", "=", "websocket_exec_write_thread", "(", "ws", ",", "tty", ":", "tty", ")", "end", "# blocks reading from websocket, returns with exec exit code", "exit_status", "=", "websocket_exec_read", "(", "ws", ")", "fail", "ws", ".", "close_reason", "unless", "exit_status", "end", "rescue", "Kontena", "::", "Websocket", "::", "Error", "=>", "exc", "exit_with_error", "(", "exc", ")", "rescue", "=>", "exc", "logger", ".", "error", "{", "\"websocket exec error: #{exc}\"", "}", "raise", "else", "logger", ".", "debug", "{", "\"websocket exec exit: #{exit_status}\"", "}", "return", "exit_status", "ensure", "if", "write_thread", "write_thread", ".", "kill", "write_thread", ".", "join", "end", "end" ]
Connect to server websocket, send from stdin, and write out messages @param paths [String] @param options [Hash] @see Kontena::Websocket::Client @param cmd [Array<String>] command to execute @param interactive [Boolean] Interactive TTY on/off @param shell [Boolean] Shell on/of @param tty [Boolean] TTY on/of @return [Integer] exit code
[ "Connect", "to", "server", "websocket", "send", "from", "stdin", "and", "write", "out", "messages" ]
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/cli/helpers/exec_helper.rb#L137-L197
16,675
kontena/kontena
agent/lib/kontena/launchers/etcd.rb
Kontena::Launchers.Etcd.update_membership
def update_membership(node) info 'checking if etcd previous membership needs to be updated' etcd_connection = find_etcd_node(node) return 'new' unless etcd_connection # No etcd hosts available, bootstrapping first node --> new cluster weave_ip = node.overlay_ip peer_url = "http://#{weave_ip}:2380" client_url = "http://#{weave_ip}:2379" members = JSON.parse(etcd_connection.get.body) members['members'].each do |member| if member['peerURLs'].include?(peer_url) && member['clientURLs'].include?(client_url) # When there's both peer and client URLs, the given peer has been a member of the cluster # and needs to be replaced delete_membership(etcd_connection, member['id']) sleep 1 # There seems to be some race condition with etcd member API, thus some sleeping required add_membership(etcd_connection, peer_url) sleep 1 return 'existing' elsif member['peerURLs'].include?(peer_url) && !member['clientURLs'].include?(client_url) # Peer found but not been part of the cluster yet, no modification needed and it can join as new member return 'new' end end info 'previous member info not found at all, adding' add_membership(etcd_connection, peer_url) 'new' # Newly added member will join as new member end
ruby
def update_membership(node) info 'checking if etcd previous membership needs to be updated' etcd_connection = find_etcd_node(node) return 'new' unless etcd_connection # No etcd hosts available, bootstrapping first node --> new cluster weave_ip = node.overlay_ip peer_url = "http://#{weave_ip}:2380" client_url = "http://#{weave_ip}:2379" members = JSON.parse(etcd_connection.get.body) members['members'].each do |member| if member['peerURLs'].include?(peer_url) && member['clientURLs'].include?(client_url) # When there's both peer and client URLs, the given peer has been a member of the cluster # and needs to be replaced delete_membership(etcd_connection, member['id']) sleep 1 # There seems to be some race condition with etcd member API, thus some sleeping required add_membership(etcd_connection, peer_url) sleep 1 return 'existing' elsif member['peerURLs'].include?(peer_url) && !member['clientURLs'].include?(client_url) # Peer found but not been part of the cluster yet, no modification needed and it can join as new member return 'new' end end info 'previous member info not found at all, adding' add_membership(etcd_connection, peer_url) 'new' # Newly added member will join as new member end
[ "def", "update_membership", "(", "node", ")", "info", "'checking if etcd previous membership needs to be updated'", "etcd_connection", "=", "find_etcd_node", "(", "node", ")", "return", "'new'", "unless", "etcd_connection", "# No etcd hosts available, bootstrapping first node --> new cluster", "weave_ip", "=", "node", ".", "overlay_ip", "peer_url", "=", "\"http://#{weave_ip}:2380\"", "client_url", "=", "\"http://#{weave_ip}:2379\"", "members", "=", "JSON", ".", "parse", "(", "etcd_connection", ".", "get", ".", "body", ")", "members", "[", "'members'", "]", ".", "each", "do", "|", "member", "|", "if", "member", "[", "'peerURLs'", "]", ".", "include?", "(", "peer_url", ")", "&&", "member", "[", "'clientURLs'", "]", ".", "include?", "(", "client_url", ")", "# When there's both peer and client URLs, the given peer has been a member of the cluster", "# and needs to be replaced", "delete_membership", "(", "etcd_connection", ",", "member", "[", "'id'", "]", ")", "sleep", "1", "# There seems to be some race condition with etcd member API, thus some sleeping required", "add_membership", "(", "etcd_connection", ",", "peer_url", ")", "sleep", "1", "return", "'existing'", "elsif", "member", "[", "'peerURLs'", "]", ".", "include?", "(", "peer_url", ")", "&&", "!", "member", "[", "'clientURLs'", "]", ".", "include?", "(", "client_url", ")", "# Peer found but not been part of the cluster yet, no modification needed and it can join as new member", "return", "'new'", "end", "end", "info", "'previous member info not found at all, adding'", "add_membership", "(", "etcd_connection", ",", "peer_url", ")", "'new'", "# Newly added member will join as new member", "end" ]
Removes possible previous member with the same IP @param [Node] node @return [String] the state of the cluster member
[ "Removes", "possible", "previous", "member", "with", "the", "same", "IP" ]
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/launchers/etcd.rb#L173-L203
16,676
kontena/kontena
agent/lib/kontena/launchers/etcd.rb
Kontena::Launchers.Etcd.find_etcd_node
def find_etcd_node(node) grid_subnet = IPAddr.new(node.grid['subnet']) tries = node.grid['initial_size'] begin etcd_host = "http://#{grid_subnet[tries]}:2379/v2/members" info "connecting to existing etcd at #{etcd_host}" connection = Excon.new(etcd_host) members = JSON.parse(connection.get.body) return connection rescue Excon::Errors::Error => exc tries -= 1 if tries > 0 info 'retrying next etcd host' retry else info 'no online etcd host found, we\'re probably bootstrapping first node' end end nil end
ruby
def find_etcd_node(node) grid_subnet = IPAddr.new(node.grid['subnet']) tries = node.grid['initial_size'] begin etcd_host = "http://#{grid_subnet[tries]}:2379/v2/members" info "connecting to existing etcd at #{etcd_host}" connection = Excon.new(etcd_host) members = JSON.parse(connection.get.body) return connection rescue Excon::Errors::Error => exc tries -= 1 if tries > 0 info 'retrying next etcd host' retry else info 'no online etcd host found, we\'re probably bootstrapping first node' end end nil end
[ "def", "find_etcd_node", "(", "node", ")", "grid_subnet", "=", "IPAddr", ".", "new", "(", "node", ".", "grid", "[", "'subnet'", "]", ")", "tries", "=", "node", ".", "grid", "[", "'initial_size'", "]", "begin", "etcd_host", "=", "\"http://#{grid_subnet[tries]}:2379/v2/members\"", "info", "\"connecting to existing etcd at #{etcd_host}\"", "connection", "=", "Excon", ".", "new", "(", "etcd_host", ")", "members", "=", "JSON", ".", "parse", "(", "connection", ".", "get", ".", "body", ")", "return", "connection", "rescue", "Excon", "::", "Errors", "::", "Error", "=>", "exc", "tries", "-=", "1", "if", "tries", ">", "0", "info", "'retrying next etcd host'", "retry", "else", "info", "'no online etcd host found, we\\'re probably bootstrapping first node'", "end", "end", "nil", "end" ]
Finds a working etcd node from set of initial nodes @param [Node] node @return [Hash] The cluster members as given by etcd API
[ "Finds", "a", "working", "etcd", "node", "from", "set", "of", "initial", "nodes" ]
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/launchers/etcd.rb#L210-L231
16,677
kontena/kontena
agent/lib/kontena/launchers/etcd.rb
Kontena::Launchers.Etcd.add_membership
def add_membership(connection, peer_url) info "Adding new etcd membership info with peer URL #{peer_url}" connection.post(:body => JSON.generate(peerURLs: [peer_url]), :headers => { 'Content-Type' => 'application/json' }) end
ruby
def add_membership(connection, peer_url) info "Adding new etcd membership info with peer URL #{peer_url}" connection.post(:body => JSON.generate(peerURLs: [peer_url]), :headers => { 'Content-Type' => 'application/json' }) end
[ "def", "add_membership", "(", "connection", ",", "peer_url", ")", "info", "\"Adding new etcd membership info with peer URL #{peer_url}\"", "connection", ".", "post", "(", ":body", "=>", "JSON", ".", "generate", "(", "peerURLs", ":", "[", "peer_url", "]", ")", ",", ":headers", "=>", "{", "'Content-Type'", "=>", "'application/json'", "}", ")", "end" ]
Add new peer membership @param [Excon::Connection] etcd HTTP members API connection @param [String] The peer URL of the new peer to be added to the cluster
[ "Add", "new", "peer", "membership" ]
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/launchers/etcd.rb#L247-L251
16,678
kontena/kontena
agent/lib/kontena/observable.rb
Kontena.Observable.update
def update(value) raise RuntimeError, "Observable crashed: #{@value}" if crashed? raise ArgumentError, "Update with nil value" if value.nil? debug { "update: #{value}" } set_and_notify(value) end
ruby
def update(value) raise RuntimeError, "Observable crashed: #{@value}" if crashed? raise ArgumentError, "Update with nil value" if value.nil? debug { "update: #{value}" } set_and_notify(value) end
[ "def", "update", "(", "value", ")", "raise", "RuntimeError", ",", "\"Observable crashed: #{@value}\"", "if", "crashed?", "raise", "ArgumentError", ",", "\"Update with nil value\"", "if", "value", ".", "nil?", "debug", "{", "\"update: #{value}\"", "}", "set_and_notify", "(", "value", ")", "end" ]
The Observable has a value. Propagate it to any observers. This will notify any Observers, causing them to yield/return if ready. The value must be immutable and threadsafe: it must remain valid for use by other threads both after this update, and after any other future updates. Do not send a mutable object that gets invalidated in between updates. TODO: automatically freeze the value? @param value [Object] @raise [RuntimeError] Observable crashed @raise [ArgumentError] Update with nil value
[ "The", "Observable", "has", "a", "value", ".", "Propagate", "it", "to", "any", "observers", "." ]
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/observable.rb#L118-L125
16,679
kontena/kontena
agent/lib/kontena/workers/volumes/volume_manager.rb
Kontena::Workers::Volumes.VolumeManager.volume_exist?
def volume_exist?(volume_name, driver) begin debug "volume #{volume_name} exists" volume = Docker::Volume.get(volume_name) if volume && volume.info['Driver'] == driver return true elsif volume && volume.info['Driver'] != driver raise DriverMismatchError.new("Volume driver not as expected. Expected #{driver}, existing volume has #{volume.info['Driver']}") end rescue Docker::Error::NotFoundError debug "volume #{volume_name} does NOT exist" false rescue => error abort error end end
ruby
def volume_exist?(volume_name, driver) begin debug "volume #{volume_name} exists" volume = Docker::Volume.get(volume_name) if volume && volume.info['Driver'] == driver return true elsif volume && volume.info['Driver'] != driver raise DriverMismatchError.new("Volume driver not as expected. Expected #{driver}, existing volume has #{volume.info['Driver']}") end rescue Docker::Error::NotFoundError debug "volume #{volume_name} does NOT exist" false rescue => error abort error end end
[ "def", "volume_exist?", "(", "volume_name", ",", "driver", ")", "begin", "debug", "\"volume #{volume_name} exists\"", "volume", "=", "Docker", "::", "Volume", ".", "get", "(", "volume_name", ")", "if", "volume", "&&", "volume", ".", "info", "[", "'Driver'", "]", "==", "driver", "return", "true", "elsif", "volume", "&&", "volume", ".", "info", "[", "'Driver'", "]", "!=", "driver", "raise", "DriverMismatchError", ".", "new", "(", "\"Volume driver not as expected. Expected #{driver}, existing volume has #{volume.info['Driver']}\"", ")", "end", "rescue", "Docker", "::", "Error", "::", "NotFoundError", "debug", "\"volume #{volume_name} does NOT exist\"", "false", "rescue", "=>", "error", "abort", "error", "end", "end" ]
Checks if given volume exists with the expected driver @param [String] name of the volume @param [String] driver to expect on the volume if already existing @raise [DriverMismatchError] If the volume is found but using a different driver than expected
[ "Checks", "if", "given", "volume", "exists", "with", "the", "expected", "driver" ]
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/workers/volumes/volume_manager.rb#L106-L121
16,680
kontena/kontena
agent/lib/kontena/workers/service_pod_worker.rb
Kontena::Workers.ServicePodWorker.on_container_die
def on_container_die(exit_code: ) cancel_restart_timers return unless @service_pod.running? # backoff restarts backoff = @restarts ** 2 backoff = max_restart_backoff if backoff > max_restart_backoff info "#{@service_pod} exited with code #{exit_code}, restarting (delay: #{backoff}s)" log_service_pod_event("service:instance_crash", "service #{@service_pod} instance exited with code #{exit_code}, restarting (delay: #{backoff}s)", Logger::WARN ) ts = Time.now.utc @restarts += 1 @restart_backoff_timer = after(backoff) { debug "restart triggered (from #{ts})" apply } end
ruby
def on_container_die(exit_code: ) cancel_restart_timers return unless @service_pod.running? # backoff restarts backoff = @restarts ** 2 backoff = max_restart_backoff if backoff > max_restart_backoff info "#{@service_pod} exited with code #{exit_code}, restarting (delay: #{backoff}s)" log_service_pod_event("service:instance_crash", "service #{@service_pod} instance exited with code #{exit_code}, restarting (delay: #{backoff}s)", Logger::WARN ) ts = Time.now.utc @restarts += 1 @restart_backoff_timer = after(backoff) { debug "restart triggered (from #{ts})" apply } end
[ "def", "on_container_die", "(", "exit_code", ":", ")", "cancel_restart_timers", "return", "unless", "@service_pod", ".", "running?", "# backoff restarts", "backoff", "=", "@restarts", "**", "2", "backoff", "=", "max_restart_backoff", "if", "backoff", ">", "max_restart_backoff", "info", "\"#{@service_pod} exited with code #{exit_code}, restarting (delay: #{backoff}s)\"", "log_service_pod_event", "(", "\"service:instance_crash\"", ",", "\"service #{@service_pod} instance exited with code #{exit_code}, restarting (delay: #{backoff}s)\"", ",", "Logger", "::", "WARN", ")", "ts", "=", "Time", ".", "now", ".", "utc", "@restarts", "+=", "1", "@restart_backoff_timer", "=", "after", "(", "backoff", ")", "{", "debug", "\"restart triggered (from #{ts})\"", "apply", "}", "end" ]
Handles events when container has died
[ "Handles", "events", "when", "container", "has", "died" ]
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/workers/service_pod_worker.rb#L103-L123
16,681
kontena/kontena
agent/lib/kontena/workers/service_pod_worker.rb
Kontena::Workers.ServicePodWorker.restart
def restart(at = Time.now, container_id: nil, started_at: nil) if container_id && @container.id != container_id debug "stale #{@service_pod} restart for container id=#{container_id}" return end if started_at && @container.started_at != started_at debug "stale #{@service_pod} restart for container started_at=#{started_at}" return end debug "mark #{@service_pod} for restart at #{at}" @restarting_at = at apply end
ruby
def restart(at = Time.now, container_id: nil, started_at: nil) if container_id && @container.id != container_id debug "stale #{@service_pod} restart for container id=#{container_id}" return end if started_at && @container.started_at != started_at debug "stale #{@service_pod} restart for container started_at=#{started_at}" return end debug "mark #{@service_pod} for restart at #{at}" @restarting_at = at apply end
[ "def", "restart", "(", "at", "=", "Time", ".", "now", ",", "container_id", ":", "nil", ",", "started_at", ":", "nil", ")", "if", "container_id", "&&", "@container", ".", "id", "!=", "container_id", "debug", "\"stale #{@service_pod} restart for container id=#{container_id}\"", "return", "end", "if", "started_at", "&&", "@container", ".", "started_at", "!=", "started_at", "debug", "\"stale #{@service_pod} restart for container started_at=#{started_at}\"", "return", "end", "debug", "\"mark #{@service_pod} for restart at #{at}\"", "@restarting_at", "=", "at", "apply", "end" ]
User requested service restart
[ "User", "requested", "service", "restart" ]
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/workers/service_pod_worker.rb#L141-L154
16,682
kontena/kontena
agent/lib/kontena/workers/service_pod_worker.rb
Kontena::Workers.ServicePodWorker.check_starting!
def check_starting!(service_pod, container) raise "service stopped" if !@service_pod.running? raise "service redeployed" if @service_pod.deploy_rev != service_pod.deploy_rev raise "container recreated" if @container.id != container.id raise "container restarted" if @container.started_at != container.started_at end
ruby
def check_starting!(service_pod, container) raise "service stopped" if !@service_pod.running? raise "service redeployed" if @service_pod.deploy_rev != service_pod.deploy_rev raise "container recreated" if @container.id != container.id raise "container restarted" if @container.started_at != container.started_at end
[ "def", "check_starting!", "(", "service_pod", ",", "container", ")", "raise", "\"service stopped\"", "if", "!", "@service_pod", ".", "running?", "raise", "\"service redeployed\"", "if", "@service_pod", ".", "deploy_rev", "!=", "service_pod", ".", "deploy_rev", "raise", "\"container recreated\"", "if", "@container", ".", "id", "!=", "container", ".", "id", "raise", "\"container restarted\"", "if", "@container", ".", "started_at", "!=", "container", ".", "started_at", "end" ]
Check that the given container is still running for the given service pod revision. @raise [RuntimeError] service stopped @raise [RuntimeError] service redeployed @raise [RuntimeError] container recreated @raise [RuntimeError] container restarted
[ "Check", "that", "the", "given", "container", "is", "still", "running", "for", "the", "given", "service", "pod", "revision", "." ]
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/workers/service_pod_worker.rb#L208-L213
16,683
kontena/kontena
server/app/mutations/grid_services/helpers.rb
GridServices.Helpers.document_changes
def document_changes(document) (document.changed + document._children.select{|child| child.changed? }.map { |child| "#{child.metadata_name.to_s}{#{child.changed.join(", ")}}" }).join(", ") end
ruby
def document_changes(document) (document.changed + document._children.select{|child| child.changed? }.map { |child| "#{child.metadata_name.to_s}{#{child.changed.join(", ")}}" }).join(", ") end
[ "def", "document_changes", "(", "document", ")", "(", "document", ".", "changed", "+", "document", ".", "_children", ".", "select", "{", "|", "child", "|", "child", ".", "changed?", "}", ".", "map", "{", "|", "child", "|", "\"#{child.metadata_name.to_s}{#{child.changed.join(\", \")}}\"", "}", ")", ".", "join", "(", "\", \"", ")", "end" ]
List changed fields of model @param document [Mongoid::Document] @return [String] field, embedded{field}
[ "List", "changed", "fields", "of", "model" ]
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/server/app/mutations/grid_services/helpers.rb#L8-L12
16,684
kontena/kontena
server/app/mutations/grid_services/helpers.rb
GridServices.Helpers.save_grid_service
def save_grid_service(grid_service) if grid_service.save return grid_service else grid_service.errors.each do |key, message| add_error(key, :invalid, message) end return nil end end
ruby
def save_grid_service(grid_service) if grid_service.save return grid_service else grid_service.errors.each do |key, message| add_error(key, :invalid, message) end return nil end end
[ "def", "save_grid_service", "(", "grid_service", ")", "if", "grid_service", ".", "save", "return", "grid_service", "else", "grid_service", ".", "errors", ".", "each", "do", "|", "key", ",", "message", "|", "add_error", "(", "key", ",", ":invalid", ",", "message", ")", "end", "return", "nil", "end", "end" ]
Adds errors if save fails @param grid_service [GridService] @return [GridService] nil if error
[ "Adds", "errors", "if", "save", "fails" ]
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/server/app/mutations/grid_services/helpers.rb#L18-L27
16,685
kontena/kontena
server/app/mutations/grid_services/helpers.rb
GridServices.Helpers.update_grid_service
def update_grid_service(grid_service, force: false) if grid_service.changed? || force grid_service.revision += 1 info "updating service #{grid_service.to_path} revision #{grid_service.revision} with changes: #{document_changes(grid_service)}" else debug "not updating service #{grid_service.to_path} revision #{grid_service.revision} without changes" end save_grid_service(grid_service) end
ruby
def update_grid_service(grid_service, force: false) if grid_service.changed? || force grid_service.revision += 1 info "updating service #{grid_service.to_path} revision #{grid_service.revision} with changes: #{document_changes(grid_service)}" else debug "not updating service #{grid_service.to_path} revision #{grid_service.revision} without changes" end save_grid_service(grid_service) end
[ "def", "update_grid_service", "(", "grid_service", ",", "force", ":", "false", ")", "if", "grid_service", ".", "changed?", "||", "force", "grid_service", ".", "revision", "+=", "1", "info", "\"updating service #{grid_service.to_path} revision #{grid_service.revision} with changes: #{document_changes(grid_service)}\"", "else", "debug", "\"not updating service #{grid_service.to_path} revision #{grid_service.revision} without changes\"", "end", "save_grid_service", "(", "grid_service", ")", "end" ]
Bump grid_service.revision if changed or force, and save Adds errors if save fails @param grid_service [GridService] @param force [Boolean] force-update revision @return [GridService] nil if error
[ "Bump", "grid_service", ".", "revision", "if", "changed", "or", "force", "and", "save", "Adds", "errors", "if", "save", "fails" ]
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/server/app/mutations/grid_services/helpers.rb#L35-L44
16,686
kontena/kontena
agent/lib/kontena/observer.rb
Kontena.Observer.error
def error @values.each_pair{|observable, value| return Error.new(observable, value) if Exception === value } return nil end
ruby
def error @values.each_pair{|observable, value| return Error.new(observable, value) if Exception === value } return nil end
[ "def", "error", "@values", ".", "each_pair", "{", "|", "observable", ",", "value", "|", "return", "Error", ".", "new", "(", "observable", ",", "value", ")", "if", "Exception", "===", "value", "}", "return", "nil", "end" ]
Return Error for first crashed observable. Should only be used if error? @return [Exception, nil]
[ "Return", "Error", "for", "first", "crashed", "observable", "." ]
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/observer.rb#L290-L295
16,687
kontena/kontena
agent/lib/kontena/observer.rb
Kontena.Observer.each
def each(timeout: nil) @deadline = Time.now + timeout if timeout while true # prevent any intervening messages from being processed and discarded before we're back in Celluloid.receive() Celluloid.exclusive { if error? debug { "raise: #{self.describe_observables}" } raise self.error elsif ready? yield *self.values @deadline = Time.now + timeout if timeout end } # must be atomic! debug { "wait: #{self.describe_observables}" } update(receive()) end end
ruby
def each(timeout: nil) @deadline = Time.now + timeout if timeout while true # prevent any intervening messages from being processed and discarded before we're back in Celluloid.receive() Celluloid.exclusive { if error? debug { "raise: #{self.describe_observables}" } raise self.error elsif ready? yield *self.values @deadline = Time.now + timeout if timeout end } # must be atomic! debug { "wait: #{self.describe_observables}" } update(receive()) end end
[ "def", "each", "(", "timeout", ":", "nil", ")", "@deadline", "=", "Time", ".", "now", "+", "timeout", "if", "timeout", "while", "true", "# prevent any intervening messages from being processed and discarded before we're back in Celluloid.receive()", "Celluloid", ".", "exclusive", "{", "if", "error?", "debug", "{", "\"raise: #{self.describe_observables}\"", "}", "raise", "self", ".", "error", "elsif", "ready?", "yield", "self", ".", "values", "@deadline", "=", "Time", ".", "now", "+", "timeout", "if", "timeout", "end", "}", "# must be atomic!", "debug", "{", "\"wait: #{self.describe_observables}\"", "}", "update", "(", "receive", "(", ")", ")", "end", "end" ]
Yield each set of ready? observed values while alive, or raise on error? The yield is exclusive, because suspending the observing task would mean that any observable messages would get discarded. @param timeout [Float] timeout between each yield
[ "Yield", "each", "set", "of", "ready?", "observed", "values", "while", "alive", "or", "raise", "on", "error?" ]
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/observer.rb#L303-L325
16,688
kontena/kontena
server/app/mutations/grid_services/common.rb
GridServices.Common.validate_secrets
def validate_secrets validate_each :secrets do |s| secret = self.grid.grid_secrets.find_by(name: s[:secret]) unless secret [:not_found, "Secret #{s[:secret]} does not exist"] else nil end end end
ruby
def validate_secrets validate_each :secrets do |s| secret = self.grid.grid_secrets.find_by(name: s[:secret]) unless secret [:not_found, "Secret #{s[:secret]} does not exist"] else nil end end end
[ "def", "validate_secrets", "validate_each", ":secrets", "do", "|", "s", "|", "secret", "=", "self", ".", "grid", ".", "grid_secrets", ".", "find_by", "(", "name", ":", "s", "[", ":secret", "]", ")", "unless", "secret", "[", ":not_found", ",", "\"Secret #{s[:secret]} does not exist\"", "]", "else", "nil", "end", "end", "end" ]
Validates that the defined secrets exist
[ "Validates", "that", "the", "defined", "secrets", "exist" ]
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/server/app/mutations/grid_services/common.rb#L173-L182
16,689
kontena/kontena
server/app/mutations/grid_services/common.rb
GridServices.Common.validate_certificates
def validate_certificates validate_each :certificates do |c| cert = self.grid.certificates.find_by(subject: c[:subject]) unless cert [:not_found, "Certificate #{c[:subject]} does not exist"] else nil end end end
ruby
def validate_certificates validate_each :certificates do |c| cert = self.grid.certificates.find_by(subject: c[:subject]) unless cert [:not_found, "Certificate #{c[:subject]} does not exist"] else nil end end end
[ "def", "validate_certificates", "validate_each", ":certificates", "do", "|", "c", "|", "cert", "=", "self", ".", "grid", ".", "certificates", ".", "find_by", "(", "subject", ":", "c", "[", ":subject", "]", ")", "unless", "cert", "[", ":not_found", ",", "\"Certificate #{c[:subject]} does not exist\"", "]", "else", "nil", "end", "end", "end" ]
Validates that the defined certificates exist
[ "Validates", "that", "the", "defined", "certificates", "exist" ]
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/server/app/mutations/grid_services/common.rb#L185-L194
16,690
kontena/kontena
server/app/services/docker/streaming_executor.rb
Docker.StreamingExecutor.start
def start(ws) @ws = ws @ws.on(:message) do |event| on_websocket_message(event.data) end @ws.on(:error) do |exc| warn exc end @ws.on(:close) do |event| on_websocket_close(event.code, event.reason) end started! end
ruby
def start(ws) @ws = ws @ws.on(:message) do |event| on_websocket_message(event.data) end @ws.on(:error) do |exc| warn exc end @ws.on(:close) do |event| on_websocket_close(event.code, event.reason) end started! end
[ "def", "start", "(", "ws", ")", "@ws", "=", "ws", "@ws", ".", "on", "(", ":message", ")", "do", "|", "event", "|", "on_websocket_message", "(", "event", ".", "data", ")", "end", "@ws", ".", "on", "(", ":error", ")", "do", "|", "exc", "|", "warn", "exc", "end", "@ws", ".", "on", "(", ":close", ")", "do", "|", "event", "|", "on_websocket_close", "(", "event", ".", "code", ",", "event", ".", "reason", ")", "end", "started!", "end" ]
Does not raise. @param ws [Faye::Websocket]
[ "Does", "not", "raise", "." ]
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/server/app/services/docker/streaming_executor.rb#L137-L153
16,691
kontena/kontena
cli/lib/kontena/cli/services/update_command.rb
Kontena::Cli::Services.UpdateCommand.parse_service_data_from_options
def parse_service_data_from_options data = {} data[:strategy] = deploy_strategy if deploy_strategy data[:ports] = parse_ports(ports_list) unless ports_list.empty? data[:links] = parse_links(link_list) unless link_list.empty? data[:memory] = parse_memory(memory) if memory data[:memory_swap] = parse_memory(memory_swap) if memory_swap data[:shm_size] = parse_memory(shm_size) if shm_size data[:cpus] = cpus if cpus data[:cpu_shares] = cpu_shares if cpu_shares data[:affinity] = affinity_list unless affinity_list.empty? data[:env] = env_list unless env_list.empty? data[:secrets] = parse_secrets(secret_list) unless secret_list.empty? data[:container_count] = instances if instances data[:cmd] = Shellwords.split(cmd) if cmd data[:user] = user if user data[:image] = parse_image(image) if image data[:privileged] = privileged? data[:cap_add] = cap_add_list if cap_add_list data[:cap_drop] = cap_drop_list if cap_drop_list data[:net] = net if net data[:log_driver] = log_driver if log_driver data[:log_opts] = parse_log_opts(log_opt_list) if log_opt_list deploy_opts = parse_deploy_opts data[:deploy_opts] = deploy_opts unless deploy_opts.empty? health_check = parse_health_check data[:health_check] = health_check unless health_check.empty? data[:pid] = pid if pid data[:stop_signal] = stop_signal if stop_signal data[:stop_grace_period] = stop_timeout if stop_timeout data end
ruby
def parse_service_data_from_options data = {} data[:strategy] = deploy_strategy if deploy_strategy data[:ports] = parse_ports(ports_list) unless ports_list.empty? data[:links] = parse_links(link_list) unless link_list.empty? data[:memory] = parse_memory(memory) if memory data[:memory_swap] = parse_memory(memory_swap) if memory_swap data[:shm_size] = parse_memory(shm_size) if shm_size data[:cpus] = cpus if cpus data[:cpu_shares] = cpu_shares if cpu_shares data[:affinity] = affinity_list unless affinity_list.empty? data[:env] = env_list unless env_list.empty? data[:secrets] = parse_secrets(secret_list) unless secret_list.empty? data[:container_count] = instances if instances data[:cmd] = Shellwords.split(cmd) if cmd data[:user] = user if user data[:image] = parse_image(image) if image data[:privileged] = privileged? data[:cap_add] = cap_add_list if cap_add_list data[:cap_drop] = cap_drop_list if cap_drop_list data[:net] = net if net data[:log_driver] = log_driver if log_driver data[:log_opts] = parse_log_opts(log_opt_list) if log_opt_list deploy_opts = parse_deploy_opts data[:deploy_opts] = deploy_opts unless deploy_opts.empty? health_check = parse_health_check data[:health_check] = health_check unless health_check.empty? data[:pid] = pid if pid data[:stop_signal] = stop_signal if stop_signal data[:stop_grace_period] = stop_timeout if stop_timeout data end
[ "def", "parse_service_data_from_options", "data", "=", "{", "}", "data", "[", ":strategy", "]", "=", "deploy_strategy", "if", "deploy_strategy", "data", "[", ":ports", "]", "=", "parse_ports", "(", "ports_list", ")", "unless", "ports_list", ".", "empty?", "data", "[", ":links", "]", "=", "parse_links", "(", "link_list", ")", "unless", "link_list", ".", "empty?", "data", "[", ":memory", "]", "=", "parse_memory", "(", "memory", ")", "if", "memory", "data", "[", ":memory_swap", "]", "=", "parse_memory", "(", "memory_swap", ")", "if", "memory_swap", "data", "[", ":shm_size", "]", "=", "parse_memory", "(", "shm_size", ")", "if", "shm_size", "data", "[", ":cpus", "]", "=", "cpus", "if", "cpus", "data", "[", ":cpu_shares", "]", "=", "cpu_shares", "if", "cpu_shares", "data", "[", ":affinity", "]", "=", "affinity_list", "unless", "affinity_list", ".", "empty?", "data", "[", ":env", "]", "=", "env_list", "unless", "env_list", ".", "empty?", "data", "[", ":secrets", "]", "=", "parse_secrets", "(", "secret_list", ")", "unless", "secret_list", ".", "empty?", "data", "[", ":container_count", "]", "=", "instances", "if", "instances", "data", "[", ":cmd", "]", "=", "Shellwords", ".", "split", "(", "cmd", ")", "if", "cmd", "data", "[", ":user", "]", "=", "user", "if", "user", "data", "[", ":image", "]", "=", "parse_image", "(", "image", ")", "if", "image", "data", "[", ":privileged", "]", "=", "privileged?", "data", "[", ":cap_add", "]", "=", "cap_add_list", "if", "cap_add_list", "data", "[", ":cap_drop", "]", "=", "cap_drop_list", "if", "cap_drop_list", "data", "[", ":net", "]", "=", "net", "if", "net", "data", "[", ":log_driver", "]", "=", "log_driver", "if", "log_driver", "data", "[", ":log_opts", "]", "=", "parse_log_opts", "(", "log_opt_list", ")", "if", "log_opt_list", "deploy_opts", "=", "parse_deploy_opts", "data", "[", ":deploy_opts", "]", "=", "deploy_opts", "unless", "deploy_opts", ".", "empty?", "health_check", "=", "parse_health_check", "data", "[", ":health_check", "]", "=", "health_check", "unless", "health_check", ".", "empty?", "data", "[", ":pid", "]", "=", "pid", "if", "pid", "data", "[", ":stop_signal", "]", "=", "stop_signal", "if", "stop_signal", "data", "[", ":stop_grace_period", "]", "=", "stop_timeout", "if", "stop_timeout", "data", "end" ]
parse given options to hash @return [Hash]
[ "parse", "given", "options", "to", "hash" ]
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/cli/services/update_command.rb#L61-L92
16,692
kontena/kontena
cli/lib/kontena/cli/helpers/time_helper.rb
Kontena::Cli::Helpers.TimeHelper.time_since
def time_since(time, terse: false) return '' if time.nil? || time.empty? dt = Time.now - Time.parse(time) dt_s = dt.to_i dt_m, dt_s = dt_s / 60, dt_s % 60 dt_h, dt_m = dt_m / 60, dt_m % 60 dt_d, dt_h = dt_h / 60, dt_h % 60 parts = [] parts << "%dd" % dt_d if dt_d > 0 parts << "%dh" % dt_h if dt_h > 0 parts << "%dm" % dt_m if dt_m > 0 parts << "%ds" % dt_s if terse return parts.first else return parts.join('') end end
ruby
def time_since(time, terse: false) return '' if time.nil? || time.empty? dt = Time.now - Time.parse(time) dt_s = dt.to_i dt_m, dt_s = dt_s / 60, dt_s % 60 dt_h, dt_m = dt_m / 60, dt_m % 60 dt_d, dt_h = dt_h / 60, dt_h % 60 parts = [] parts << "%dd" % dt_d if dt_d > 0 parts << "%dh" % dt_h if dt_h > 0 parts << "%dm" % dt_m if dt_m > 0 parts << "%ds" % dt_s if terse return parts.first else return parts.join('') end end
[ "def", "time_since", "(", "time", ",", "terse", ":", "false", ")", "return", "''", "if", "time", ".", "nil?", "||", "time", ".", "empty?", "dt", "=", "Time", ".", "now", "-", "Time", ".", "parse", "(", "time", ")", "dt_s", "=", "dt", ".", "to_i", "dt_m", ",", "dt_s", "=", "dt_s", "/", "60", ",", "dt_s", "%", "60", "dt_h", ",", "dt_m", "=", "dt_m", "/", "60", ",", "dt_m", "%", "60", "dt_d", ",", "dt_h", "=", "dt_h", "/", "60", ",", "dt_h", "%", "60", "parts", "=", "[", "]", "parts", "<<", "\"%dd\"", "%", "dt_d", "if", "dt_d", ">", "0", "parts", "<<", "\"%dh\"", "%", "dt_h", "if", "dt_h", ">", "0", "parts", "<<", "\"%dm\"", "%", "dt_m", "if", "dt_m", ">", "0", "parts", "<<", "\"%ds\"", "%", "dt_s", "if", "terse", "return", "parts", ".", "first", "else", "return", "parts", ".", "join", "(", "''", ")", "end", "end" ]
Return an approximation of how long ago the given time was. @param time [String] @param terse [Boolean] very terse output (2-3 chars wide)
[ "Return", "an", "approximation", "of", "how", "long", "ago", "the", "given", "time", "was", "." ]
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/cli/helpers/time_helper.rb#L6-L27
16,693
kontena/kontena
agent/lib/kontena/websocket_client.rb
Kontena.WebsocketClient.connect!
def connect! info "connecting to master at #{@api_uri}" headers = { 'Kontena-Node-Id' => @node_id.to_s, 'Kontena-Node-Name' => @node_name, 'Kontena-Version' => Kontena::Agent::VERSION, 'Kontena-Node-Labels' => @node_labels.join(','), 'Kontena-Connected-At' => Time.now.utc.strftime(STRFTIME), } if @node_token headers['Kontena-Node-Token'] = @node_token.to_s elsif @grid_token headers['Kontena-Grid-Token'] = @grid_token.to_s else fail "Missing grid, node token" end @ws = Kontena::Websocket::Client.new(@api_uri, headers: headers, ssl_params: @ssl_params, ssl_hostname: @ssl_hostname, connect_timeout: CONNECT_TIMEOUT, open_timeout: OPEN_TIMEOUT, ping_interval: PING_INTERVAL, ping_timeout: PING_TIMEOUT, close_timeout: CLOSE_TIMEOUT, ) async.connect_client @ws publish('websocket:connect', nil) rescue => exc error exc reconnect! end
ruby
def connect! info "connecting to master at #{@api_uri}" headers = { 'Kontena-Node-Id' => @node_id.to_s, 'Kontena-Node-Name' => @node_name, 'Kontena-Version' => Kontena::Agent::VERSION, 'Kontena-Node-Labels' => @node_labels.join(','), 'Kontena-Connected-At' => Time.now.utc.strftime(STRFTIME), } if @node_token headers['Kontena-Node-Token'] = @node_token.to_s elsif @grid_token headers['Kontena-Grid-Token'] = @grid_token.to_s else fail "Missing grid, node token" end @ws = Kontena::Websocket::Client.new(@api_uri, headers: headers, ssl_params: @ssl_params, ssl_hostname: @ssl_hostname, connect_timeout: CONNECT_TIMEOUT, open_timeout: OPEN_TIMEOUT, ping_interval: PING_INTERVAL, ping_timeout: PING_TIMEOUT, close_timeout: CLOSE_TIMEOUT, ) async.connect_client @ws publish('websocket:connect', nil) rescue => exc error exc reconnect! end
[ "def", "connect!", "info", "\"connecting to master at #{@api_uri}\"", "headers", "=", "{", "'Kontena-Node-Id'", "=>", "@node_id", ".", "to_s", ",", "'Kontena-Node-Name'", "=>", "@node_name", ",", "'Kontena-Version'", "=>", "Kontena", "::", "Agent", "::", "VERSION", ",", "'Kontena-Node-Labels'", "=>", "@node_labels", ".", "join", "(", "','", ")", ",", "'Kontena-Connected-At'", "=>", "Time", ".", "now", ".", "utc", ".", "strftime", "(", "STRFTIME", ")", ",", "}", "if", "@node_token", "headers", "[", "'Kontena-Node-Token'", "]", "=", "@node_token", ".", "to_s", "elsif", "@grid_token", "headers", "[", "'Kontena-Grid-Token'", "]", "=", "@grid_token", ".", "to_s", "else", "fail", "\"Missing grid, node token\"", "end", "@ws", "=", "Kontena", "::", "Websocket", "::", "Client", ".", "new", "(", "@api_uri", ",", "headers", ":", "headers", ",", "ssl_params", ":", "@ssl_params", ",", "ssl_hostname", ":", "@ssl_hostname", ",", "connect_timeout", ":", "CONNECT_TIMEOUT", ",", "open_timeout", ":", "OPEN_TIMEOUT", ",", "ping_interval", ":", "PING_INTERVAL", ",", "ping_timeout", ":", "PING_TIMEOUT", ",", "close_timeout", ":", "CLOSE_TIMEOUT", ",", ")", "async", ".", "connect_client", "@ws", "publish", "(", "'websocket:connect'", ",", "nil", ")", "rescue", "=>", "exc", "error", "exc", "reconnect!", "end" ]
Connect to server, and start connect_client task Calls reconnect! on errors
[ "Connect", "to", "server", "and", "start", "connect_client", "task" ]
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/websocket_client.rb#L113-L149
16,694
kontena/kontena
agent/lib/kontena/websocket_client.rb
Kontena.WebsocketClient.send_message
def send_message(msg) ws.send(msg) rescue => exc warn exc abort exc end
ruby
def send_message(msg) ws.send(msg) rescue => exc warn exc abort exc end
[ "def", "send_message", "(", "msg", ")", "ws", ".", "send", "(", "msg", ")", "rescue", "=>", "exc", "warn", "exc", "abort", "exc", "end" ]
Called from RpcServer, does not crash the Actor on errors. @param [String, Array] msg @raise [RuntimeError] not connected
[ "Called", "from", "RpcServer", "does", "not", "crash", "the", "Actor", "on", "errors", "." ]
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/websocket_client.rb#L265-L270
16,695
kontena/kontena
agent/lib/kontena/websocket_client.rb
Kontena.WebsocketClient.on_error
def on_error(exc) case exc when Kontena::Websocket::SSLVerifyError if exc.cert error "unable to connect to SSL server with KONTENA_SSL_VERIFY=true: #{exc} (subject #{exc.subject}, issuer #{exc.issuer})" else error "unable to connect to SSL server with KONTENA_SSL_VERIFY=true: #{exc}" end when Kontena::Websocket::SSLConnectError error "unable to connect to SSL server: #{exc}" when Kontena::Websocket::ConnectError error "unable to connect to server: #{exc}" when Kontena::Websocket::ProtocolError error "unexpected response from server, check url: #{exc}" else error "websocket error: #{exc}" end end
ruby
def on_error(exc) case exc when Kontena::Websocket::SSLVerifyError if exc.cert error "unable to connect to SSL server with KONTENA_SSL_VERIFY=true: #{exc} (subject #{exc.subject}, issuer #{exc.issuer})" else error "unable to connect to SSL server with KONTENA_SSL_VERIFY=true: #{exc}" end when Kontena::Websocket::SSLConnectError error "unable to connect to SSL server: #{exc}" when Kontena::Websocket::ConnectError error "unable to connect to server: #{exc}" when Kontena::Websocket::ProtocolError error "unexpected response from server, check url: #{exc}" else error "websocket error: #{exc}" end end
[ "def", "on_error", "(", "exc", ")", "case", "exc", "when", "Kontena", "::", "Websocket", "::", "SSLVerifyError", "if", "exc", ".", "cert", "error", "\"unable to connect to SSL server with KONTENA_SSL_VERIFY=true: #{exc} (subject #{exc.subject}, issuer #{exc.issuer})\"", "else", "error", "\"unable to connect to SSL server with KONTENA_SSL_VERIFY=true: #{exc}\"", "end", "when", "Kontena", "::", "Websocket", "::", "SSLConnectError", "error", "\"unable to connect to SSL server: #{exc}\"", "when", "Kontena", "::", "Websocket", "::", "ConnectError", "error", "\"unable to connect to server: #{exc}\"", "when", "Kontena", "::", "Websocket", "::", "ProtocolError", "error", "\"unexpected response from server, check url: #{exc}\"", "else", "error", "\"websocket error: #{exc}\"", "end", "end" ]
Websocket connection failed @param exc [Kontena::Websocket::Error]
[ "Websocket", "connection", "failed" ]
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/websocket_client.rb#L314-L335
16,696
kontena/kontena
agent/lib/kontena/websocket_client.rb
Kontena.WebsocketClient.on_close
def on_close(code, reason) debug "Server closed connection with code #{code}: #{reason}" case code when 4001 handle_invalid_token when 4010 handle_invalid_version(reason) when 4040, 4041 handle_invalid_connection(reason) else warn "connection closed with code #{code}: #{reason}" end end
ruby
def on_close(code, reason) debug "Server closed connection with code #{code}: #{reason}" case code when 4001 handle_invalid_token when 4010 handle_invalid_version(reason) when 4040, 4041 handle_invalid_connection(reason) else warn "connection closed with code #{code}: #{reason}" end end
[ "def", "on_close", "(", "code", ",", "reason", ")", "debug", "\"Server closed connection with code #{code}: #{reason}\"", "case", "code", "when", "4001", "handle_invalid_token", "when", "4010", "handle_invalid_version", "(", "reason", ")", "when", "4040", ",", "4041", "handle_invalid_connection", "(", "reason", ")", "else", "warn", "\"connection closed with code #{code}: #{reason}\"", "end", "end" ]
Server closed websocket connection @param code [Integer] @param reason [String]
[ "Server", "closed", "websocket", "connection" ]
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/websocket_client.rb#L341-L354
16,697
kontena/kontena
cli/lib/kontena/cli/subcommand_loader.rb
Kontena::Cli.SubcommandLoader.symbolize_path
def symbolize_path(path) path.gsub(/.*\/cli\//, '').split('/').map do |path_part| path_part.split('_').map{ |e| e.capitalize }.join end.map(&:to_sym) end
ruby
def symbolize_path(path) path.gsub(/.*\/cli\//, '').split('/').map do |path_part| path_part.split('_').map{ |e| e.capitalize }.join end.map(&:to_sym) end
[ "def", "symbolize_path", "(", "path", ")", "path", ".", "gsub", "(", "/", "\\/", "\\/", "/", ",", "''", ")", ".", "split", "(", "'/'", ")", ".", "map", "do", "|", "path_part", "|", "path_part", ".", "split", "(", "'_'", ")", ".", "map", "{", "|", "e", "|", "e", ".", "capitalize", "}", ".", "join", "end", ".", "map", "(", ":to_sym", ")", "end" ]
Create a subcommand loader instance @param [String] path path to command definition Takes something like /foo/bar/cli/master/foo_coimmand and returns [:Master, :FooCommand] @param path [String] @return [Array<Symbol>]
[ "Create", "a", "subcommand", "loader", "instance" ]
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/cli/subcommand_loader.rb#L17-L21
16,698
kontena/kontena
cli/lib/kontena/client.rb
Kontena.Client.authentication_ok?
def authentication_ok?(token_verify_path) return false unless token return false unless token['access_token'] return false unless token_verify_path final_path = token_verify_path.gsub(/\:access\_token/, token['access_token']) debug { "Requesting user info from #{final_path}" } request(path: final_path) true rescue => ex error { "Authentication verification exception" } error { ex } false end
ruby
def authentication_ok?(token_verify_path) return false unless token return false unless token['access_token'] return false unless token_verify_path final_path = token_verify_path.gsub(/\:access\_token/, token['access_token']) debug { "Requesting user info from #{final_path}" } request(path: final_path) true rescue => ex error { "Authentication verification exception" } error { ex } false end
[ "def", "authentication_ok?", "(", "token_verify_path", ")", "return", "false", "unless", "token", "return", "false", "unless", "token", "[", "'access_token'", "]", "return", "false", "unless", "token_verify_path", "final_path", "=", "token_verify_path", ".", "gsub", "(", "/", "\\:", "\\_", "/", ",", "token", "[", "'access_token'", "]", ")", "debug", "{", "\"Requesting user info from #{final_path}\"", "}", "request", "(", "path", ":", "final_path", ")", "true", "rescue", "=>", "ex", "error", "{", "\"Authentication verification exception\"", "}", "error", "{", "ex", "}", "false", "end" ]
Requests path supplied as argument and returns true if the request was a success. For checking if the current authentication is valid. @param [String] token_verify_path a path that requires authentication @return [Boolean]
[ "Requests", "path", "supplied", "as", "argument", "and", "returns", "true", "if", "the", "request", "was", "a", "success", ".", "For", "checking", "if", "the", "current", "authentication", "is", "valid", "." ]
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/client.rb#L130-L143
16,699
kontena/kontena
cli/lib/kontena/client.rb
Kontena.Client.exchange_code
def exchange_code(code) return nil unless token_account return nil unless token_account['token_endpoint'] response = request( http_method: token_account['token_method'].downcase.to_sym, path: token_account['token_endpoint'], headers: { CONTENT_TYPE => token_account['token_post_content_type'] }, body: { 'grant_type' => 'authorization_code', 'code' => code, 'client_id' => Kontena::Client::CLIENT_ID, 'client_secret' => Kontena::Client::CLIENT_SECRET }, expects: [200,201], auth: false ) response['expires_at'] ||= in_to_at(response['expires_in']) response end
ruby
def exchange_code(code) return nil unless token_account return nil unless token_account['token_endpoint'] response = request( http_method: token_account['token_method'].downcase.to_sym, path: token_account['token_endpoint'], headers: { CONTENT_TYPE => token_account['token_post_content_type'] }, body: { 'grant_type' => 'authorization_code', 'code' => code, 'client_id' => Kontena::Client::CLIENT_ID, 'client_secret' => Kontena::Client::CLIENT_SECRET }, expects: [200,201], auth: false ) response['expires_at'] ||= in_to_at(response['expires_in']) response end
[ "def", "exchange_code", "(", "code", ")", "return", "nil", "unless", "token_account", "return", "nil", "unless", "token_account", "[", "'token_endpoint'", "]", "response", "=", "request", "(", "http_method", ":", "token_account", "[", "'token_method'", "]", ".", "downcase", ".", "to_sym", ",", "path", ":", "token_account", "[", "'token_endpoint'", "]", ",", "headers", ":", "{", "CONTENT_TYPE", "=>", "token_account", "[", "'token_post_content_type'", "]", "}", ",", "body", ":", "{", "'grant_type'", "=>", "'authorization_code'", ",", "'code'", "=>", "code", ",", "'client_id'", "=>", "Kontena", "::", "Client", "::", "CLIENT_ID", ",", "'client_secret'", "=>", "Kontena", "::", "Client", "::", "CLIENT_SECRET", "}", ",", "expects", ":", "[", "200", ",", "201", "]", ",", "auth", ":", "false", ")", "response", "[", "'expires_at'", "]", "||=", "in_to_at", "(", "response", "[", "'expires_in'", "]", ")", "response", "end" ]
Calls the code exchange endpoint in token's config to exchange an authorization_code to a access_token
[ "Calls", "the", "code", "exchange", "endpoint", "in", "token", "s", "config", "to", "exchange", "an", "authorization_code", "to", "a", "access_token" ]
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/client.rb#L147-L166