repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/lib/zabbixapi/classes/configurations.rb
lib/zabbixapi/classes/configurations.rb
class ZabbixApi class Configurations < Basic # @return [Boolean] def array_flag true end # The method name used for interacting with Configurations via Zabbix API # # @return [String] def method_name 'configuration' end # The id field name used for identifying specific Configuration objects via Zabbix API # # @return [String] def identify 'host' end # Export configuration data using Zabbix API # # @param data [Hash] # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Hash] def export(data) @client.api_request(method: 'configuration.export', params: data) end # Import configuration data using Zabbix API # # @param data [Hash] # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Hash] def import(data) @client.api_request(method: 'configuration.import', params: data) end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/lib/zabbixapi/classes/maintenance.rb
lib/zabbixapi/classes/maintenance.rb
class ZabbixApi class Maintenance < Basic # The method name used for interacting with Maintenances via Zabbix API # # @return [String] def method_name 'maintenance' end # The id field name used for identifying specific Maintenance objects via Zabbix API # # @return [String] def identify 'name' end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/lib/zabbixapi/classes/problems.rb
lib/zabbixapi/classes/problems.rb
class ZabbixApi class Problems < Basic # The method name used for interacting with Hosts via Zabbix API # # @return [String] def method_name 'problem' end # The id field name used for identifying specific Problem objects via Zabbix API # # @return [String] def identify 'name' end # The key field name used for Problem objects via Zabbix API # However, Problem object does not have a unique identifier # # @return [String] def key 'problemid' end # Returns the object's plural id field name (identify) based on key # However, Problem object does not have a unique identifier # # @return [String] def keys 'problemids' end # Dump Problem object data by key from Zabbix API # # @param data [Hash] Should include desired object's key and value # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Hash] def dump_by_id(data) log "[DEBUG] Call dump_by_id with parameters: #{data.inspect}" @client.api_request( method: 'problem.get', params: { filter: { identify.to_sym => data[identify.to_sym] }, output: 'extend' } ) end # Get full/extended Problem data from Zabbix API # # @param data [Hash] Should include object's id field name (identify) and id value # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Hash] def get_full_data(data) log "[DEBUG] Call get_full_data with parameters: #{data.inspect}" data = symbolize_keys(data) @client.api_request( method: "#{method_name}.get", params: { filter: { identify.to_sym => data[identify.to_sym] }, eventids: data[:eventids] || nil, groupids: data[:groupids] || nil, hostids: data[:hostids] || nil, objectids: data[:objectids] || nil, applicationids: data[:applicationids] || nil, tags: data[:tags] || nil, time_from: data[:time_from] || nil, time_till: data[:time_till] || nil, eventid_from: data[:eventid_from] || nil, eventid_till: data[:eventid_till] || nil, recent: data[:recent] || false, sortfield: data[:sortfield] || ['eventid'], sortorder: data[:sortorder] || 'DESC', countOutput: data[:countOutput] || nil, output: 'extend', selectAcknowledges: 'extend', selectTags: 'extend', selectSuppressionData: 'extend' } ) end # Get full/extended Zabbix data for Problem objects from API # # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Array<Hash>] Array of matching objects def all get_full_data({}) end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/lib/zabbixapi/classes/items.rb
lib/zabbixapi/classes/items.rb
class ZabbixApi class Items < Basic # The method name used for interacting with Items via Zabbix API # # @return [String] def method_name 'item' end # The id field name used for identifying specific Item objects via Zabbix API # # @return [String] def identify 'name' end # The default options used when creating Item objects via Zabbix API # # @return [Hash] def default_options { name: nil, key_: nil, hostid: nil, delay: 60, history: 3600, status: 0, type: 7, snmp_community: '', snmp_oid: '', value_type: 3, data_type: 0, trapper_hosts: 'localhost', snmp_port: 161, units: '', multiplier: 0, delta: 0, snmpv3_securityname: '', snmpv3_securitylevel: 0, snmpv3_authpassphrase: '', snmpv3_privpassphrase: '', formula: 0, trends: 86400, logtimefmt: '', valuemapid: 0, delay_flex: '', authtype: 0, username: '', password: '', publickey: '', privatekey: '', params: '', ipmi_sensor: '' } end # Get or Create Item object using Zabbix API # # @param data [Hash] Needs to include name and hostid to properly identify Items via Zabbix API # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] Zabbix object id def get_or_create(data) log "[DEBUG] Call get_or_create with parameters: #{data.inspect}" unless (id = get_id(name: data[:name], hostid: data[:hostid])) id = create(data) end id end # Create or update Item object using Zabbix API # # @param data [Hash] Needs to include name and hostid to properly identify Items via Zabbix API # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] Zabbix object id def create_or_update(data) itemid = get_id(name: data[:name], hostid: data[:hostid]) itemid ? update(data.merge(itemid: itemid)) : create(data) end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/lib/zabbixapi/classes/errors.rb
lib/zabbixapi/classes/errors.rb
class ZabbixApi class BaseError < RuntimeError attr_accessor :response, :error, :error_message def initialize(message, response = nil) super(message) @response = response set_error! if @response end private def set_error! @error = @response['error'] @error_message = "#{@error['message']}: #{@error['data']}" rescue StandardError @error = nil @error_message = nil end end class ApiError < BaseError end class HttpError < BaseError end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/lib/zabbixapi/classes/applications.rb
lib/zabbixapi/classes/applications.rb
class ZabbixApi class Applications < Basic # The method name used for interacting with Applications via Zabbix API # # @return [String] def method_name 'application' end # The id field name used for identifying specific Application objects via Zabbix API # # @return [String] def identify 'name' end # Get or Create Application object using Zabbix API # # @param data [Hash] Needs to include name and hostid to properly identify Applications via Zabbix API # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] Zabbix object id def get_or_create(data) log "[DEBUG] Call get_or_create with parameters: #{data.inspect}" unless (id = get_id(name: data[:name], hostid: data[:hostid])) id = create(data) end id end # Create or update Application object using Zabbix API # # @param data [Hash] Needs to include name and hostid to properly identify Applications via Zabbix API # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] Zabbix object id def create_or_update(data) applicationid = get_id(name: data[:name], hostid: data[:hostid]) applicationid ? update(data.merge(applicationid: applicationid)) : create(data) end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/lib/zabbixapi/classes/hostgroups.rb
lib/zabbixapi/classes/hostgroups.rb
class ZabbixApi class HostGroups < Basic # The method name used for interacting with HostGroups via Zabbix API # # @return [String] def method_name 'hostgroup' end # The id field name used for identifying specific HostGroup objects via Zabbix API # # @return [String] def identify 'name' end # The key field name used for HostGroup objects via Zabbix API # # @return [String] def key 'groupid' end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/lib/zabbixapi/classes/proxies.rb
lib/zabbixapi/classes/proxies.rb
class ZabbixApi class Proxies < Basic # The method name used for interacting with Proxies via Zabbix API # # @return [String] def method_name 'proxy' end # The id field name used for identifying specific Proxy objects via Zabbix API # # @return [String] def identify 'name' end # Delete Proxy object using Zabbix API # # @param data [Array] Should include array of proxyid's # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] The Proxy object id that was deleted def delete(data) result = @client.api_request(method: 'proxy.delete', params: data) result.empty? ? nil : result['proxyids'][0].to_i end # Check if a Proxy object is readable using Zabbix API # # @param data [Array] Should include array of proxyid's # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Boolean] Returns true if the given proxies are readable def isreadable(data) @client.api_request(method: 'proxy.isreadable', params: data) end # Check if a Proxy object is writable using Zabbix API # # @param data [Array] Should include array of proxyid's # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Boolean] Returns true if the given proxies are writable def iswritable(data) @client.api_request(method: 'proxy.iswritable', params: data) end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/lib/zabbixapi/classes/templates.rb
lib/zabbixapi/classes/templates.rb
class ZabbixApi class Templates < Basic # The method name used for interacting with Templates via Zabbix API # # @return [String] def method_name 'template' end # The id field name used for identifying specific Template objects via Zabbix API # # @return [String] def identify 'host' end # Delete Template object using Zabbix API # # @param data [Array] Should include array of templateid's # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] The Template object id that was deleted def delete(data) result = @client.api_request(method: 'template.delete', params: [data]) result.empty? ? nil : result['templateids'][0].to_i end # Get Template ids for Host from Zabbix API # # @param data [Hash] Should include host value to query for matching templates # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Array] Returns array of Template ids def get_ids_by_host(data) @client.api_request(method: 'template.get', params: data).map do |tmpl| tmpl['templateid'] end end # Get or Create Template object using Zabbix API # # @param data [Hash] Needs to include host to properly identify Templates via Zabbix API # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] Zabbix object id def get_or_create(data) unless (templateid = get_id(host: data[:host])) templateid = create(data) end templateid end # Mass update Templates for Hosts using Zabbix API # # @param data [Hash] Should include hosts_id array and templates_id array # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Boolean] def mass_update(data) result = @client.api_request( method: 'template.massUpdate', params: { hosts: data[:hosts_id].map { |t| { hostid: t } }, templates: data[:templates_id].map { |t| { templateid: t } } } ) result.empty? ? false : true end # Mass add Templates to Hosts using Zabbix API # # @param data [Hash] Should include hosts_id array and templates_id array # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Boolean] def mass_add(data) result = @client.api_request( method: 'template.massAdd', params: { hosts: data[:hosts_id].map { |t| { hostid: t } }, templates: data[:templates_id].map { |t| { templateid: t } } } ) result.empty? ? false : true end # Mass remove Templates to Hosts using Zabbix API # # @param data [Hash] Should include hosts_id array and templates_id array # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Boolean] def mass_remove(data) result = @client.api_request( method: 'template.massRemove', params: { hostids: data[:hosts_id], templateids: data[:templates_id], groupids: data[:group_id], force: 1 } ) result.empty? ? false : true end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/lib/zabbixapi/classes/roles.rb
lib/zabbixapi/classes/roles.rb
class ZabbixApi class Roles < Basic # The method name used for interacting with Role via Zabbix API # # @return [String] def method_name 'role' end # The key field name used for Role objects via Zabbix API # # @return [String] def key 'roleid' end # The id field name used for identifying specific Role objects via Zabbix API # # @return [String] def identify 'name' end # Set permissions for usergroup using Zabbix API # # @param data [Hash] Needs to include usrgrpids and hostgroupids along with permissions to set # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] Zabbix object id (usergroup) def rules(data) rules = data[:rules] || 2 result = @client.api_request( method: 'role.update', params: { roleid: data[:roleid], rules: data[:hostgroupids].map { |t| { permission: permission, id: t } } } ) result ? result['usrgrpids'][0].to_i : nil end # Add users to usergroup using Zabbix API # # @deprecated Zabbix has removed massAdd in favor of update. # @param data [Hash] Needs to include userids and usrgrpids to mass add users to groups # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] Zabbix object id (usergroup) def add_user(data) update_users(data) end # Dump Role object data by key from Zabbix API # # @param data [Hash] Should include desired object's key and value # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Hash] def dump_by_id(data) log "[DEBUG] Call dump_by_id with parameters: #{data.inspect}" @client.api_request( method: 'role.get', params: { output: 'extend', selectRules: 'extend', roleids: data[:id] } ) end # Get Role ids by Role Name from Zabbix API # # @param data [Hash] Should include host value to query for matching graphs # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Array] Returns array of Graph ids def get_ids_by_name(data) result = @client.api_request( method: 'role.get', params: { filter: { name: data[:name] }, output: 'extend' } ) result.map do |rule| rule['roleid'] end.compact end # Update users in Userroles using Zabbix API # # @param data [Hash] Needs to include userids and usrgrpids to mass update users in groups # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] Zabbix object id (usergroup) def update_users(data) user_groups = data[:usrgrpids].map do |t| { usrgrpid: t, userids: data[:userids], } end result = @client.api_request( method: 'usergroup.update', params: user_groups, ) result ? result['usrgrpids'][0].to_i : nil end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/lib/zabbixapi/classes/unusable.rb
lib/zabbixapi/classes/unusable.rb
class ZabbixApi class Triggers < Basic def create_or_update(data) log "[DEBUG] Call create_or_update with parameters: #{data.inspect}" get_or_create(data) end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/lib/zabbixapi/classes/graphs.rb
lib/zabbixapi/classes/graphs.rb
class ZabbixApi class Graphs < Basic # The method name used for interacting with Graphs via Zabbix API # # @return [String] def method_name 'graph' end # The id field name used for identifying specific Graph objects via Zabbix API # # @return [String] def identify 'name' end # Get full/extended Graph data from Zabbix API # # @param data [Hash] Should include object's id field name (identify) and id value # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Hash] def get_full_data(data) log "[DEBUG] Call get_full_data with parameters: #{data.inspect}" @client.api_request( method: "#{method_name}.get", params: { search: { identify.to_sym => data[identify.to_sym] }, output: 'extend' } ) end # Get Graph ids for Host from Zabbix API # # @param data [Hash] Should include host value to query for matching graphs # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Array] Returns array of Graph ids def get_ids_by_host(data) result = @client.api_request( method: 'graph.get', params: { filter: { host: data[:host] }, output: 'extend' } ) result.map do |graph| num = graph['graphid'] name = graph['name'] filter = data[:filter] num if filter.nil? || /#{filter}/ =~ name end.compact end # Get Graph Item object using Zabbix API # # @param data [Hash] Needs to include graphids to properly identify Graph Items via Zabbix API # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Hash] def get_items(data) @client.api_request( method: 'graphitem.get', params: { graphids: [data], output: 'extend' } ) end # Get or Create Graph object using Zabbix API # # @param data [Hash] Needs to include name and templateid to properly identify Graphs via Zabbix API # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] Zabbix object id def get_or_create(data) log "[DEBUG] Call get_or_create with parameters: #{data.inspect}" unless (id = get_id(name: data[:name], templateid: data[:templateid])) id = create(data) end id end # Create or update Graph object using Zabbix API # # @param data [Hash] Needs to include name and templateid to properly identify Graphs via Zabbix API # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] Zabbix object id def create_or_update(data) graphid = get_id(name: data[:name], templateid: data[:templateid]) graphid ? _update(data.merge(graphid: graphid)) : create(data) end def _update(data) data.delete(:name) update(data) end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/lib/zabbixapi/classes/httptests.rb
lib/zabbixapi/classes/httptests.rb
class ZabbixApi class HttpTests < Basic # The method name used for interacting with HttpTests via Zabbix API # # @return [String] def method_name 'httptest' end # The id field name used for identifying specific HttpTest objects via Zabbix API # # @return [String] def identify 'name' end # The default options used when creating HttpTest objects via Zabbix API # # @return [Hash] def default_options { hostid: nil, name: nil, steps: [] } end # Get or Create HttpTest object using Zabbix API # # @param data [Hash] Needs to include name and hostid to properly identify HttpTests via Zabbix API # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] Zabbix object id def get_or_create(data) log "[DEBUG] Call get_or_create with parameters: #{data.inspect}" unless (id = get_id(name: data[:name], hostid: data[:hostid])) id = create(data) end id end # Create or update HttpTest object using Zabbix API # # @param data [Hash] Needs to include name and hostid to properly identify HttpTests via Zabbix API # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] Zabbix object id def create_or_update(data) httptestid = get_id(name: data[:name], hostid: data[:hostid]) httptestid ? update(data.merge(httptestid: httptestid)) : create(data) end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/lib/zabbixapi/classes/scripts.rb
lib/zabbixapi/classes/scripts.rb
class ZabbixApi class Scripts < Basic def method_name 'script' end # The id field name used for identifying specific Screen objects via Zabbix API # # @return [String] def identify 'name' end # Submits a request to the zabbix api # data - A Hash containing the scriptid and hostid # # Example: # execute({ scriptid: '12', hostid: '32 }) # # Returns nothing def execute(data) @client.api_request( method: 'script.execute', params: { scriptid: data[:scriptid], hostid: data[:hostid] } ) end def getscriptsbyhost(data) @client.api_request(method: 'script.getscriptsbyhosts', params: data) end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/lib/zabbixapi/classes/drules.rb
lib/zabbixapi/classes/drules.rb
class ZabbixApi class Drules < Basic # The method name used for interacting with Drules via Zabbix API # # @return [String] def method_name 'drule' end # The id field name used for identifying specific Drule objects via Zabbix API # # @return [String] def identify 'name' end # The default options used when creating Drule objects via Zabbix API # # @return [Hash] def default_options { name: nil, iprange: nil, delay: 3600, status: 0, } end # Get or Create Drule object using Zabbix API # # @param data [Hash] Needs to include name to properly identify Drule via Zabbix API # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] Zabbix object id def get_or_create(data) log "[DEBUG] Call get_or_create with parameters: #{data.inspect}" unless (id = get_id(name: data[:name])) id = create(data) end id end # Create or update Drule object using Zabbix API # # @param data [Hash] Needs to include name to properly identify Drules via Zabbix API # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] Zabbix object id def create_or_update(data) druleid = get_id(name: data[:name]) druleid ? update(data.merge(druleid: druleid)) : create(data) end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/lib/zabbixapi/classes/triggers.rb
lib/zabbixapi/classes/triggers.rb
class ZabbixApi class Triggers < Basic # The method name used for interacting with Triggers via Zabbix API # # @return [String] def method_name 'trigger' end # The id field name used for identifying specific Trigger objects via Zabbix API # # @return [String] def identify 'description' end # Dump Trigger object data by key from Zabbix API # # @param data [Hash] Should include desired object's key and value # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Hash] def dump_by_id(data) log "[DEBUG] Call dump_by_id with parameters: #{data.inspect}" @client.api_request( method: 'trigger.get', params: { filter: { key.to_sym => data[key.to_sym] }, output: 'extend', select_items: 'extend', select_functions: 'extend' } ) end # Safely update Trigger object using Zabbix API by deleting and replacing trigger # # @param data [Hash] Needs to include description and hostid to properly identify Triggers via Zabbix API # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] Zabbix object id def safe_update(data) log "[DEBUG] Call safe_update with parameters: #{data.inspect}" dump = {} item_id = data[key.to_sym].to_i dump_by_id(key.to_sym => data[key.to_sym]).each do |item| dump = symbolize_keys(item) if item[key].to_i == data[key.to_sym].to_i end expression = dump[:items][0][:key_] + '.' + dump[:functions][0][:function] + '(' + dump[:functions][0][:parameter] + ')' dump[:expression] = dump[:expression].gsub(/\{(\d*)\}/, "{#{expression}}") # TODO: ugly regexp dump.delete(:functions) dump.delete(:items) old_expression = data[:expression] data[:expression] = data[:expression].gsub(/\{.*\:/, '{') # TODO: ugly regexp data.delete(:templateid) log "[DEBUG] expression: #{dump[:expression]}\n data: #{data[:expression]}" if hash_equals?(dump, data) log "[DEBUG] Equal keys #{dump} and #{data}, skip safe_update" item_id else data[:expression] = old_expression # disable old trigger log '[DEBUG] disable :' + @client.api_request(method: "#{method_name}.update", params: [{ triggerid: data[:triggerid], status: '1' }]).inspect # create new trigger data.delete(:triggerid) create(data) end end # Get or Create Trigger object using Zabbix API # # @param data [Hash] Needs to include description and hostid to properly identify Triggers via Zabbix API # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] Zabbix object id def get_or_create(data) log "[DEBUG] Call get_or_create with parameters: #{data.inspect}" unless (id = get_id(description: data[:description], hostid: data[:hostid])) id = create(data) end id end # Create or update Trigger object using Zabbix API # # @param data [Hash] Needs to include description and hostid to properly identify Triggers via Zabbix API # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] Zabbix object id def create_or_update(data) triggerid = get_id(description: data[:description], hostid: data[:hostid]) triggerid ? update(data.merge(triggerid: triggerid)) : create(data) end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/lib/zabbixapi/classes/server.rb
lib/zabbixapi/classes/server.rb
class ZabbixApi class Server # @return [String] attr_reader :version # Initializes a new Server object with ZabbixApi Client and fetches Zabbix Server API version # # @param client [ZabbixApi::Client] # @return [ZabbixApi::Client] # @return [String] Zabbix API version number def initialize(client) @client = client @version = @client.api_version() end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/lib/zabbixapi/classes/mediatypes.rb
lib/zabbixapi/classes/mediatypes.rb
class ZabbixApi class Mediatypes < Basic # The method name used for interacting with MediaTypes via Zabbix API # # @return [String] def method_name 'mediatype' end # The id field name used for identifying specific MediaType objects via Zabbix API # # @return [String] def identify 'name' end # The default options used when creating MediaType objects via Zabbix API # # @return [Hash] def default_options { name: '', # Name description: '', # Description type: 0, # 0 - Email, 1 - External script, 2 - SMS, 3 - Jabber, 100 - EzTexting smtp_server: '', smtp_helo: '', smtp_email: '', # Email address of Zabbix server exec_path: '', # Name of external script gsm_modem: '', # Serial device name of GSM modem username: '', # Jabber user name used by Zabbix server passwd: '' # Jabber password used by Zabbix server } end # def log(message) # STDERR.puts # STDERR.puts message.to_s # STDERR.puts # end # Update MediaType object using API # # @param data [Hash] Should include object's id field name (identify) and id value # @param force [Boolean] Whether to force an object update even if provided data matches Zabbix # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] The object id if a single object is created # @return [Boolean] True/False if multiple objects are created def update(data, force = false) log "[DEBUG] Call update with parameters: #{data.inspect}" if data[key.to_sym].nil? data[key.to_sym] = get_id(data) log "[DEBUG] Enriched data with id: #{data.inspect}" end dump = {} dump_by_id(key.to_sym => data[key.to_sym]).each do |item| dump = symbolize_keys(item) if item[key].to_i == data[key.to_sym].to_i end if hash_equals?(dump, data) && !force log "[DEBUG] Equal keys #{dump} and #{data}, skip update" data[key.to_sym].to_i else data_update = [data] result = @client.api_request(method: "#{method_name}.update", params: data_update) parse_keys result end end # Get MediaType object id from API based on provided data # # @param data [Hash] # @raise [ApiError] Error returned when there is a problem with the Zabbix API call or missing object's id field name (identify). # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] Zabbix object id def get_id(data) log "[DEBUG] Call get_id with parameters: #{data.inspect}" # symbolize keys if the user used string keys instead of symbols data = symbolize_keys(data) if data.key?(identify) # raise an error if identify name was not supplied name = data[identify.to_sym] raise ApiError.new("#{identify} not supplied in call to get_id, #{data} (#{method_name})") if name.nil? result = @client.api_request( method: "#{method_name}.get", params: { filter: {name: name}, output: [key, identify] } ) id = nil result.each { |item| id = item[key].to_i if item[identify] == data[identify.to_sym] } id end # Create or update MediaType object using API # # @param data [Hash] Should include object's id field name (identify) and id value # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] The object id if a single object is created # @return [Boolean] True/False if multiple objects are created def create_or_update(data) log "[DEBUG] Call create_or_update with parameters: #{data.inspect}" id = get_id(identify.to_sym => data[identify.to_sym]) id ? update(data.merge(key.to_sym => id.to_s)) : create(data) end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/lib/zabbixapi/classes/valuemaps.rb
lib/zabbixapi/classes/valuemaps.rb
class ZabbixApi class ValueMaps < Basic # The method name used for interacting with ValueMaps via Zabbix API # # @return [String] def method_name 'valuemap' end # The key field name used for ValueMap objects via Zabbix API # # @return [String] def key 'valuemapid' end # The id field name used for identifying specific ValueMap objects via Zabbix API # # @return [String] def identify 'name' end # Get or Create ValueMap object using Zabbix API # # @param data [Hash] Needs to include valuemapids [List] to properly identify ValueMaps via Zabbix API # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] Zabbix object id def get_or_create(data) log "[DEBUG] Call get_or_create with parameters: #{data.inspect}" unless (id = get_id(valuemapids: data[:valuemapids])) id = create(data) end id end # Create or update Item object using Zabbix API # # @param data [Hash] Needs to include valuemapids to properly identify ValueMaps via Zabbix API # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] Zabbix object id def create_or_update(data) valuemapid = get_id(name: data[:name]) valuemapid ? update(data.merge(valuemapids: [:valuemapid])) : create(data) end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/lib/zabbixapi/classes/hosts.rb
lib/zabbixapi/classes/hosts.rb
class ZabbixApi class Hosts < Basic # The method name used for interacting with Hosts via Zabbix API # # @return [String] def method_name 'host' end # The id field name used for identifying specific Host objects via Zabbix API # # @return [String] def identify 'host' end # Dump Host object data by key from Zabbix API # # @param data [Hash] Should include desired object's key and value # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Hash] def dump_by_id(data) log "[DEBUG] Call dump_by_id with parameters: #{data.inspect}" @client.api_request( method: 'host.get', params: { filter: { key.to_sym => data[key.to_sym] }, output: 'extend', selectHostGroups: 'extend' } ) end # The default options used when creating Host objects via Zabbix API # # @return [Hash] def default_options { host: nil, interfaces: [], status: 0, available: 1, groups: [] } end # Unlink/Remove Templates from Hosts using Zabbix API # # @param data [Hash] Should include hosts_id array and templates_id array # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Boolean] def unlink_templates(data) result = @client.api_request( method: 'host.massRemove', params: { hostids: data[:hosts_id], templates: data[:templates_id] } ) result.empty? ? false : true end # Create or update Host object using Zabbix API # # @param data [Hash] Needs to include host to properly identify Hosts via Zabbix API # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] Zabbix object id def create_or_update(data) hostid = get_id(host: data[:host]) hostid ? update(data.merge(hostid: hostid)) : create(data) end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/lib/zabbixapi/classes/screens.rb
lib/zabbixapi/classes/screens.rb
class ZabbixApi class Screens < Basic # extracted from frontends/php/include/defines.inc.php # SCREEN_RESOURCE_GRAPH => 0, # SCREEN_RESOURCE_SIMPLE_GRAPH => 1, # SCREEN_RESOURCE_MAP => 2, # SCREEN_RESOURCE_PLAIN_TEXT => 3, # SCREEN_RESOURCE_HOSTS_INFO => 4, # SCREEN_RESOURCE_TRIGGERS_INFO => 5, # SCREEN_RESOURCE_SERVER_INFO => 6, # SCREEN_RESOURCE_CLOCK => 7, # SCREEN_RESOURCE_SCREEN => 8, # SCREEN_RESOURCE_TRIGGERS_OVERVIEW => 9, # SCREEN_RESOURCE_DATA_OVERVIEW => 10, # SCREEN_RESOURCE_URL => 11, # SCREEN_RESOURCE_ACTIONS => 12, # SCREEN_RESOURCE_EVENTS => 13, # SCREEN_RESOURCE_HOSTGROUP_TRIGGERS => 14, # SCREEN_RESOURCE_SYSTEM_STATUS => 15, # SCREEN_RESOURCE_HOST_TRIGGERS => 16 # The method name used for interacting with Screens via Zabbix API # # @return [String] def method_name 'screen' end # The id field name used for identifying specific Screen objects via Zabbix API # # @return [String] def identify 'name' end # Delete Screen object using Zabbix API # # @param data [String, Array] Should include id's of the screens to delete # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] Zabbix object id def delete(data) result = @client.api_request(method: 'screen.delete', params: [data]) result.empty? ? nil : result['screenids'][0].to_i end # Get or Create Screen object for Host using Zabbix API # # @param data [Hash] Needs to include screen_name and graphids to properly identify Screens via Zabbix API # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] Zabbix object id def get_or_create_for_host(data) screen_name = data[:screen_name] graphids = data[:graphids] screenitems = [] hsize = data[:hsize] || 3 valign = data[:valign] || 2 halign = data[:halign] || 2 rowspan = data[:rowspan] || 1 colspan = data[:colspan] || 1 height = data[:height] || 320 # default 320 width = data[:width] || 200 # default 200 vsize = data[:vsize] || [1, (graphids.size / hsize).to_i].max screenid = get_id(name: screen_name) unless screenid # Create screen graphids.each_with_index do |graphid, index| screenitems << { resourcetype: 0, resourceid: graphid, x: (index % hsize).to_i, y: (index % graphids.size / hsize).to_i, valign: valign, halign: halign, rowspan: rowspan, colspan: colspan, height: height, width: width } end screenid = create( name: screen_name, hsize: hsize, vsize: vsize, screenitems: screenitems ) end screenid end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/lib/zabbixapi/classes/usergroups.rb
lib/zabbixapi/classes/usergroups.rb
class ZabbixApi class Usergroups < Basic # The method name used for interacting with Usergroups via Zabbix API # # @return [String] def method_name 'usergroup' end # The key field name used for Usergroup objects via Zabbix API # # @return [String] def key 'usrgrpid' end # The id field name used for identifying specific Usergroup objects via Zabbix API # # @return [String] def identify 'name' end # Set permissions for usergroup using Zabbix API # # @param data [Hash] Needs to include usrgrpids and hostgroupids along with permissions to set # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] Zabbix object id (usergroup) def permissions(data) permission = data[:permission] || 2 result = @client.api_request( method: 'usergroup.update', params: { usrgrpid: data[:usrgrpid], rights: data[:hostgroupids].map { |t| { permission: permission, id: t } } } ) result ? result['usrgrpids'][0].to_i : nil end # Add users to usergroup using Zabbix API # # @deprecated Zabbix has removed massAdd in favor of update. # @param data [Hash] Needs to include userids and usrgrpids to mass add users to groups # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] Zabbix object id (usergroup) def add_user(data) update_users(data) end # Update users in usergroups using Zabbix API # # @param data [Hash] Needs to include userids and usrgrpids to mass update users in groups # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] Zabbix object id (usergroup) def update_users(data) user_groups = data[:usrgrpids].map do |t| { usrgrpid: t, userids: data[:userids], } end result = @client.api_request( method: 'usergroup.update', params: user_groups, ) result ? result['usrgrpids'][0].to_i : nil end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/lib/zabbixapi/classes/usermacros.rb
lib/zabbixapi/classes/usermacros.rb
class ZabbixApi class Usermacros < Basic # The id field name used for identifying specific User macro objects via Zabbix API # # @return [String] def identify 'macro' end # The method name used for interacting with User macros via Zabbix API # # @return [String] def method_name 'usermacro' end # Get User macro object id from Zabbix API based on provided data # # @param data [Hash] Needs to include macro to properly identify user macros via Zabbix API # @raise [ApiError] Error returned when there is a problem with the Zabbix API call or missing object's id field name (identify). # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] Zabbix object id def get_id(data) log "[DEBUG] Call get_id with parameters: #{data.inspect}" # symbolize keys if the user used string keys instead of symbols data = symbolize_keys(data) if data.key?(identify) # raise an error if identify name was not supplied name = data[identify.to_sym] raise ApiError.new("#{identify} not supplied in call to get_id") if name.nil? result = request(data, 'usermacro.get', 'hostmacroid') !result.empty? && result[0].key?('hostmacroid') ? result[0]['hostmacroid'].to_i : nil end # Get Global macro object id from Zabbix API based on provided data # # @param data [Hash] Needs to include macro to properly identify global macros via Zabbix API # @raise [ApiError] Error returned when there is a problem with the Zabbix API call or missing object's id field name (identify). # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] Zabbix object id def get_id_global(data) log "[DEBUG] Call get_id_global with parameters: #{data.inspect}" # symbolize keys if the user used string keys instead of symbols data = symbolize_keys(data) if data.key?(identify) # raise an error if identify name was not supplied name = data[identify.to_sym] raise ApiError.new("#{identify} not supplied in call to get_id_global") if name.nil? result = request(data, 'usermacro.get', 'globalmacroid') !result.empty? && result[0].key?('globalmacroid') ? result[0]['globalmacroid'].to_i : nil end # Get full/extended User macro data from Zabbix API # # @param data [Hash] Should include object's id field name (identify) and id value # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Hash] def get_full_data(data) log "[DEBUG] Call get_full_data with parameters: #{data.inspect}" request(data, 'usermacro.get', 'hostmacroid') end # Get full/extended Global macro data from Zabbix API # # @param data [Hash] Should include object's id field name (identify) and id value # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Hash] def get_full_data_global(data) log "[DEBUG] Call get_full_data_global with parameters: #{data.inspect}" request(data, 'usermacro.get', 'globalmacroid') end # Create new User macro object using Zabbix API (with defaults) # # @param data [Hash] Needs to include hostid, macro, and value to create User macro via Zabbix API # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] The object id if a single object is created # @return [Boolean] True/False if multiple objects are created def create(data) request(data, 'usermacro.create', 'hostmacroids') end # Create new Global macro object using Zabbix API (with defaults) # # @param data [Hash] Needs to include hostid, macro, and value to create Global macro via Zabbix API # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] The object id if a single object is created # @return [Boolean] True/False if multiple objects are created def create_global(data) request(data, 'usermacro.createglobal', 'globalmacroids') end # Delete User macro object using Zabbix API # # @param data [Hash] Should include hostmacroid's of User macros to delete # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] The object id if a single object is deleted # @return [Boolean] True/False if multiple objects are deleted def delete(data) data_delete = [data] request(data_delete, 'usermacro.delete', 'hostmacroids') end # Delete Global macro object using Zabbix API # # @param data [Hash] Should include hostmacroid's of Global macros to delete # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] The object id if a single object is deleted # @return [Boolean] True/False if multiple objects are deleted def delete_global(data) data_delete = [data] request(data_delete, 'usermacro.deleteglobal', 'globalmacroids') end # Update User macro object using Zabbix API # # @param data [Hash] Should include object's id field name (identify), id value, and fields to update # @param force [Boolean] Whether to force an object update even if provided data matches Zabbix # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] The object id if a single object is created # @return [Boolean] True/False if multiple objects are created def update(data) request(data, 'usermacro.update', 'hostmacroids') end # Update Global macro object using Zabbix API # # @param data [Hash] Should include object's id field name (identify), id value, and fields to update # @param force [Boolean] Whether to force an object update even if provided data matches Zabbix # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] The object id if a single object is created # @return [Boolean] True/False if multiple objects are created def update_global(data) request(data, 'usermacro.updateglobal', 'globalmacroids') end # Get or Create User macro object using Zabbix API # # @param data [Hash] Needs to include macro and hostid to properly identify User macros via Zabbix API # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] Zabbix object id def get_or_create(data) log "[DEBUG] Call get_or_create with parameters: #{data.inspect}" unless (id = get_id(macro: data[:macro], hostid: data[:hostid])) id = create(data) end id end # Get or Create Global macro object using Zabbix API # # @param data [Hash] Needs to include macro and hostid to properly identify Global macros via Zabbix API # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] Zabbix object id def get_or_create_global(data) log "[DEBUG] Call get_or_create_global with parameters: #{data.inspect}" unless (id = get_id_global(macro: data[:macro], hostid: data[:hostid])) id = create_global(data) end id end # Create or update User macro object using Zabbix API # # @param data [Hash] Needs to include macro and hostid to properly identify User macros via Zabbix API # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] Zabbix object id def create_or_update(data) hostmacroid = get_id(macro: data[:macro], hostid: data[:hostid]) hostmacroid ? update(data.merge(hostmacroid: hostmacroid)) : create(data) end # Create or update Global macro object using Zabbix API # # @param data [Hash] Needs to include macro and hostid to properly identify Global macros via Zabbix API # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] Zabbix object id def create_or_update_global(data) globalmacroid = get_id_global(macro: data[:macro], hostid: data[:hostid]) globalmacroid ? update_global(data.merge(globalmacroid: globalmacroid)) : create_global(data) end private # Custom request method to handle both User and Global macros in one # # @param data [Hash] Needs to include macro and hostid to properly identify Global macros via Zabbix API # @param method [String] Zabbix API method to use for the request # @param result_key [String] Which key to use for parsing results based on User vs Global macros # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] Zabbix object id def request(data, method, result_key) # Zabbix has different result formats for gets vs updates if method.include?('.get') if result_key.include?('global') @client.api_request(method: method, params: { globalmacro: true, filter: data }) else @client.api_request(method: method, params: { filter: data }) end else result = @client.api_request(method: method, params: data) result.key?(result_key) && !result[result_key].empty? ? result[result_key][0].to_i : nil end end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/lib/zabbixapi/classes/proxygroup.rb
lib/zabbixapi/classes/proxygroup.rb
class ZabbixApi class Proxygroup < Basic # The method name used for interacting with Proxygroup via Zabbix API # # @return [String] def method_name 'proxygroup' end # The id field name used for identifying specific Proxygroup objects via Zabbix API # # @return [String] def identify 'name' end # The key field name used for proxygroup objects via Zabbix API # # @return [String] def key 'proxy_groupid' end # Delete Proxygroup object using Zabbix API # # @param data [Array] Should include array of Proxygroupid's # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] The Proxygroup object id that was deleted def delete(data) result = @client.api_request(method: 'proxygroup.delete', params: data) result.empty? ? nil : result['proxyids'][0].to_i end # Check if a Proxygroup object is readable using Zabbix API # # @param data [Array] Should include array of Proxygroupid's # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Boolean] Returns true if the given Proxygroupgroup are readable def isreadable(data) @client.api_request(method: 'proxygroup.isreadable', params: data) end # Check if a Proxygroup object is writable using Zabbix API # # @param data [Array] Should include array of Proxygroupid's # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Boolean] Returns true if the given Proxygroup are writable def iswritable(data) @client.api_request(method: 'proxygroup.iswritable', params: data) end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
yabeda-rb/yabeda-sidekiq
https://github.com/yabeda-rb/yabeda-sidekiq/blob/4488eb848788093ac5809129646fd4956edbf0ec/spec/spec_helper.rb
spec/spec_helper.rb
# frozen_string_literal: true require "bundler/setup" require "sidekiq/cli" # Fake that we're a worker to test worker-specific things require "yabeda/sidekiq" require "yabeda/rspec" require "sidekiq/testing" require "active_job" require "active_job/queue_adapters/sidekiq_adapter" require "pry" require_relative "support/custom_metrics" require_relative "support/jobs" require_relative "support/sidekiq_inline_middlewares" RSpec.configure do |config| # Enable flags like --only-failures and --next-failure config.example_status_persistence_file_path = ".rspec_status" # Disable RSpec exposing methods globally on `Module` and `main` config.disable_monkey_patching! config.expect_with :rspec do |c| c.syntax = :expect end config.mock_with :rspec Kernel.srand config.seed config.order = :random config.filter_run focus: true config.run_all_when_everything_filtered = true config.before(:all) do Sidekiq::Testing.fake! ActiveJob::QueueAdapters::SidekiqAdapter::JobWrapper.jobs.clear end config.after(:all) do Sidekiq::Queues.clear_all Sidekiq::Testing.disable! end config.around do |ex| next ex.run unless ex.metadata[:sidekiq] begin previous_mode = Sidekiq::Testing.__test_mode Sidekiq::Testing.__set_test_mode(ex.metadata[:sidekiq]) ex.run ensure Sidekiq::Testing.__set_test_mode(previous_mode) end end end ActiveJob::Base.logger = Logger.new(nil)
ruby
MIT
4488eb848788093ac5809129646fd4956edbf0ec
2026-01-04T17:47:44.155696Z
false
yabeda-rb/yabeda-sidekiq
https://github.com/yabeda-rb/yabeda-sidekiq/blob/4488eb848788093ac5809129646fd4956edbf0ec/spec/support/sidekiq_inline_middlewares.rb
spec/support/sidekiq_inline_middlewares.rb
# frozen_string_literal: true require "sidekiq/testing" module SidekiqTestingInlineWithMiddlewares # rubocop:disable Metrics/AbcSize def push(job) return super unless Sidekiq::Testing.inline? job = Sidekiq.load_json(Sidekiq.dump_json(job)) job["jid"] ||= SecureRandom.hex(12) job_class = Object.const_get(job["class"]) job_instance = job_class.new queue = (job_instance.sidekiq_options_hash || {}).fetch("queue", "default") server = Sidekiq.respond_to?(:default_configuration) ? Sidekiq.default_configuration : Sidekiq server.server_middleware.invoke(job_instance, job, queue) do job_instance.perform(*job["args"]) end job["jid"] end # rubocop:enable Metrics/AbcSize end Sidekiq::Client.prepend(SidekiqTestingInlineWithMiddlewares)
ruby
MIT
4488eb848788093ac5809129646fd4956edbf0ec
2026-01-04T17:47:44.155696Z
false
yabeda-rb/yabeda-sidekiq
https://github.com/yabeda-rb/yabeda-sidekiq/blob/4488eb848788093ac5809129646fd4956edbf0ec/spec/support/custom_metrics.rb
spec/support/custom_metrics.rb
# frozen_string_literal: true Yabeda.configure do group :test do counter :whatever end end
ruby
MIT
4488eb848788093ac5809129646fd4956edbf0ec
2026-01-04T17:47:44.155696Z
false
yabeda-rb/yabeda-sidekiq
https://github.com/yabeda-rb/yabeda-sidekiq/blob/4488eb848788093ac5809129646fd4956edbf0ec/spec/support/jobs.rb
spec/support/jobs.rb
# frozen_string_literal: true class SamplePlainJob include Sidekiq::Worker def perform(*_args) "My job is simple" end end class SampleLongRunningJob include Sidekiq::Worker def perform(*_args) sleep 0.05 "Phew, I'm done!" end end class SampleComplexJob include Sidekiq::Worker def perform(*_args) Yabeda.test.whatever.increment({ explicit: true }) "My job is complex" end def yabeda_tags { implicit: true } end end class FailingPlainJob include Sidekiq::Worker SpecialError = Class.new(StandardError) def perform(*_args) raise SpecialError, "Badaboom" end end class SampleActiveJob < ActiveJob::Base self.queue_adapter = :Sidekiq def perform(*_args) "I'm doing my job" end end class FailingActiveJob < ActiveJob::Base SpecialError = Class.new(StandardError) self.queue_adapter = :Sidekiq def perform(*_args) raise SpecialError, "Boom" end end class ReRouteJobsMiddleware def call(_worker, job, _queue, _redis_pool) job["queue"] = "rerouted_queue" yield end end
ruby
MIT
4488eb848788093ac5809129646fd4956edbf0ec
2026-01-04T17:47:44.155696Z
false
yabeda-rb/yabeda-sidekiq
https://github.com/yabeda-rb/yabeda-sidekiq/blob/4488eb848788093ac5809129646fd4956edbf0ec/spec/yabeda/sidekiq_spec.rb
spec/yabeda/sidekiq_spec.rb
# frozen_string_literal: true RSpec.describe Yabeda::Sidekiq do it "has a version number" do expect(Yabeda::Sidekiq::VERSION).not_to be nil end it "configures middlewares" do config = Sidekiq.respond_to?(:default_configuration) ? Sidekiq.default_configuration : Sidekiq expect(config.client_middleware).to include(have_attributes(klass: Yabeda::Sidekiq::ClientMiddleware)) end describe "plain Sidekiq jobs" do it "counts enqueues" do expect do SamplePlainJob.perform_async SamplePlainJob.perform_async FailingPlainJob.perform_async end.to \ increment_yabeda_counter(Yabeda.sidekiq.jobs_enqueued_total).with( { queue: "default", worker: "SamplePlainJob" } => 2, { queue: "default", worker: "FailingPlainJob" } => 1, ) end context "when label_for_error_class_on_sidekiq_jobs_failed is set to true" do around do |example| old_value = described_class.config.label_for_error_class_on_sidekiq_jobs_failed described_class.config.label_for_error_class_on_sidekiq_jobs_failed = true example.run described_class.config.label_for_error_class_on_sidekiq_jobs_failed = old_value end it "counts failed total and executed total with correct labels", sidekiq: :inline do expect do SamplePlainJob.perform_async SamplePlainJob.perform_async begin FailingPlainJob.perform_async rescue StandardError nil end end.to \ increment_yabeda_counter(Yabeda.sidekiq.jobs_failed_total).with( { queue: "default", worker: "FailingPlainJob", error: "FailingPlainJob::SpecialError" } => 1, ).and \ increment_yabeda_counter(Yabeda.sidekiq.jobs_executed_total).with( { queue: "default", worker: "SamplePlainJob" } => 2, { queue: "default", worker: "FailingPlainJob" } => 1, ) end it "does not add jobs_failed_total error label to labels used for jobs_executed_total", sidekiq: :inline do expect do SamplePlainJob.perform_async SamplePlainJob.perform_async begin FailingPlainJob.perform_async rescue StandardError nil end end.not_to \ increment_yabeda_counter(Yabeda.sidekiq.jobs_executed_total).with( { queue: "default", worker: "FailingPlainJob", error: "FailingPlainJob::SpecialError" } => 1, ) end end describe "re-routing jobs by middleware" do around do |example| add_reroute_jobs_middleware example.run remove_reroute_jobs_middleware end it "counts enqueues" do expect do SamplePlainJob.perform_async SamplePlainJob.perform_async FailingPlainJob.perform_async end.to \ increment_yabeda_counter(Yabeda.sidekiq.jobs_enqueued_total).with( { queue: "rerouted_queue", worker: "SamplePlainJob" } => 2, { queue: "rerouted_queue", worker: "FailingPlainJob" } => 1, ).and \ increment_yabeda_counter(Yabeda.sidekiq.jobs_rerouted_total).with( { from_queue: "default", to_queue: "rerouted_queue", worker: "SamplePlainJob" } => 2, { from_queue: "default", to_queue: "rerouted_queue", worker: "FailingPlainJob" } => 1, ) end end it "measures runtime", sidekiq: :inline do expect do SamplePlainJob.perform_async SamplePlainJob.perform_async begin FailingPlainJob.perform_async rescue StandardError nil end end.to \ increment_yabeda_counter(Yabeda.sidekiq.jobs_executed_total).with( { queue: "default", worker: "SamplePlainJob" } => 2, { queue: "default", worker: "FailingPlainJob" } => 1, ).and \ increment_yabeda_counter(Yabeda.sidekiq.jobs_success_total).with( { queue: "default", worker: "SamplePlainJob" } => 2, ).and \ increment_yabeda_counter(Yabeda.sidekiq.jobs_failed_total).with( { queue: "default", worker: "FailingPlainJob" } => 1, ).and \ measure_yabeda_histogram(Yabeda.sidekiq.job_runtime).with( { queue: "default", worker: "SamplePlainJob" } => kind_of(Numeric), { queue: "default", worker: "FailingPlainJob" } => kind_of(Numeric), ) end end describe "ActiveJob jobs" do it "counts enqueues" do expect { SampleActiveJob.perform_later }.to \ increment_yabeda_counter(Yabeda.sidekiq.jobs_enqueued_total).with( { queue: "default", worker: "SampleActiveJob" } => 1, ) end describe "re-routing jobs by middleware" do around do |example| add_reroute_jobs_middleware example.run remove_reroute_jobs_middleware end it "counts enqueues" do expect { SampleActiveJob.perform_later }.to \ increment_yabeda_counter(Yabeda.sidekiq.jobs_enqueued_total).with( { queue: "rerouted_queue", worker: "SampleActiveJob" } => 1, ).and \ increment_yabeda_counter(Yabeda.sidekiq.jobs_rerouted_total).with( { from_queue: "default", to_queue: "rerouted_queue", worker: "SampleActiveJob" } => 1, ) end end context "when label_for_error_class_on_sidekiq_jobs_failed is set to true" do around do |example| old_value = described_class.config.label_for_error_class_on_sidekiq_jobs_failed described_class.config.label_for_error_class_on_sidekiq_jobs_failed = true example.run described_class.config.label_for_error_class_on_sidekiq_jobs_failed = old_value end it "counts enqueues and uses the default label for the error class", sidekiq: :inline do expect do SampleActiveJob.perform_later SampleActiveJob.perform_later begin FailingActiveJob.perform_later rescue StandardError nil end end.to \ increment_yabeda_counter(Yabeda.sidekiq.jobs_failed_total).with( { queue: "default", worker: "FailingActiveJob", error: "FailingActiveJob::SpecialError" } => 1, ) end end it "measures runtime", sidekiq: :inline do expect do SampleActiveJob.perform_later SampleActiveJob.perform_later begin FailingActiveJob.perform_later rescue StandardError nil end end.to \ increment_yabeda_counter(Yabeda.sidekiq.jobs_executed_total).with( { queue: "default", worker: "SampleActiveJob" } => 2, { queue: "default", worker: "FailingActiveJob" } => 1, ).and \ increment_yabeda_counter(Yabeda.sidekiq.jobs_success_total).with( { queue: "default", worker: "SampleActiveJob" } => 2, ).and \ increment_yabeda_counter(Yabeda.sidekiq.jobs_failed_total).with( { queue: "default", worker: "FailingActiveJob" } => 1, ).and \ measure_yabeda_histogram(Yabeda.sidekiq.job_runtime).with( { queue: "default", worker: "SampleActiveJob" } => kind_of(Numeric), { queue: "default", worker: "FailingActiveJob" } => kind_of(Numeric), ) end end describe "#yabeda_tags worker method" do it "uses custom labels for both sidekiq and application metrics", sidekiq: :inline do expect { SampleComplexJob.perform_async }.to \ increment_yabeda_counter(Yabeda.sidekiq.jobs_executed_total).with( { queue: "default", worker: "SampleComplexJob", implicit: true } => 1, ).and \ measure_yabeda_histogram(Yabeda.sidekiq.job_runtime).with( { queue: "default", worker: "SampleComplexJob", implicit: true } => kind_of(Numeric), ).and \ increment_yabeda_counter(Yabeda.test.whatever).with( { explicit: true, implicit: true } => 1, ) end end describe "collection of Sidekiq statistics" do before do allow(Sidekiq::Stats).to receive(:new).and_return( OpenStruct.new( processes_size: 1, workers_size: 10, retry_size: 1, scheduled_size: 2, dead_size: 3, processed: 42, failed: 13, queues: { "default" => 5, "mailers" => 4 }, ), ) allow(Sidekiq::Queue).to receive(:all).and_return( [ OpenStruct.new({ name: "default", latency: 0.5 }), OpenStruct.new({ name: "mailers", latency: 0 }), ], ) end it "collects queue latencies" do expect { Yabeda.collect! }.to \ update_yabeda_gauge(Yabeda.sidekiq.queue_latency).with( { queue: "default" } => 0.5, { queue: "mailers" } => 0.0, ) end it "collects queue sizes" do expect { Yabeda.collect! }.to \ update_yabeda_gauge(Yabeda.sidekiq.jobs_waiting_count).with( { queue: "default" } => 5, { queue: "mailers" } => 4, ) end it "collects named queues stats", :aggregate_failures do expect { Yabeda.collect! }.to \ update_yabeda_gauge(Yabeda.sidekiq.jobs_retry_count).with(1).and \ update_yabeda_gauge(Yabeda.sidekiq.jobs_dead_count).with(3).and \ update_yabeda_gauge(Yabeda.sidekiq.jobs_scheduled_count).with(2) end it "measures maximum runtime of currently running jobs", sidekiq: :inline do workers = [] workers.push(Thread.new { SampleLongRunningJob.perform_async }) sleep 0.015 # Ruby can sleep less than requested workers.push(Thread.new { SampleLongRunningJob.perform_async }) expect { Yabeda.collect! }.to \ update_yabeda_gauge(Yabeda.sidekiq.running_job_runtime).with( { queue: "default", worker: "SampleLongRunningJob" } => (be >= 0.010), ) sleep 0.015 # Ruby can sleep less than requested begin FailingActiveJob.perform_later rescue StandardError nil end expect { Yabeda.collect! }.to \ update_yabeda_gauge(Yabeda.sidekiq.running_job_runtime).with( { queue: "default", worker: "SampleLongRunningJob" } => (be >= 0.020), ) # When all jobs are completed, metric should respond with zero workers.map(&:join) expect { Yabeda.collect! }.to \ update_yabeda_gauge(Yabeda.sidekiq.running_job_runtime).with( { queue: "default", worker: "SampleLongRunningJob" } => 0.0, ) end end def add_reroute_jobs_middleware ::Sidekiq.configure_server do |config| config.client_middleware do |chain| chain.insert_before Yabeda::Sidekiq::ClientMiddleware, ReRouteJobsMiddleware end end end def remove_reroute_jobs_middleware ::Sidekiq.configure_server do |config| config.client_middleware do |chain| chain.remove ReRouteJobsMiddleware end end end end
ruby
MIT
4488eb848788093ac5809129646fd4956edbf0ec
2026-01-04T17:47:44.155696Z
false
yabeda-rb/yabeda-sidekiq
https://github.com/yabeda-rb/yabeda-sidekiq/blob/4488eb848788093ac5809129646fd4956edbf0ec/lib/yabeda/sidekiq.rb
lib/yabeda/sidekiq.rb
# frozen_string_literal: true require "sidekiq" require "sidekiq/api" require "yabeda" require "yabeda/sidekiq/version" require "yabeda/sidekiq/client_middleware" require "yabeda/sidekiq/server_middleware" require "yabeda/sidekiq/config" module Yabeda module Sidekiq LONG_RUNNING_JOB_RUNTIME_BUCKETS = [ 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, # standard (from Prometheus) 30, 60, 120, 300, 1800, 3600, 21_600, # Sidekiq tasks may be very long-running ].freeze def self.config @config ||= Config.new end Yabeda.configure do config = ::Yabeda::Sidekiq.config group :sidekiq counter :jobs_enqueued_total, tags: %i[queue worker], comment: "A counter of the total number of jobs sidekiq enqueued." counter :jobs_rerouted_total, tags: %i[from_queue to_queue worker], comment: "A counter of the total number of rerouted jobs sidekiq enqueued." if config.declare_process_metrics # defaults to +::Sidekiq.server?+ failed_total_tags = config.label_for_error_class_on_sidekiq_jobs_failed ? %i[queue worker error] : %i[queue worker] counter :jobs_executed_total, tags: %i[queue worker], comment: "A counter of the total number of jobs sidekiq executed." counter :jobs_success_total, tags: %i[queue worker], comment: "A counter of the total number of jobs successfully processed by sidekiq." counter :jobs_failed_total, tags: failed_total_tags, comment: "A counter of the total number of jobs failed in sidekiq." gauge :running_job_runtime, tags: %i[queue worker], aggregation: :max, unit: :seconds, comment: "How long currently running jobs are running (useful for detection of hung jobs)" histogram :job_latency, comment: "The job latency, the difference in seconds between enqueued and running time", unit: :seconds, per: :job, tags: %i[queue worker], buckets: LONG_RUNNING_JOB_RUNTIME_BUCKETS histogram :job_runtime, comment: "A histogram of the job execution time.", unit: :seconds, per: :job, tags: %i[queue worker], buckets: LONG_RUNNING_JOB_RUNTIME_BUCKETS end # Metrics not specific for current Sidekiq process, but representing state of the whole Sidekiq installation (queues, processes, etc) # You can opt-out from collecting these by setting YABEDA_SIDEKIQ_COLLECT_CLUSTER_METRICS to falsy value (+no+ or +false+) if config.collect_cluster_metrics # defaults to +::Sidekiq.server?+ retry_count_tags = config.retries_segmented_by_queue ? %i[queue] : [] gauge :jobs_waiting_count, tags: %i[queue], aggregation: :most_recent, comment: "The number of jobs waiting to process in sidekiq." gauge :active_workers_count, tags: [], aggregation: :most_recent, comment: "The number of currently running machines with sidekiq workers." gauge :jobs_scheduled_count, tags: [], aggregation: :most_recent, comment: "The number of jobs scheduled for later execution." gauge :jobs_retry_count, tags: retry_count_tags, aggregation: :most_recent, comment: "The number of failed jobs waiting to be retried" gauge :jobs_dead_count, tags: [], aggregation: :most_recent, comment: "The number of jobs exceeded their retry count." gauge :active_processes, tags: [], aggregation: :most_recent, comment: "The number of active Sidekiq worker processes." gauge :queue_latency, tags: %i[queue], aggregation: :most_recent, comment: "The queue latency, the difference in seconds since the oldest job in the queue was enqueued" end collect do Yabeda::Sidekiq.track_max_job_runtime if ::Sidekiq.server? next unless config.collect_cluster_metrics stats = ::Sidekiq::Stats.new stats.queues.each do |k, v| sidekiq_jobs_waiting_count.set({ queue: k }, v) end sidekiq_active_workers_count.set({}, stats.workers_size) sidekiq_jobs_scheduled_count.set({}, stats.scheduled_size) sidekiq_jobs_dead_count.set({}, stats.dead_size) sidekiq_active_processes.set({}, stats.processes_size) ::Sidekiq::Queue.all.each do |queue| sidekiq_queue_latency.set({ queue: queue.name }, queue.latency) end if config.retries_segmented_by_queue retries_by_queues = ::Sidekiq::RetrySet.new.each_with_object(Hash.new(0)) do |job, cntr| cntr[job["queue"]] += 1 end retries_by_queues.each do |queue, count| sidekiq_jobs_retry_count.set({ queue: queue }, count) end else sidekiq_jobs_retry_count.set({}, stats.retry_size) end end end ::Sidekiq.configure_server do |config| config.server_middleware do |chain| chain.add ServerMiddleware end config.client_middleware do |chain| chain.add ClientMiddleware end end ::Sidekiq.configure_client do |config| config.client_middleware do |chain| chain.add ClientMiddleware end end class << self def labelize(worker, job, queue) { queue: queue, worker: worker_class(worker, job) } end def worker_class(worker, job) worker = job["wrapped"] || worker (worker.is_a?(String) || worker.is_a?(Class) ? worker : worker.class).to_s end def custom_tags(worker, job) return {} unless worker.respond_to?(:yabeda_tags) worker.method(:yabeda_tags).arity.zero? ? worker.yabeda_tags : worker.yabeda_tags(*job["args"]) end # Hash of hashes containing all currently running jobs' start timestamps # to calculate maximum durations of currently running not yet completed jobs # { { queue: "default", worker: "SomeJob" } => { "jid1" => 100500, "jid2" => 424242 } } attr_accessor :jobs_started_at def track_max_job_runtime now = Process.clock_gettime(Process::CLOCK_MONOTONIC) ::Yabeda::Sidekiq.jobs_started_at.each do |labels, jobs| oldest_job_started_at = jobs.values.min oldest_job_duration = oldest_job_started_at ? (now - oldest_job_started_at).round(3) : 0 Yabeda.sidekiq.running_job_runtime.set(labels, oldest_job_duration) end end end self.jobs_started_at = Concurrent::Map.new { |hash, key| hash[key] = Concurrent::Map.new } end end
ruby
MIT
4488eb848788093ac5809129646fd4956edbf0ec
2026-01-04T17:47:44.155696Z
false
yabeda-rb/yabeda-sidekiq
https://github.com/yabeda-rb/yabeda-sidekiq/blob/4488eb848788093ac5809129646fd4956edbf0ec/lib/yabeda/sidekiq/version.rb
lib/yabeda/sidekiq/version.rb
# frozen_string_literal: true module Yabeda module Sidekiq VERSION = "0.12.0" end end
ruby
MIT
4488eb848788093ac5809129646fd4956edbf0ec
2026-01-04T17:47:44.155696Z
false
yabeda-rb/yabeda-sidekiq
https://github.com/yabeda-rb/yabeda-sidekiq/blob/4488eb848788093ac5809129646fd4956edbf0ec/lib/yabeda/sidekiq/server_middleware.rb
lib/yabeda/sidekiq/server_middleware.rb
# frozen_string_literal: true module Yabeda module Sidekiq # Sidekiq worker middleware class ServerMiddleware # See https://github.com/mperham/sidekiq/discussions/4971 JOB_RECORD_CLASS = defined?(::Sidekiq::JobRecord) ? ::Sidekiq::JobRecord : ::Sidekiq::Job # rubocop: disable Metrics/AbcSize, Metrics/MethodLength: def call(worker, job, queue) custom_tags = Yabeda::Sidekiq.custom_tags(worker, job).to_h labels = Yabeda::Sidekiq.labelize(worker, job, queue).merge(custom_tags) start = Process.clock_gettime(Process::CLOCK_MONOTONIC) begin job_instance = JOB_RECORD_CLASS.new(job) Yabeda.sidekiq_job_latency.measure(labels, job_instance.latency) Yabeda::Sidekiq.jobs_started_at[labels][job["jid"]] = start Yabeda.with_tags(**custom_tags) do yield end Yabeda.sidekiq_jobs_success_total.increment(labels) rescue Exception => e # rubocop: disable Lint/RescueException jobs_failed_labels = labels.dup jobs_failed_labels[:error] = e.class.name if Yabeda::Sidekiq.config.label_for_error_class_on_sidekiq_jobs_failed Yabeda.sidekiq_jobs_failed_total.increment(jobs_failed_labels) raise ensure Yabeda.sidekiq_job_runtime.measure(labels, elapsed(start)) Yabeda.sidekiq_jobs_executed_total.increment(labels) Yabeda::Sidekiq.jobs_started_at[labels].delete(job["jid"]) end end # rubocop: enable Metrics/AbcSize, Metrics/MethodLength: private def elapsed(start) (Process.clock_gettime(Process::CLOCK_MONOTONIC) - start).round(3) end end end end
ruby
MIT
4488eb848788093ac5809129646fd4956edbf0ec
2026-01-04T17:47:44.155696Z
false
yabeda-rb/yabeda-sidekiq
https://github.com/yabeda-rb/yabeda-sidekiq/blob/4488eb848788093ac5809129646fd4956edbf0ec/lib/yabeda/sidekiq/client_middleware.rb
lib/yabeda/sidekiq/client_middleware.rb
# frozen_string_literal: true module Yabeda module Sidekiq # Client middleware to count number of enqueued jobs class ClientMiddleware def call(worker, job, queue, _redis_pool) labels = Yabeda::Sidekiq.labelize(worker, job, job["queue"] || queue) Yabeda.sidekiq_jobs_enqueued_total.increment(labels) if job["queue"] && job["queue"] != queue labels = Yabeda::Sidekiq.labelize(worker, job, queue) Yabeda.sidekiq_jobs_rerouted_total.increment({ from_queue: queue, to_queue: job["queue"], **labels.except(:queue) }) end yield end end end end
ruby
MIT
4488eb848788093ac5809129646fd4956edbf0ec
2026-01-04T17:47:44.155696Z
false
yabeda-rb/yabeda-sidekiq
https://github.com/yabeda-rb/yabeda-sidekiq/blob/4488eb848788093ac5809129646fd4956edbf0ec/lib/yabeda/sidekiq/config.rb
lib/yabeda/sidekiq/config.rb
# frozen_string_literal: true require "anyway" module Yabeda module Sidekiq class Config < ::Anyway::Config config_name :yabeda_sidekiq # By default all sidekiq worker processes (servers) collects global metrics about whole Sidekiq installation. # Client processes (everything else that is not Sidekiq worker) by default doesn't. # With this config you can override this behavior: # - force disable if you don't want multiple Sidekiq workers to report the same numbers (that causes excess load to both Redis and monitoring) # - force enable if you want non-Sidekiq process to collect them (like dedicated metric exporter process) attr_config collect_cluster_metrics: ::Sidekiq.server? # Declare metrics that are only tracked inside worker process even outside them attr_config declare_process_metrics: ::Sidekiq.server? # Retries are tracked by default as a single metric. If you want to track them separately for each queue, set this to +true+ # Disabled by default because it is quite slow if the retry set is large attr_config retries_segmented_by_queue: false # If set to true, an `:error` label will be added with name of the error class to all failed jobs attr_config label_for_error_class_on_sidekiq_jobs_failed: false end end end
ruby
MIT
4488eb848788093ac5809129646fd4956edbf0ec
2026-01-04T17:47:44.155696Z
false
CocoaPods/cocoapods-try
https://github.com/CocoaPods/cocoapods-try/blob/c30ca17e364e10086aa75ac5f2f61f368d7c7e95/spec/spec_helper.rb
spec/spec_helper.rb
# Set up #-----------------------------------------------------------------------------# require 'bundler/setup' require 'pathname' require 'bacon' require 'mocha-on-bacon' require 'pretty_bacon' require 'cocoapods' ROOT = Pathname.new(File.expand_path('../../', __FILE__)) $LOAD_PATH.unshift((ROOT + 'lib').to_s) $LOAD_PATH.unshift((ROOT + 'spec').to_s) require 'cocoapods_plugin' #-----------------------------------------------------------------------------# module Pod # Disable the wrapping so the output is deterministic in the tests. # UI.disable_wrap = true # Redirects the messages to an internal store. # module UI @output = '' @warnings = '' class << self attr_accessor :output attr_accessor :warnings def puts(message = '') @output << "#{message}\n" end def warn(message = '', _actions = []) @warnings << "#{message}\n" end def print(message) @output << message end end end end #-----------------------------------------------------------------------------#
ruby
MIT
c30ca17e364e10086aa75ac5f2f61f368d7c7e95
2026-01-04T17:48:05.498097Z
false
CocoaPods/cocoapods-try
https://github.com/CocoaPods/cocoapods-try/blob/c30ca17e364e10086aa75ac5f2f61f368d7c7e95/spec/command/try_settings_spec.rb
spec/command/try_settings_spec.rb
require 'tmpdir' require File.expand_path('../../spec_helper', __FILE__) # The CocoaPods namespace # module Pod describe TrySettings do it 'returns an instance with empty defaults when there are no yml settings files' do Dir.mktmpdir do |dir| settings = TrySettings.settings_from_folder dir settings.should.be.instance_of TrySettings settings.pre_install_commands.should.be.nil? settings.project_path.should.be.nil? end end it 'returns an instance with the right defaults when there are no yml settings files' do Dir.mktmpdir do |dir| yaml = <<YAML try: install: pre: - pod install - git submodule init project: 'ORStackView.xcworkspace' YAML File.open(dir + '/.cocoapods.yml', 'w') { |f| f.write(yaml) } settings = TrySettings.settings_from_folder dir settings.should.be.instance_of TrySettings settings.pre_install_commands.should == ['pod install', 'git submodule init'] settings.project_path.should == Pathname.new(dir) + 'ORStackView.xcworkspace' end end it 'converts a string for the pre_install hook to a single object array' do Dir.mktmpdir do |dir| yaml = <<YAML try: install: pre: pod install YAML File.open(dir + '/.cocoapods.yml', 'w') { |f| f.write(yaml) } settings = TrySettings.settings_from_folder dir settings.should.be.instance_of TrySettings settings.pre_install_commands.should == ['pod install'] end end it 'handles running commands in the pre-install' do Dir.mktmpdir do |dir| yaml = <<YAML try: install: pre: - pod install - git submodule init YAML File.open(dir + '/.cocoapods.yml', 'w') { |f| f.write(yaml) } Executable.expects(:execute_command).with('bash', ['-ec', 'pod install'], true) Executable.expects(:execute_command).with('bash', ['-ec', 'git submodule init'], true) settings = TrySettings.settings_from_folder dir settings.run_pre_install_commands false end end it 'handles not including system commands in the pre-install' do Dir.mktmpdir do |dir| yaml = <<YAML try: project: 'ORStackView.xcworkspace' YAML File.open(dir + '/.cocoapods.yml', 'w') { |f| f.write(yaml) } settings = TrySettings.settings_from_folder dir settings.project_path.should == Pathname.new(dir) + 'ORStackView.xcworkspace' end end it 'handles not including the try in the yaml' do Dir.mktmpdir do |dir| yaml = <<YAML thing: "other" YAML File.open(dir + '/.cocoapods.yml', 'w') { |f| f.write(yaml) } settings = TrySettings.settings_from_folder dir settings.pre_install_commands.should.be.nil? settings.project_path.should.be.nil? end end it 'does not show a prompt with no pre_install commands' do Dir.mktmpdir do |dir| TrySettings.any_instance.expects(:prompt_for_permission).never settings = TrySettings.settings_from_folder dir settings.run_pre_install_commands true end end end end
ruby
MIT
c30ca17e364e10086aa75ac5f2f61f368d7c7e95
2026-01-04T17:48:05.498097Z
false
CocoaPods/cocoapods-try
https://github.com/CocoaPods/cocoapods-try/blob/c30ca17e364e10086aa75ac5f2f61f368d7c7e95/spec/command/try_spec.rb
spec/command/try_spec.rb
require File.expand_path('../../spec_helper', __FILE__) # The CocoaPods namespace # module Pod describe Command::Try do describe 'Try' do XCODE_PROJECT = Pod::Command::Try::TRY_TMP_DIR + 'Project.xcodeproj' XCODE_WORKSPACE = Pod::Command::Try::TRY_TMP_DIR + 'Project.xcworkspace' it 'registers it self' do Command.parse(%w(try)).should.be.instance_of Command::Try end it 'presents the help if no name is provided' do command = Pod::Command.parse(['try']) should.raise CLAide::Help do command.validate! end.message.should.match(/A Pod name or URL is required/) end it 'presents the help if name and podspec name is provided' do command = Pod::Command.parse(%w(try ARAnalytics --podspec_name=Analytics.podspec)) should.raise CLAide::Help do command.validate! end.message.should.match(/Podspec name can only be used with a Git URL/) end before do @original_install_method = method = Pod::Command::Try.instance_method(:install_pod) Pod::Command::Try.send(:define_method, :install_pod) do |*args| dir = method.bind(self).call(*args) FileUtils.mkdir_p(dir) dir end end after do Pod::Command::Try.send(:define_method, :install_pod, @original_install_method) end it 'allows the user to try the Pod with the given name' do command = Pod::Command.parse(%w(try ARAnalytics)) Installer::PodSourceInstaller.any_instance.expects(:install!) command.expects(:update_specs_repos) command.expects(:pick_demo_project).returns(XCODE_PROJECT) command.expects(:open_project).with(XCODE_PROJECT) command.run end it 'allows the user to try the Pod with the given Git URL' do require 'cocoapods-downloader/git' Pod::Downloader::Git.any_instance.expects(:download) spec_file = Pod::Command::Try::TRY_TMP_DIR + 'ARAnalytics/ARAnalytics.podspec' Pathname.stubs(:glob).once.returns([spec_file]) stub_spec = stub(:name => 'ARAnalytics') Pod::Specification.stubs(:from_file).with(spec_file).returns(stub_spec) command = Pod::Command.parse(['try', 'https://github.com/orta/ARAnalytics.git']) Installer::PodSourceInstaller.any_instance.expects(:install!) command.expects(:update_specs_repos).never command.expects(:pick_demo_project).returns(XCODE_PROJECT) command.expects(:open_project).with(XCODE_PROJECT) command.run end describe 'updates of the spec repos' do it 'updates the spec repos by default' do command = Pod::Command.parse(%w(try ARAnalytics)) Installer::PodSourceInstaller.any_instance.expects(:install!) command.config.sources_manager.expects(:update) command.expects(:pick_demo_project).returns(XCODE_PROJECT) command.expects(:open_project).with(XCODE_PROJECT) command.run end it "doesn't update the spec repos if that option was given" do command = Pod::Command.parse(%w(try ARAnalytics --no-repo-update)) Installer::PodSourceInstaller.any_instance.expects(:install!) command.config.sources_manager.expects(:update).never command.expects(:pick_demo_project).returns(XCODE_PROJECT) command.expects(:open_project).with(XCODE_PROJECT) command.run end end end describe 'Helpers' do before do @sut = Pod::Command.parse(['try']) end it 'returns the spec with the given name' do spec = @sut.spec_with_name('ARAnalytics') spec.name.should == 'ARAnalytics' end describe '#spec_at_url' do it 'returns a spec for an https git repo' do require 'cocoapods-downloader/git' Pod::Downloader::Git.any_instance.expects(:download) spec_file = Pod::Command::Try::TRY_TMP_DIR + 'ARAnalytics/ARAnalytics.podspec' Pathname.stubs(:glob).once.returns([spec_file]) stub_spec = stub Pod::Specification.stubs(:from_file).with(spec_file).returns(stub_spec) spec = @sut.spec_with_url('https://github.com/orta/ARAnalytics.git') spec.should == stub_spec end it 'returns a spec for an https git repo with podspec_name option' do require 'cocoapods-downloader/git' Pod::Downloader::Git.any_instance.expects(:download) spec_file = Pod::Command::Try::TRY_TMP_DIR + 'ARAnalytics/Analytics.podspec' Pathname.stubs(:glob).once.returns([spec_file]) stub_spec = stub Pod::Specification.stubs(:from_file).with(spec_file).returns(stub_spec) spec = @sut.spec_with_url('https://github.com/orta/ARAnalytics.git', 'Analytics') spec.should == stub_spec end end it 'installs the pod' do Installer::PodSourceInstaller.any_instance.expects(:install!) spec = stub(:name => 'ARAnalytics') sandbox_root = Pathname.new(Pod::Command::Try::TRY_TMP_DIR) sandbox = Sandbox.new(sandbox_root) path = @sut.install_pod(spec, sandbox) path.should == sandbox.root + 'ARAnalytics' end it 'installs the pod on older versions of CocoaPods' do @sut.stubs(:cocoapods_version).returns(Pod::Version.new('1.7.0')) spec = stub(:name => 'ARAnalytics') sandbox_root = Pathname.new(Pod::Command::Try::TRY_TMP_DIR) sandbox = Sandbox.new(sandbox_root) installer = stub('Installer') installer.stubs(:install!) Pod::Installer::PodSourceInstaller.expects(:new).with(any_parameters) do |*args| args.size == 3 end.returns(installer).once @sut.install_pod(spec, sandbox) @sut.stubs(:cocoapods_version).returns(Pod::Version.new('1.8.0')) Pod::Installer::PodSourceInstaller.expects(:new).with(any_parameters) do |*args| args.size == 4 end.returns(installer) @sut.install_pod(spec, sandbox) end describe '#pick_demo_project' do it 'raises if no demo project could be found' do @sut.stubs(:projects_in_dir).returns([]) should.raise Informative do @sut.pick_demo_project('.') end.message.should.match(/Unable to find any project/) end it 'picks a demo project' do projects = ['Demo.xcodeproj'] Dir.stubs(:glob).returns(projects) path = @sut.pick_demo_project('.') path.should == 'Demo.xcodeproj' end it 'is not case sensitive' do projects = ['demo.xcodeproj'] Dir.stubs(:glob).returns(projects) path = @sut.pick_demo_project('.') path.should == 'demo.xcodeproj' end it 'considers also projects named example' do projects = ['Example.xcodeproj'] Dir.stubs(:glob).returns(projects) path = @sut.pick_demo_project('.') path.should == 'Example.xcodeproj' end it 'returns the project if only one is found' do projects = [Pathname.new('Lib.xcodeproj')] @sut.stubs(:projects_in_dir).returns(projects) path = @sut.pick_demo_project('.') path.to_s.should == 'Lib.xcodeproj' end it 'asks the user which project would like to open if not a single suitable one is found' do projects = ['Lib_1.xcodeproj', 'Lib_2.xcodeproj'] @sut.stubs(:projects_in_dir).returns(projects) UI.stubs(:choose_from_array).returns(0) path = @sut.pick_demo_project('.') path.to_s.should == 'Lib_1.xcodeproj' UI.stubs(:choose_from_array).returns(1) path = @sut.pick_demo_project('.') path.to_s.should == 'Lib_2.xcodeproj' end it 'should prefer demo or example workspaces' do @sut.stubs(:projects_in_dir).returns(['Project Demo.xcodeproj', 'Project Demo.xcworkspace']) path = @sut.pick_demo_project('.') path.should == 'Project Demo.xcworkspace' end it 'should not show workspaces inside a project' do Dir.stubs(:glob).returns(['Project Demo.xcodeproj', 'Project Demo.xcodeproj/project.xcworkspace']) path = @sut.pick_demo_project('.') path.should == 'Project Demo.xcodeproj' end it 'should prefer workspaces over projects with the same name' do @sut.stubs(:projects_in_dir).returns(['Project Demo.xcodeproj', 'Project Demo.xcworkspace']) path = @sut.pick_demo_project('.') path.should == 'Project Demo.xcworkspace' end end describe '#install_podfile' do it 'returns the original project if no Podfile could be found' do Pathname.any_instance.stubs(:exist?).returns(false) proj = XCODE_PROJECT path = @sut.install_podfile(proj) path.should == proj end it 'performs an installation and returns the path of the workspace' do Pathname.any_instance.stubs(:exist?).returns(true) proj = XCODE_PROJECT @sut.expects(:perform_cocoapods_installation) Podfile.stubs(:from_file).returns(stub('Workspace', :workspace_path => XCODE_WORKSPACE)) path = @sut.install_podfile(proj) path.to_s.should == XCODE_WORKSPACE.to_s end it 'returns the default workspace if one is not set' do Pathname.any_instance.stubs(:exist?).returns(true) proj = XCODE_PROJECT Podfile.stubs(:from_file).returns(stub('Workspace', :workspace_path => nil)) @sut.expects(:perform_cocoapods_installation).once path = @sut.install_podfile(proj) path.to_s.should == XCODE_WORKSPACE.to_s end end end end end
ruby
MIT
c30ca17e364e10086aa75ac5f2f61f368d7c7e95
2026-01-04T17:48:05.498097Z
false
CocoaPods/cocoapods-try
https://github.com/CocoaPods/cocoapods-try/blob/c30ca17e364e10086aa75ac5f2f61f368d7c7e95/lib/cocoapods_plugin.rb
lib/cocoapods_plugin.rb
require 'pod/command/try'
ruby
MIT
c30ca17e364e10086aa75ac5f2f61f368d7c7e95
2026-01-04T17:48:05.498097Z
false
CocoaPods/cocoapods-try
https://github.com/CocoaPods/cocoapods-try/blob/c30ca17e364e10086aa75ac5f2f61f368d7c7e95/lib/cocoapods_try.rb
lib/cocoapods_try.rb
# The namespace of the Cocoapods try plugin. # module CocoapodsTry VERSION = '1.2.0'.freeze end
ruby
MIT
c30ca17e364e10086aa75ac5f2f61f368d7c7e95
2026-01-04T17:48:05.498097Z
false
CocoaPods/cocoapods-try
https://github.com/CocoaPods/cocoapods-try/blob/c30ca17e364e10086aa75ac5f2f61f368d7c7e95/lib/pod/try_settings.rb
lib/pod/try_settings.rb
module Pod class TrySettings attr_accessor :pre_install_commands, :project_path # Creates a TrySettings instance based on a folder path # def self.settings_from_folder(path) settings_path = Pathname.new(path) + '.cocoapods.yml' return TrySettings.new unless File.exist? settings_path settings = YAMLHelper.load_file(settings_path) try_settings = TrySettings.new return try_settings unless settings['try'] if settings['try']['install'] try_settings.pre_install_commands = Array(settings['try']['install']['pre']) end if settings['try']['project'] try_settings.project_path = Pathname.new(path) + settings['try']['project'] end try_settings end # If we need to run commands from pod-try we should let the users know # what is going to be running on their device. # def prompt_for_permission UI.titled_section 'Running Pre-Install Commands' do commands = pre_install_commands.length > 1 ? 'commands' : 'command' UI.puts "In order to try this pod, CocoaPods-Try needs to run the following #{commands}:" pre_install_commands.each { |command| UI.puts " - #{command}" } UI.puts "\nPress return to run these #{commands}, or press `ctrl + c` to stop trying this pod." end # Give an elegant exit point. UI.gets.chomp end # Runs the pre_install_commands from # # @param [Bool] prompt # Should CocoaPods-Try show a prompt with the commands to the user. # def run_pre_install_commands(prompt) if pre_install_commands prompt_for_permission if prompt pre_install_commands.each { |command| Executable.execute_command('bash', ['-ec', command], true) } end end end end
ruby
MIT
c30ca17e364e10086aa75ac5f2f61f368d7c7e95
2026-01-04T17:48:05.498097Z
false
CocoaPods/cocoapods-try
https://github.com/CocoaPods/cocoapods-try/blob/c30ca17e364e10086aa75ac5f2f61f368d7c7e95/lib/pod/command/try.rb
lib/pod/command/try.rb
require 'pod/try_settings' # The CocoaPods namespace # module Pod class Command # The pod try command. # @CocoaPods 0.29.0 # class Try < Command include RepoUpdate self.summary = 'Try a Pod!' self.description = <<-DESC Downloads the Pod with the given `NAME` (or Git `URL`), install its dependencies if needed and opens its demo project. If a Git URL is provided the head of the repo is used. If a Git URL is specified, then a --podspec_name can be provided, if the podspec name is different than the git repo for some reason. DESC self.arguments = [CLAide::Argument.new(%w(NAME URL), true)] def self.options [ ['--podspec_name=[name]', 'The name of the podspec file within the Git Repository'], ].concat(super) end def initialize(argv) @name = argv.shift_argument @podspec_name = argv.option('podspec_name') super end def validate! super help! 'A Pod name or URL is required.' unless @name help! 'Podspec name can only be used with a Git URL' if @podspec_name && !git_url?(@name) end def run ensure_master_spec_repo_exists! sandbox = Sandbox.new(TRY_TMP_DIR) spec = setup_spec_in_sandbox(sandbox) UI.title "Trying #{spec.name}" do pod_dir = install_pod(spec, sandbox) settings = TrySettings.settings_from_folder(pod_dir) Dir.chdir(pod_dir) { settings.run_pre_install_commands(true) } proj = settings.project_path || pick_demo_project(pod_dir) file = install_podfile(proj) if file open_project(file) else UI.puts "Unable to locate a project for #{spec.name}" end end end public # Helpers #-----------------------------------------------------------------------# # @return [Pathname] # TRY_TMP_DIR = Pathname.new(Dir.tmpdir) + 'CocoaPods/Try' # Puts the spec's data in the sandbox # def setup_spec_in_sandbox(sandbox) if git_url?(@name) spec = spec_with_url(@name, @podspec_name) sandbox.store_pre_downloaded_pod(spec.name) else update_specs_repos spec = spec_with_name(@name) end spec end # Returns the specification of the last version of the Pod with the given # name. # # @param [String] name # The name of the pod. # # @return [Specification] The specification. # def spec_with_name(name) set = config.sources_manager.search(Dependency.new(name)) if set set.specification.root else raise Informative, "Unable to find a specification for `#{name}`" end end # Returns the specification found in the given Git repository URL by # downloading the repository. # # @param [String] url # The URL for the pod Git repository. # # @param [String] spec_name # The name of the podspec file within the Git repository. # # @return [Specification] The specification. # def spec_with_url(url, spec_name = nil) name = url.split('/').last name = name.chomp('.git') if name.end_with?('.git') name = spec_name unless spec_name.nil? target_dir = TRY_TMP_DIR + name target_dir.rmtree if target_dir.exist? downloader = Pod::Downloader.for_target(target_dir, :git => url) downloader.download spec_file = Pathname.glob(target_dir + "#{name}.podspec{,.json}").first Pod::Specification.from_file(spec_file) end # Installs the specification in the given directory. # # @param [Specification] The specification of the Pod. # @param [Pathname] The directory of the sandbox where to install the # Pod. # # @return [Pathname] The path where the Pod was installed # def install_pod(spec, sandbox) specs = { :ios => spec, :osx => spec } if cocoapods_version >= Pod::Version.new('1.8.0') dummy_podfile = Podfile.new installer = Installer::PodSourceInstaller.new(sandbox, dummy_podfile, specs, :can_cache => false) else installer = Installer::PodSourceInstaller.new(sandbox, specs, :can_cache => false) end installer.install! sandbox.root + spec.name end # Picks a project or workspace suitable for the demo purposes in the # given directory. # # To decide the project simple heuristics are used according to the name, # if no project is found this method raises and `Informative` otherwise # if more than one project is found the choice is presented to the user. # # @param [#to_s] dir # The path where to look for projects. # # @return [String] The path of the project. # def pick_demo_project(dir) dir = Pathname.new(dir) projs = projects_in_dir(dir) if projs.count == 0 raise Informative, 'Unable to find any project in the source files' \ " of the Pod: `#{dir}`" elsif projs.count == 1 projs.first elsif (workspaces = projs.grep(/(demo|example|sample).*\.xcworkspace$/i)).count == 1 workspaces.first elsif (projects = projs.grep(/demo|example|sample/i)).count == 1 projects.first else message = 'Which project would you like to open' selection_array = projs.map do |p| Pathname.new(p).relative_path_from(dir).to_s end index = UI.choose_from_array(selection_array, message) projs[index] end end # Performs a CocoaPods installation for the given project if Podfile is # found. Shells out to avoid issues with the config of the process # running the try command. # # @return [String] proj # The path of the project. # # @return [String] The path of the file to open, in other words the # workspace of the installation or the given project. # def install_podfile(proj) return unless proj dirname = Pathname.new(proj).dirname podfile_path = dirname + 'Podfile' if podfile_path.exist? Dir.chdir(dirname) do perform_cocoapods_installation podfile = Pod::Podfile.from_file(podfile_path) if podfile.workspace_path File.expand_path(podfile.workspace_path) else proj.to_s.chomp(File.extname(proj.to_s)) + '.xcworkspace' end end else proj end end public # Private Helpers #-----------------------------------------------------------------------# # @return [void] Updates the specs repo unless disabled by the config. # def update_specs_repos return unless repo_update?(:default => true) UI.section 'Updating spec repositories' do config.sources_manager.update end end # Opens the project at the given path. # # @return [String] path # The path of the project. # # @return [void] # def open_project(path) UI.puts "Opening '#{path}'" `open "#{path}"` end # @return [void] Performs a CocoaPods installation in the working # directory. # def perform_cocoapods_installation UI.titled_section 'Performing CocoaPods Installation' do Command::Install.invoke end end # @return [Bool] Wether the given string is the name of a Pod or an URL # for a Git repo. # def git_url?(name) prefixes = ['https://', 'http://'] prefixes.any? { |prefix| name.start_with?(prefix) } end # @return [Array<String>] The list of the workspaces and projects in a # given directory excluding The Pods project and the projects # that have a sister workspace. # def projects_in_dir(dir) glob_match = Dir.glob("#{dir}/**/*.xc{odeproj,workspace}") glob_match = glob_match.reject do |p| next true if p.include?('Pods.xcodeproj') next true if p.end_with?('.xcodeproj/project.xcworkspace') sister_workspace = p.chomp(File.extname(p.to_s)) + '.xcworkspace' p.end_with?('.xcodeproj') && glob_match.include?(sister_workspace) end end # @return [Pod::Version] the version of CocoaPods currently running # def cocoapods_version Pod::Version.new(Pod::VERSION) end #-------------------------------------------------------------------# end end end
ruby
MIT
c30ca17e364e10086aa75ac5f2f61f368d7c7e95
2026-01-04T17:48:05.498097Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/helpers/reports_helper.rb
app/helpers/reports_helper.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module ReportsHelper end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/helpers/dashboard_helper.rb
app/helpers/dashboard_helper.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module DashboardHelper end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/helpers/sessions_helper.rb
app/helpers/sessions_helper.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module SessionsHelper end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/helpers/search_helper.rb
app/helpers/search_helper.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module SearchHelper end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/helpers/syslog_helper.rb
app/helpers/syslog_helper.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module SyslogHelper def syslog_audit(audit) msg = "[#{audit.auditable_type.downcase}:#{audit.action}:#{audit.auditable_id}]" msg << "[#{audit.associated_type.downcase}:#{audit.associated_id}]" if audit.associated_type msg << "[user:#{audit.user.name}]" if audit.user && audit.user.name msg << "[from:#{audit.remote_address}]" if audit.remote_address msg << " #{audit.audited_changes.to_json}" msg << " (#{audit.comment})" if audit.comment Rails.syslogger.info msg end def syslog_info(message) Rails.syslogger.info "[INFO] #{message}" end def syslog_error(message) Rails.syslogger.error "[ERROR] #{message}" end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/helpers/users_helper.rb
app/helpers/users_helper.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module UsersHelper end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/helpers/access_denied_helper.rb
app/helpers/access_denied_helper.rb
module AccessDeniedHelper end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/helpers/macros_helper.rb
app/helpers/macros_helper.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module MacrosHelper end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/helpers/records_helper.rb
app/helpers/records_helper.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module RecordsHelper def should_increase_ttl? GloboDns::Config::INCREASE_TTL end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/helpers/bind_time_format_helper.rb
app/helpers/bind_time_format_helper.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module BindTimeFormatHelper ::String.class_eval do def parse_bind_time_format value = self.to_s.clone sum = 0 while value.slice!(/^(\d+)([sSmMhHdDwW]|$)/) sum += case $2.downcase when ''; $1.to_i.seconds when 's'; $1.to_i.seconds when 'm'; $1.to_i.minutes when 'h'; $1.to_i.hours when 'd'; $1.to_i.days when 'w'; $1.to_i.weeks else nil end end value.size == 0 ? sum : nil end end def self.included(base) base.send(:extend, ClassMethods) base.send(:include, InstanceMethods) end module ClassMethods def validates_bind_time_format(*attr_names) # validates *args, :bind_time_format => true validates_with BindTimeFormatValidator, _merge_attributes(attr_names) attr_names.each do |attr_name| define_method "#{attr_name}_int" do parse_bind_time_format(attr_name) end end end end module InstanceMethods def parse_bind_time_format(attr) value = self.send(attr.to_sym) value.is_a?(String) ? value.parse_bind_time_format : value end end class BindTimeFormatValidator < ActiveModel::EachValidator MAX_INT = ((2 ** 31) - 1) def validate_each(record, attribute, value) return if value.nil? || value.blank? if value.is_a?(String) int_value = value.parse_bind_time_format record.errors.add(attribute) if int_value.nil? || (int_value.to_i < 0) || (int_value.to_i > MAX_INT) elsif value.is_a?(Numeric) record.errors.add(attribute) if (value.to_i < 0) || (value.to_i > MAX_INT) else record.errors.add(attribute) end end end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/helpers/application_helper.rb
app/helpers/application_helper.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Methods added to this helper will be available to all templates in the application. module ApplicationHelper def last_export_timestamp @last_export_timestamp ||= GloboDns::Util::last_export_timestamp end def num_pending_updates @num_pending_updates ||= Audited::Adapters::ActiveRecord::Audit.where('created_at > ?', last_export_timestamp).count end # Outputs a page title with +@page_title+ appended def page_title title = t(:layout_main_title) title << ' - ' + @page_title unless @page_title.nil? title end # Output the flashes if they exist def show_flash html = '' [ :alert, :notice, :info, :warning, :error ].each do |f| options = { :id => "flash-#{f}", :class => "flash-#{f}" } options.merge!( :style => 'display:none' ) if flash[f].nil? html << content_tag( 'div', options ) { flash[f] || '' } end html.html_safe end # Link to Zytrax def dns_book( text, link ) link_to text, "http://www.zytrax.com/books/dns/#{link}", :target => '_blank' end # Add a cancel link for shared forms. Looks at the provided object and either # creates a link to the index or show actions. def link_to_cancel(object, options = {}) path = object.class.name.tableize path = if object.new_record? send( path.pluralize + '_path' ) else send( path.singularize + '_path', object ) end link_to "Cancel", path, options end # Add a cancel link for shared forms. Looks at the provided object and either # creates a link to the index or show actions. def cancel_button(options = {}) # path = object.class.name.tableize # path = if object.new_record? # send(path.pluralize + '_path') # else # send(path.singularize + '_path', object) # end # button_to_function(t(:generic_cancel), 'history.back()', options) button_tag(t(:generic_cancel), options.merge({:onclick => 'history.back()'})) end def help_icon( dom_id ) # image_tag('help.png', :id => "help-icn-#{dom_id}", :class => 'help-icon', "data-help" => dom_id ) content_tag(:span, '', :id => "help-icn-#{dom_id}", :class => 'help-icon ui-icon-question-sign', "data-help" => dom_id) end def info_icon( image, dom_id ) image_tag( image , :id => "help-icn-#{dom_id}", :class => 'help-icn', "data-help" => dom_id ) end def form_errors object html = "" if object.errors.any? html << '<div class="alert alert-error">' html << '<h4 class="alert-heading">' + pluralize(object.errors.count, "error(s)") + '</h4>' html << '<ul>' object.errors.full_messages.each do |msg| html << '<li>'+ msg +'</li>' end html << '</ul>' html << '</div>' end raw html end def app_version Rails.configuration.app_version end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/helpers/domains_helper.rb
app/helpers/domains_helper.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module DomainsHelper def select_record_type( form ) types = if current_user RecordTemplate.record_types.map{ |t| [t,t] } - [["SOA", "SOA"]] else current_token.new_types end form.select( :type, types ) end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/helpers/macro_steps_helper.rb
app/helpers/macro_steps_helper.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module MacroStepsHelper end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/helpers/templates_helper.rb
app/helpers/templates_helper.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module TemplatesHelper end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/helpers/auth_tokens_helper.rb
app/helpers/auth_tokens_helper.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module AuthTokensHelper end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/helpers/audits_helper.rb
app/helpers/audits_helper.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module AuditsHelper def updated_changes (audit) if audit.action == "update" begin changes = audit.audited_changes record = Record.find(audit.auditable_id).attributes.except('created_at', 'updated_at') changes.keys.each do |key| record.delete(key) end changes.merge(record) rescue changes = audit.audited_changes audit_record = Audited::Adapters::ActiveRecord::Audit.where(auditable_id: audit.auditable_id, action: "create") || Audited::Adapters::ActiveRecord::Audit.where(auditable_id: audit.auditable_id, action: "destroy") unless audit_record.empty? record = audit_record.first['audited_changes'] audit.audited_changes.merge(record) end end else audit.audited_changes end end def parenthesize( text ) "(#{text})" end def link_to_domain_audit( audit ) caption = "#{audit.version} #{audit.action} by " caption << audit_user( audit ) link_to_function caption, "toggleDomainAudit(#{audit.id})" end def link_to_record_audit( audit ) caption = audit.audited_changes['type'] caption ||= (audit.auditable.nil? ? '[UNKNOWN]' : audit.auditable.class.to_s ) unless audit.audited_changes['name'].nil? name = audit.audited_changes['name'].is_a?( Array ) ? audit.audited_changes['name'].pop : audit.audited_changes['name'] caption += " (#{name})" end caption += " #{audit.version} #{audit.action} by " caption += audit_user( audit ) link_to_function caption, "toggleRecordAudit(#{audit.id})" end def display_hash( hash ) hash ||= {} hash.map do |k,v| if v.nil? nil # strip out non-values else if v.is_a?( Array ) v = "From <em>#{v.shift}</em> to <em>#{v.shift}</em>" end "<em>#{k}</em>: #{v}" end end.compact.join('<br />') end def sort_audits_by_date( collection ) collection.sort_by(&:created_at).reverse end def audit_user( audit ) if audit.user.is_a?( User ) audit.user.name else audit.username || 'UNKNOWN' end end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/controllers/bind9_controller.rb
app/controllers/bind9_controller.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class Bind9Controller < ApplicationController include GloboDns::Config respond_to :html, :json responders :flash before_filter :admin?, :except => :schedule_export before_filter :admin_or_operator?, :only => :schedule_export def index get_current_config end def configuration get_current_config respond_with(@current_config) do |format| format.html { render :text => @current_config if request.xhr? } end end def export if params['now'].try(:downcase) == 'true' @output, status = run_export else scheduled = Schedule.run_exclusive :schedule do |s| s.date end if scheduled.nil? @output = I18n.t('no_export_scheduled') status = :ok elsif scheduled <= DateTime.now @output, status = run_export else @output = I18n.t('export_scheduled', :timestamp => scheduled) status = :ok end end respond_to do |format| format.html { render :status => status, :layout => false } if request.xhr? format.json { render :status => status, :json => { ((status == :ok) ? 'output' : 'error') => @output } } end end def schedule_export # clear schedule, because will run now schedule_date = Schedule.run_exclusive :schedule do |s| # round up to the nearest round minute, as it's the smallest time grain # supported by cron jobs s.date ||= Time.at(((DateTime.now + EXPORT_DELAY.seconds).to_i / 60.0 + 1).round * 60) # sleep 20 # Keep this commented. Only for tests end @output = I18n.t('export_scheduled', :timestamp => schedule_date.to_formatted_s(:short)) respond_to do |format| format.html { render :status => status, :layout => false } if request.xhr? format.json { render :status => status, :json => { 'output' => @output, 'schedule_date' => "#{schedule_date}" } } end end private def get_current_config bind_config = GloboDns::Config::Bind @master_named_conf = GloboDns::Exporter.load_named_conf(bind_config::Master::EXPORT_CHROOT_DIR, bind_config::Master::NAMED_CONF_FILE) @slaves_named_confs = bind_config::Slaves.map do |slave| GloboDns::Exporter.load_named_conf(slave::EXPORT_CHROOT_DIR, slave::NAMED_CONF_FILE) if slave_enabled?(slave) end @slaves_named_confs.compact! end def run_export # create exporter before everything because it's necesary in rescue block exporter = GloboDns::Exporter.new # clear schedule, because will run now Schedule.run_exclusive :schedule do |s| s.date = nil end # I can't keep lock during all export because can cause troubles # if export is too long. So, I fill date field and clear in the end. Schedule.run_exclusive :export do |s| if not s.date.nil? logger.warn "There is another process running. To run export again, remove row #{s.id} in schedules table" raise "There is another process running" end # register last execution in schedule s.date = DateTime.now end begin # sleep 60 # Keep this commented. Only for tests exporter.export_all(params['master-named-conf'], params['slave-named-conf'], :all => params['all'] == 'true', :keep_tmp_dir => true, :reset_repository_on_failure => true) [ exporter.logger.string, :ok ] ensure Schedule.run_exclusive :export do |s| s.date = nil end end rescue Exception => e logger.error "[ERROR] export failed: #{e}" logger.error "backtrace: #{e.backtrace}" [ e.to_s, :unprocessable_entity ] end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/controllers/domains_controller.rb
app/controllers/domains_controller.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require 'domain_ownership' class DomainsController < ApplicationController include GloboDns::Config respond_to :html, :json responders :flash before_filter :admin_or_operator?, :except => [:index, :show] DEFAULT_PAGE_SIZE = 25 def index @ns = get_nameservers if GloboDns::Config::DOMAINS_OWNERSHIP users_permissions_info = DomainOwnership::API.instance.users_permissions_info(current_user) @sub_components = users_permissions_info[:sub_components] end session[:show_reverse_domains] = (params[:reverse] == 'true') if params.has_key?(:reverse) @domains = session[:show_reverse_domains] ? Domain.all : Domain.nonreverse @domains = @domains.includes(:records).paginate(:page => params[:page], :per_page => params[:per_page] || DEFAULT_PAGE_SIZE) if params[:query].present? params[:query].to_s.gsub(/^[ \t]/,'') @domains = @domains.matching(params[:query]) end if request.path_parameters[:format] == 'json' and (defined? GloboDns::Config::ENABLE_VIEW and GloboDns::Config::ENABLE_VIEW == true) if params[:view] view = View.where(name: params[:view]).first if view.nil? and params[:view] != "all" @domains = nil else params[:view_id] = (params[:view] == "all"? "all" : view.id) end else params[:view_id] = View.where(name: "default").first.id end end @domains = @domains.where(view_id: params[:view_id]) if params[:view_id] and params[:view_id] != '' and params[:view_id] != 'all' respond_with(@domains) do |format| format.html { render :partial => 'list', :object => @domains, :as => :domains if request.xhr? } end end def show @domain = Domain.find(params[:id]) if GloboDns::Config::DOMAINS_OWNERSHIP users_permissions_info = DomainOwnership::API.instance.users_permissions_info(current_user) @sub_components = users_permissions_info[:sub_components] @domain_ownership_info = DomainOwnership::API.instance.get_domain_ownership_info(@domain.name) end query = params[:records_query].blank? ? nil : params[:records_query].gsub("%","*") if query.nil? @records = @domain.records.without_soa.paginate(:page => params[:page], :per_page => params[:per_page] || DEFAULT_PAGE_SIZE) else @records = @domain.records.without_soa.matching(params[:records_query]).paginate(:page => params[:page], :per_page => params[:per_page] || DEFAULT_PAGE_SIZE) end @sibling = @domain.sibling if @domain.sibling @sibling_records = @sibling.records.without_soa.paginate(:page => params[:page], :per_page => params[:per_page] || DEFAULT_PAGE_SIZE) if @sibling respond_with(@domain) end def new @domain = Domain.new respond_with(@domain) end def edit @domain = Domain.find(params[:id]) respond_with(@domain) end def create domain_template_in_params = false domain_view_in_params = false params[:domain].each do |label, value| params[:domain][label] = params[:domain][label].to_s.gsub(/^[ \t]/,'') unless value.nil? end if params[:domain][:domain_template_id].present? || params[:domain][:domain_template_name].present? domain_template_in_params = true @domain_template = DomainTemplate.find(params[:domain][:domain_template_id]) if params[:domain][:domain_template_id] @domain_template ||= DomainTemplate.where('name' => params[:domain][:domain_template_name]).first if params[:domain][:domain_template_name] end if params[:domain][:domain_view_id].present? || params[:domain][:domain_view_name].present? domain_view_in_params = true @domain_view = View.where('id' => params[:domain][:domain_view_id]).first if params[:domain][:domain_view_id] @domain_view ||= View.where('name' => params[:domain][:domain_view_name]).first if params[:domain][:domain_view_name] end if @domain_template @domain = @domain_template.build(params[:domain][:name]) else @domain = Domain.new(params[:domain].except(:domain_template_id, :domain_template_name)) end if @domain_view @domain.view = @domain_view end if domain_template_in_params && !@domain_template @domain.errors.add(:domain_template, 'Domain Template not found') end if domain_view_in_params && !@domain_view @domain.errors.add(:domain_view, 'Domain view not found') end # if 'uses_view' is set as true at 'globodns.yml', forces use default view when saving if defined? GloboDns::Config::ENABLE_VIEW and GloboDns::Config::ENABLE_VIEW == true @domain.view = View.default unless @domain.view end if @domain.export_to @domain.export_to = JSON.parse(params[:domain][:export_to]) - [""] @domain.export_to = nil if @domain.export_to.empty? end valid = (!@domain.errors.any? and @domain.valid?) ownership = true if GloboDns::Config::DOMAINS_OWNERSHIP unless current_user.admin? name_available = DomainOwnership::API.instance.get_domain_ownership_info(@domain.name)[:group].nil? permission = @domain.check_ownership(current_user) ownership = name_available or permission end end valid = (valid and ownership) if valid @domain.save if GloboDns::Config::DOMAINS_OWNERSHIP @domain.save @domain.set_ownership(params[:sub_component], current_user) @domain.records.each do |record| record.set_ownership(params[:sub_component], current_user) end end # flash[:warning] = "#{@domain.warnings.full_messages * '; '}" if @domain.has_warnings? && navigation_format? respond_with(@domain) do |format| format.html { render :status => valid ? :ok : :unprocessable_entity, :partial => valid ? @domain : 'errors' } if request.xhr? end end def destroy @domain = Domain.find(params[:id]) @domain.destroy respond_with(@domain) end def update_domain_owner @domain = Domain.find(params[:id]) if GloboDns::Config::DOMAINS_OWNERSHIP users_permissions_info = DomainOwnership::API.instance.users_permissions_info(current_user) @sub_components = users_permissions_info[:sub_components] @domain_ownership_info = DomainOwnership::API.instance.get_domain_ownership_info(@domain.name) if @domain_ownership_info[:id].nil? DomainOwnership::API.instance.post_domain_ownership_info(@domain.name, params[:sub_component], "domain", current_user) else DomainOwnership::API.instance.patch_domain_ownership_info(@domain_ownership_info[:id], @domain.name, params[:sub_component], "domain") end @domain_ownership_info = DomainOwnership::API.instance.get_domain_ownership_info(@domain.name) @domain = Domain.find(params[:id]) respond_to do |format| format.html { render :partial => 'owner_info' } end else end end end def update params[:domain].each do |label, value| params[:domain][label] = params[:domain][label].to_s.gsub(/^[ \t]/,'') unless (value.nil? or label == 'notes') end @domain = Domain.find(params[:id]) ownership = true if GloboDns::Config::DOMAINS_OWNERSHIP unless current_user.admin? ownership = !DomainOwnership::API.instance.get_domain_ownership_info(@domain.name)[:sub_component].nil? and @domain.check_ownership(current_user) end end valid = (!@domain.errors.any? and ownership) @domain.update_attributes(params[:domain]) if valid # flash[:warning] = "#{@domain.warnings.full_messages * '; '}" if @domain.has_warnings? && navigation_format? respond_with(@domain) do |format| format.html { render :status => valid ? :ok : :unprocessable_entity, :partial => valid ? 'form' : 'errors', :object => @domain, :as => :domain } if request.xhr? end end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/controllers/access_denied_controller.rb
app/controllers/access_denied_controller.rb
class AccessDeniedController < ApplicationController skip_before_filter :authenticate_user! def show respond_to do |format| format.html { render :status => :not_authorized, :file => File.join(Rails.root, 'public', '401.html'), :layout => nil } format.json { render :status => :forbidden, :json => {:error => 'NOT AUTHORIZED'} } end end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/controllers/omniauth_callbacks_controller.rb
app/controllers/omniauth_callbacks_controller.rb
class OmniauthCallbacksController < Devise::OmniauthCallbacksController skip_before_filter :authenticate_user! # def oauth_provider # @user = User.from_omniauth(request.env["omniauth.auth"]) # if @user.persisted? # if @user.active # sign_in_and_redirect @user, :event => :authentication #this will throw if @user is not activated # set_flash_message(:notice, :success, :kind => "oauth provider") if is_navigational_format? # else # session[:user_name] = @user.login # flash[:alert] = t "user_deactivated" # redirect_to access_denied_url # end # else # session["devise.oauth_provider_data"] = request.env["omniauth.auth"] # redirect_to new_user_session # end # end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/controllers/domain_templates_controller.rb
app/controllers/domain_templates_controller.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class DomainTemplatesController < ApplicationController respond_to :html, :json responders :flash before_filter :admin?, :except => [:show, :index] before_filter :admin_or_operator?, :only => [:show, :index] DEFAULT_PAGE_SIZE = 25 def index @domain_templates = DomainTemplate.all @domain_templates = @domain_templates.includes(:record_templates).paginate(:page => params[:page], :per_page => params[:per_page] || DEFAULT_PAGE_SIZE) respond_with(@domain_templates) do |format| format.html { render :partial => 'list', :object => @domain_templates, :as => :domain_templates if request.xhr? } end end def show @domain_template = DomainTemplate.find(params[:id]) unless request.xhr? @soa_record_template = @domain_template.record_templates.where('type = ?', 'SOA').first @record_templates = @domain_template.record_templates.where('type != ?', 'SOA').paginate(:page => params[:page], :per_page => params[:per_page] || DEFAULT_PAGE_SIZE) end respond_with(@domain_template) end def new @domain_template = DomainTemplate.new respond_with(@domain_template) end def edit @domain_template = DomainTemplate.find(params[:id]) respond_with(@domain_template) end def create @domain_template = DomainTemplate.new(params[:domain_template]) @domain_template.save Rails.logger.info "[controller] after save" respond_with(@domain_template) do |format| format.html { render :status => @domain_template.valid? ? :ok : :unprocessable_entity, :partial => @domain_template.valid? ? @domain_template : 'errors' } if request.xhr? end end def update @domain_template = DomainTemplate.find(params[:id]) @domain_template.update_attributes(params[:domain_template]) respond_with(@domain_template) do |format| format.html { render :status => @domain_template.valid? ? :ok : :unprocessable_entity, :partial => @domain_template.valid? ? 'form' : 'errors' } if request.xhr? end end def destroy @domain_template = DomainTemplate.find(params[:id]) @domain_template.destroy respond_with(@domain_template) end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/controllers/records_controller.rb
app/controllers/records_controller.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require 'domain_ownership' class RecordsController < ApplicationController include RecordsHelper respond_to :html, :json responders :flash before_filter :admin_or_operator?, :except => [:index, :show] DEFAULT_PAGE_SIZE = 25 def index @records = Record.where(:domain_id => params[:domain_id]) @records = @records.without_soa.paginate(:page => params[:page] || 1, :per_page => params[:per_page] || DEFAULT_PAGE_SIZE) @records = @records.matching(params[:records_query]) if params[:records_query].present? @records = @records.matching(params[:query]) if params[:query].present? # when using api respond_with(@records) do |format| format.html { render :partial => 'list', :object => @records, :as => :records if request.xhr? } end end def show @record = Record.find(params[:id]) respond_with(@record) end def new @record = Record.new(:domain_id => params[:domain_id]) respond_with(@record) end def edit @record = Record.find(params[:id]) respond_with(@record) end def create if should_increase_ttl? params[:record][:ttl] = 60 unless (params[:record][:ttl] and params[:record][:ttl].to_i < 60) end params[:record].each do |label, value| params[:record][label] = params[:record][label].to_s.gsub(/^[ \t]/,'') unless value.nil? end @record = params[:record][:type].constantize.new(params[:record]) @record.domain_id = params[:domain_id] valid = (!@record.errors.any? and @record.valid?) ownership = true if GloboDns::Config::DOMAINS_OWNERSHIP ownership = @record.check_ownership(current_user, true) unless current_user.admin? end valid = (valid and ownership) if valid @record.save if GloboDns::Config::DOMAINS_OWNERSHIP @record.set_ownership(params[:sub_component], current_user) end end flash[:warning] = "#{@record.warnings.full_messages * '; '}" if @record.has_warnings? respond_with(@record.becomes(Record)) do |format| format.html { render :status => valid ? :ok : :unprocessable_entity, :partial => valid ? @record : 'errors' } if request.xhr? end end def update if should_increase_ttl? params[:record][:ttl] = 60 unless (params[:record][:ttl] and params[:record][:ttl].to_i < 60) end params[:record].each do |label, value| params[:record][label] = params[:record][label].to_s.gsub(/^[ \t]/,'') unless value.nil? end @record = Record.find(params[:id]) valid = (!@record.errors.any? and @record.valid?) ownership = true old_ownership_info = nil new_ownership_info = nil if GloboDns::Config::DOMAINS_OWNERSHIP unless current_user.admin? ownership = @record.check_ownership(current_user) name_changed = !(@record.name.eql? params[:record][:name]) if name_changed old_ownership_info = DomainOwnership::API.instance.get_domain_ownership_info @record.url DomainOwnership::API.instance.delete_domain @record.name @record.name = params[:record][:name] new_ownership_info = DomainOwnership::API.instance.get_domain_ownership_info @record.url end end end valid = (valid and ownership) if valid and GloboDns::Config::DOMAINS_OWNERSHIP @record.update_attributes(params[:record]) @record.set_ownership(old_ownership_info[:sub_component_id], current_user) if name_changed and new_ownership_info[:group_id].nil? end flash[:warning] = "#{@record.warnings.full_messages * '; '}" if @record.has_warnings? respond_with(@record.becomes(Record)) do |format| format.html { render :status => valid ? :ok : :unprocessable_entity, :partial => valid ? @record : 'errors' } if request.xhr? end end def destroy @record = Record.find(params[:id]) @record.destroy respond_with(@record) do |format| format.html { head :no_content if request.xhr? } end end def resolve @record = Record.find(params[:id]) @response = @record.resolve if Record::testable_types.include? @record.type respond_to do |format| format.html { render :partial => 'resolve' } if request.xhr? # format.json { render :json => {'master' => @master_response, 'slave' => @slave_response}.to_json } end end def update_domain_owner @record = Record.find(params[:id]) if GloboDns::Config::DOMAINS_OWNERSHIP users_permissions_info = DomainOwnership::API.instance.users_permissions_info(current_user) @sub_components = users_permissions_info[:sub_components] @record_ownership_info = DomainOwnership::API.instance.get_domain_ownership_info(@record.url) if @record_ownership_info[:id].nil? DomainOwnership::API.instance.post_domain_ownership_info(@record.url, params[:sub_component], "domain", current_user) else DomainOwnership::API.instance.patch_domain_ownership_info(@record_ownership_info[:id], @record.url, params[:sub_component], "domain") end @record_ownership_info = DomainOwnership::API.instance.get_domain_ownership_info(@record.url) @record = Record.find(params[:id]) respond_to do |format| format.html { render :partial => 'owner_info' } end else end end def verify_owner @record = Record.find(params[:id]) if GloboDns::Config::DOMAINS_OWNERSHIP users_permissions_info = DomainOwnership::API.instance.users_permissions_info(current_user) @sub_components = users_permissions_info[:sub_components] @record_ownership_info = DomainOwnership::API.instance.get_domain_ownership_info(@record.url) end @record = Record.find(params[:id]) respond_to do |format| format.html { render :partial => 'owner_info' } if request.xhr? end end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/controllers/dashboard_controller.rb
app/controllers/dashboard_controller.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require 'domain_ownership' class DashboardController < ApplicationController include GloboDns::Config def index @ns = get_nameservers if GloboDns::Config::DOMAINS_OWNERSHIP users_permissions_info = DomainOwnership::API.instance.users_permissions_info(current_user) @sub_components = users_permissions_info[:sub_components] end @latest_domains = Domain.nonreverse.reorder('created_at DESC').limit(5) end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/controllers/views_controller.rb
app/controllers/views_controller.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class ViewsController < ApplicationController respond_to :html, :json responders :flash before_filter :admin? def index @views = View.all @views = @views.paginate(:page => params[:page], :per_page => 5) if request.format.html? || request.format.js? @views = @views.where(name: params[:query]) if params[:query] respond_with(@views) do |format| format.html { render :partial => 'list', :object => @views, :as => :views if request.xhr? } end end def show @view = View.find(params[:id]) respond_with(@view) end def new @view = View.new respond_with(@view) end def edit @view = View.find(params[:id]) respond_with(@view) end def create @view = View.new(params[:view]) @view.save respond_with(@view) do |format| format.html { render :status => @view.valid? ? :ok : :unprocessable_entity, :partial => @view.valid? ? @view : 'errors' } if request.xhr? end end def update if params[:view] && params[:view][:password].blank? && params[:view][:password_confirmation].blank? params[:view].delete(:password) params[:view].delete(:password_confirmation) end @view = View.find(params[:id]) @view.update_attributes(params[:view]) respond_with(@view) do |format| format.html { render :status => @view.valid? ? :ok : :unprocessable_entity, :partial => @view.valid? ? @view : 'errors' } if request.xhr? end end def destroy @view = View.find(params[:id]) @view.destroy respond_with(@view) do |format| format.html { head :no_content if request.xhr? } end end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/controllers/users_controller.rb
app/controllers/users_controller.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class UsersController < ApplicationController respond_to :html, :json responders :flash before_filter :admin?, :except => [:update_password, :save_password_update] def index @users = User.all if params[:user_query] @users = User.where("login like :login or email like :email", login: "%#{params[:user_query]}%", email: "%#{params[:user_query]}%") end @users = @users.paginate(:page => params[:page], :per_page => 25) if request.format.html? || request.format.js? respond_with(@users) do |format| format.html { render :partial => 'list', :object => @users, :as => :users if request.xhr? } end end def show @user = User.find(params[:id]) respond_with(@user) end def new @user = User.new respond_with(@user) end def edit @user = User.find(params[:id]) respond_with(@user) end def update_password @user = User.find(current_user.id) respond_to do |format| format.html end end def save_password_update @user = User.find(current_user.id) logger.info "Changing password for user #{@user.email}" if @user.update_attributes(:password => params[:user][:password], :password_confirmation => params[:user][:password_confirmation]) @user.save redirect_to(root_path, :notice => t(:successful_password_change, :user => @user.email)) else render :action => :update_password end end def create @user = User.new(params[:user]) @user.save respond_with(@user) do |format| format.html { render :status => @user.valid? ? :ok : :unprocessable_entity, :partial => @user.valid? ? @user : 'errors' } if request.xhr? end end def update if params[:user] && params[:user][:password].blank? && params[:user][:password_confirmation].blank? params[:user].delete(:password) params[:user].delete(:password_confirmation) end @user = User.find(params[:id]) @user.update_attributes(params[:user]) respond_with(@user) do |format| format.html { render :status => @user.valid? ? :ok : :unprocessable_entity, :partial => @user.valid? ? @user : 'errors' } if request.xhr? end end def destroy @user = User.find(params[:id]) @user.destroy respond_with(@user) do |format| format.html { head :no_content if request.xhr? } end end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/controllers/record_templates_controller.rb
app/controllers/record_templates_controller.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class RecordTemplatesController < ApplicationController respond_to :html, :json responders :flash before_filter :admin? DEFAULT_PAGE_SIZE = 25 def index @record_templates = RecordTemplate.where(:domain_template_id => params[:domain_template_id]) @record_templates = @record_templates.without_soa.paginate(:page => params[:page], :per_page => params[:per_page] || DEFAULT_PAGE_SIZE) respond_with(@record_templates) do |format| format.html { render :partial => 'list', :object => @record_templates, :as => :record_templates if request.xhr? } end end def show @record_template = RecordTemplate.find(params[:id]) end def new @record_template = RecordTemplate.new(:domain_template_id => params[:domain_template_id]) respond_with(@record_template) end def edit @record_template = RecordTemplate.find(params[:id]) respond_with(@record_template) end def create @record_template = RecordTemplate.new(params[:record_template]) @record_template.domain_template_id = params[:domain_template_id] @record_template.save respond_with(@record_template) do |format| format.html { render :status => @record_template.valid? ? :ok : :unprocessable_entity, :partial => @record_template.valid? ? @record_template : 'errors' } if request.xhr? end end def update @record_template = RecordTemplate.find(params[:id]) @record_template.update(params[:record_template]) respond_with(@record_template) do |format| format.html { render :status => @record_template.valid? ? :ok : :unprocessable_entity, :partial => @record_template.valid? ? @record_template : 'errors' } if request.xhr? end end def destroy @record_template = RecordTemplate.find(params[:id]) @record_template.destroy respond_with(@record_template) do |format| format.html { head :no_content if request.xhr? } end end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/controllers/reports_controller.rb
app/controllers/reports_controller.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class ReportsController < ApplicationController before_filter do unless current_user.admin? redirect_to root_url end end # search for a specific user def index @users = User.where(:admin => false).paginate(:page => params[:page]) @total_domains = Domain.count @system_domains = Domain.where('user_id IS NULL').count end def results if params[:q].chomp.blank? redirect_to reports_path else @results = User.search(params[:q], params[:page]) end end def view @user = User.find(params[:id]) end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/controllers/audits_controller.rb
app/controllers/audits_controller.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class AuditsController < ApplicationController respond_to :html, :json responders :flash before_filter :admin_or_operator? def index @audits = Audited::Adapters::ActiveRecord::Audit.includes(:user) # filtros dos logs if params[:audit_days] || params[:audit_hours] || params[:audit_mins] @audits = @audits.where('created_at >= :time_ago', :time_ago => Time.now - params[:audit_days].to_i.days - params[:audit_hours].to_i.hours - params[:audit_mins].to_i.minutes) end if params[:audit_action] @audits = @audits.where(action: params[:audit_action]) unless params[:audit_action] == "all" end if params[:audit_user] && params[:audit_user] != "" user = User.where("login like :login", login: "%#{params[:audit_user]}%").first user = User.where("email like :email", email: "%#{params[:audit_user]}%").first if user.nil? @audits = @audits.where(user: user) end if params[:audit_content] && params[:audit_content] != "" ids = [] @audits.each do |a| if a.action == "update" and a['audited_changes'].keys.include? 'content' a['audited_changes']['content'].each do |c| ids.push(a.id) if c.include? params[:audit_content] end else ids.push(a.id) if a['audited_changes']['content'] == params[:audit_content] end end @audits = @audits.where({id: ids}) end if params[:audit_record] && params[:audit_record] != "" ids = [] @audits.where(auditable_type: "Record").each do |a| ids.push(a.id) if a['audited_changes']['name'] == params[:audit_record] end @audits = @audits.where({id: ids}) end if params[:audit_record_type] && params[:audit_record_type] != "" ids = [] @audits.where(auditable_type: "Record").each do |a| ids.push(a.id) if a['audited_changes']['type'] == params[:audit_record_type] end @audits = @audits.where({id: ids}) end if params[:audit_domain] && params[:audit_domain] != "" ids = [] domain_id = 0 if domain = Domain.where(name: params[:audit_domain]).first # o dominio buscado ainda existe no banco de dados @audits.where(auditable_type: "Record").each do |a| id = a['audited_changes']['domain_id'] || a.associated_id ids.push(a.id) if id == domain.id end @audits.where(auditable_type: "Domain").each do |a| if a.associated_id? ids.push(a.id) if a.associated_id == domain.id elsif !a['audited_changes']['name'].nil? ids.push(a.id) if a['audited_changes']['name'] == params[:audit_domain] else ids.push(a.id) if Record.find(a.auditable_id).domain.id == domain.id end end else # procura a id do dominio nos logs dos domains deletados deleted = Audited::Adapters::ActiveRecord::Audit.where(auditable_type: "Domain", action: "Destroy") deleted.each do |d| if d['audited_changes']['name'] == params[:audit_domain] domain_id = d.auditable_id break end end # o dominio buscado foi deletado if domain_id != 0 @audits.where(auditable_type: "Record").each do |a| id = a['audited_changes']['domain_id'] || a.associated_id ids.push(a.id) if id == domain_id end @audits.where(auditable_type: "Domain").each do |a| if a.associated_id? ids.push(a.id) if a.associated_id == domain_id elsif !a['audited_changes']['name'].nil? ids.push(a.id) if a['audited_changes']['name'] == params[:audit_domain] else ids.push(a.id) if Record.find(a.auditable_id).domain.id == domain_id end end # dominio nunca existiu else end end @audits = @audits.where({id: ids}) end # fim dos filtros @audits = @audits.reorder('id DESC').paginate(:page => params[:page] || 1, :per_page => 20) if request.format.html? || request.format.js? respond_with(@audits) do |format| format.html { render :partial => 'list', :object => @audits, :as => :audits if request.xhr? } end end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/controllers/auth_tokens_controller.rb
app/controllers/auth_tokens_controller.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class AuthTokensController < DeviseController # skip_before_filter :authenticate_user!, :only => [:token] # before_filter do # unless current_user.auth_tokens? # redirect_to root_url # end # end # Create a new #AuthToken. See #AuthToken for the finer details on # how authentication tokens work. # # Expects an XML POST to /auth_token.xml with the following # information: # # <auth_token> # <domain>name</domain> # <expires_at>RFC822 timestamp</expires_at> # <policy>token policy</policy> # <allow_new>true/false</allow_new> # <remove>true</false> # <!-- record tag for each record --> # <record>...</record> # <record>...</record> # <!-- protect_type tag for each type to be protected --> # <protect_type>...</protect_type> # <protect_type>...</protect_type> # <!-- protect tag for each record to protect --> # <protect>...</protect> # </auth_token> # # Returns the following when successful: # # <token> # <url>...</url> # <auth_token>...</auth_token> # <expires>...</expires> # </token> # # Or on failure: # # <error>Message</error> # # def create # if params[:auth_token].blank? # render :status => 422, :xml => <<-EOS #<error>#{t(:message_token_missing_parametr)}</error> #EOS # return false # end # # # Get our domain # domain = Domain.find_by_name( params[:auth_token][:domain] ) # if domain.nil? # render :text => t(:message_domain_not_found), :status => 404 # return # end # # # expiry time # t = params[:auth_token][:expires_at].present? ? Time.parse( params[:auth_token][:expires_at] ) : nil # # # Our new token # @auth_token = AuthToken.new( # :domain => domain, # :user => current_user, # :expires_at => t # ) # # # Build our token from here on # @auth_token.policy = params[:auth_token][:policy] unless params[:auth_token][:policy].blank? # @auth_token.allow_new_records = ( params[:auth_token][:allow_new] == "true" ) unless params[:auth_token][:allow_new].blank? # @auth_token.remove_records = ( params[:auth_token][:remove] == "true" ) unless params[:auth_token][:remove].blank? # # if params[:auth_token][:protect_type] && params[:auth_token][:protect_type].size > 0 # params[:auth_token][:protect_type].each do |t| # @auth_token.protect_type( t ) # end # end # # if params[:auth_token][:record] && params[:auth_token][:record].size > 0 # params[:auth_token][:record].each do |r| # name, type = r.split(':') # @auth_token.can_change( name, type || '*' ) # end # end # # if params[:auth_token][:protect] && params[:auth_token][:protect].size > 0 # params[:auth_token][:protect].each do |r| # name, type = r.split(':') # @auth_token.protect( name, type || '*' ) # end # end # # if @auth_token.save # render :status => 200, :xml => <<-EOF # <token> # <expires>#{@auth_token.expires_at}</expires> # <auth_token>#{@auth_token.token}</auth_token> # <url>#{token_url( :token => @auth_token.token )}</url> # </token> # EOF # else # render :status => 500, :xml => <<-EOF # <error> # #{@auth_token.errors.to_xml} # </error> # EOF # end # end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/controllers/sessions_controller.rb
app/controllers/sessions_controller.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class SessionsController < Devise::SessionsController skip_before_filter :login_required, :except => [ :destroy ] def create resource = warden.authenticate!(auth_options) set_flash_message(:notice, :signed_in) if is_navigational_format? sign_in(resource_name, resource) respond_with resource, :location => after_sign_in_path_for(resource) do |format| format.json { render :status => :ok, :json => resource.auth_json } end end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/controllers/application_controller.rb
app/controllers/application_controller.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class ApplicationController < ActionController::Base HTTP_AUTH_TOKEN_HEADER = 'X-Auth-Token' protect_from_forgery with: :exception protect_from_forgery with: :null_session, if: Proc.new { |c| c.request.format =~ %r{application/json} } before_filter :check_auth before_filter :authenticate_user! after_filter :flash_headers rescue_from Exception, :with => :render_500 rescue_from ActiveRecord::RecordNotFound, :with => :render_404 rescue_from ActionController::RoutingError, :with => :render_404 rescue_from ActionController::UnknownController, :with => :render_404 rescue_from AbstractController::ActionNotFound, :with => :render_404 helper_method :admin?, :operator?, :admin_or_operator?, :viewer? def new_session_path(scope) new_user_session_path end def admin? current_user.admin? or render_401 end def operator? current_user.operator? or render_401 end def admin_or_operator? (current_user.admin? || current_user.operator?) or render_401 end def viewer? current_user.viewer? or render_401 end def logout sign_out current_user path = new_user_session_url client_id = Rails.application.secrets.oauth_provider_client_id redirect_to "https://oauthprovider.com/logout"+ "?client_id=#{client_id}&redirect_uri=#{path}" # set providers logout uri end protected def flash_headers return unless request.xhr? if flash[:error].present? response.headers['x-flash'] = flash[:error] response.headers['x-flash-type'] = 'error' elsif flash[:warning].present? response.headers['x-flash'] = flash[:warning] response.headers['x-flash-type'] = 'warning' elsif flash[:notice].present? response.headers['x-flash'] = flash[:notice] response.headers['x-flash-type'] = 'notice' end flash.discard end def render_401 respond_to do |format| format.html { render :status => :not_authorized, :file => File.join(Rails.root, 'public', '401.html'), :layout => nil } format.json { render :status => :forbidden, :json => {:error => 'NOT AUTHORIZED'} } end end def render_403 respond_to do |format| format.html { render :status => :forbidden, :file => File.join(Rails.root, 'public', '403.html'), :layout => nil } format.json { render :status => :forbidden, :json => {:error => 'FORBIDDEN'} } end end def render_404(exception) respond_to do |format| format.html { render :status => :not_found, :file => File.join(Rails.root, 'public', '404.html'), :layout => nil } format.json { render :status => :not_found, :json => { :error => 'NOT FOUND' } } end end def render_500(exception) logger.info "[Internal Server Error] exception: #{exception}\n#{exception.backtrace.join("\n")}" respond_to do |format| format.json { render :status => :internal_server_error, :json => { :error => exception.message, :backtrace => exception.backtrace } } format.html { raise(exception) } end end def navigation_format? request.format.html? || request.format.js? end private def login_present? if !params[:user].nil? !params[:user][:email].blank? && !params[:user][:password].blank? else false end end def token_present? !request.env['HTTP_X_AUTH_TOKEN'].nil? end def check_auth if !(res = request.env['HTTP_AUTHORIZATION']).nil? type, token = res.split(' ') if !type.nil? && type.eql?('Bearer') resource = RestClient::Resource.new(OmniAuth::YourProvider::Client.client_options(Rails.env)[:site]) # set the OAut hProvider begin response = JSON.parse(resource['user'].get(:Authorization => "Bearer #{token}")) response['token'] = token user = User.from_api(response) logger.debug "User: #{user.inspect}" if user.active sign_in user, :store => false end rescue Exception => e logger.error e.message end end elsif login_present? && request.format == "text/x-json" user = User.find_by_email(params[:user][:email]) if user && user.valid_password?(params[:user][:password]) sign_in user respond_to do |format| format.json { render :status => :ok, :json => current_user.auth_json } end end elsif token_present? user = User.find_by_authentication_token(request.env['HTTP_X_AUTH_TOKEN']) if user sign_in user end end end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/controllers/search_controller.rb
app/controllers/search_controller.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class SearchController < ApplicationController def results if params[:q].chomp.blank? respond_to do |format| format.html { redirect_to root_path } format.json { render :status => 404, :json => { :error => "Missing 'q' parameter" } } end else @results = Domain.search(params[:q], params[:page], current_user) respond_to do |format| format.html do if @results.size == 1 redirect_to domain_path(@results.pop) end end format.json do render :json => @results.to_json(:only => [:id, :name]) end end end end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/models/user_observer.rb
app/models/user_observer.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class UserObserver < ActiveRecord::Observer def after_create(user) UserMailer.deliver_signup_notification(user) end def after_save(user) UserMailer.deliver_activation(user) if user.recently_activated? end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/models/nsec3param.rb
app/models/nsec3param.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # = NSEC3 parameters Record (NSEC3PARAM) # # Parameter record for use with NSEC3 class NSEC3PARAM < Record def resolv_resource_class Resolv::DNS::Resource::IN::NSEC3PARAM end def match_resolv_resource(resource) resource.strings.join(' ') == self.content.chomp('.') end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/models/dlv.rb
app/models/dlv.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # = DNSSEC Lookaside Validation Record (DLV) # # For publishing DNSSEC trust anchors outside of the DNS delegation chain. Uses # the same format as the DS record. RFC 5074 describes a way of using these # records. class DLV < Record def resolv_resource_class Resolv::DNS::Resource::IN::DLV end def match_resolv_resource(resource) resource.strings.join(' ') == self.content.chomp('.') end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/models/record.rb
app/models/record.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # = Record # # The parent class for all our DNS RR's. Used to apply global rules and logic # that can easily be applied to any DNS RR's class Record < ActiveRecord::Base include RecordsHelper include SyslogHelper include BindTimeFormatHelper include ModelSerializationWithWarnings belongs_to :domain, :inverse_of => :records attr_accessor :importing attr_accessible :domain_id, :name, :type, :content, :ttl, :prio, :weight, :port, :tag audited :associated_with => :domain self.non_audited_columns.delete(self.inheritance_column) # audit the 'type' column validates_presence_of :domain validates_presence_of :name validates_presence_of :content validates_bind_time_format :ttl validate :validate_content_characters validate :validate_generate validate :validate_name_cname, :unless => :importing? validate :validate_name_format, :unless => :importing? validate :validate_recursive_subdomains, :unless => :importing? validate :validate_same_record, :unless => :importing? validate :validate_txt, :unless => :importing? validate :ensure_quoted_content # validations that generate 'warnings' (i.e., doesn't prevent 'saving' the record) validation_scope :warnings do |scope| scope.validate :validate_same_name_and_type scope.validate :check_cname_content scope.validate :check_a_content end class_attribute :batch_soa_updates # this is needed here for generic form support, actual functionality # implemented in #SOA # attr_accessor :primary_ns, :contact, :refresh, :retry, :expire, :minimum attr_protected :domain_id protected_attributes.delete('type') # 'type' is a special inheritance column use by Rails and not accessible by default; # before_validation :inherit_attributes_from_domain # before_save :update_change_date # after_save :update_soa_serial after_destroy :update_domain_timestamp after_save :update_domain_timestamp after_update :update_domain_timestamp before_save :reset_prio before_save :ipv6_remove_leading_zeros, :if => :is_ipv6? scope :sorted, -> {order('name ASC')} scope :to_update_ttl, -> {without_soa.where('updated_at < ?',DateTime.now - 7.days).where('ttl >= ?', 60)} scope :without_soa, -> {where('type != ?', 'SOA')} scope :soa, -> {find_by(type: 'SOA')} scope :updated_since, -> (timestamp) { where('updated_at > ?', timestamp) } scope :matching, -> (query){ query.gsub!(/:0{,4}/,":").gsub!(/:{3,}/,"::") if query.include? ":" if query.index('*') query.gsub!(/\*/, '%') where('name LIKE ? OR content LIKE ?', query, query) else where('name = ? OR content = ?', query, query) end } # known record types @@record_types = %w(AAAA A CERT CNAME DLV DNSKEY DS IPSECKEY KEY KX LOC MX NSEC3PARAM NSEC3 NSEC NS PTR RRSIG SIG SOA SPF SRV TA TKEY TSIG TXT CAA) @@high_priority_types = %w(A MX CNAME TXT NS) @@testable_types = %w(A AAAA MX CNAME TXT SRV) @@caa_tags = %w(issue issuewild ideof) cattr_reader :record_types cattr_reader :high_priority_types cattr_reader :testable_types cattr_reader :caa_tags def self.last_update select('updated_at').order('updated_at DESC').limit(1).first.updated_at end class << self # Restrict the SOA serial number updates to just one during the execution # of the block. Useful for batch updates to a zone def batch raise ArgumentError, "Block expected" unless block_given? self.batch_soa_updates = [] yield self.batch_soa_updates = nil end # Make some ammendments to the acts_as_audited assumptions def configure_audits record_types.map(&:constantize).each do |klass| defaults = [klass.non_audited_columns ].flatten defaults.delete( klass.inheritance_column ) # defaults.push( :change_date ) klass.write_inheritable_attribute :non_audited_columns, defaults.flatten.map(&:to_s) end end end def shortname self[:name].gsub( /\.?#{self.domain.name}$/, '' ) end def shortname=( value ) self[:name] = value end def export_name (name == self.domain.name) ? '@' : (shortname.presence || (name + '.')) end # pull in the name & TTL from the domain if missing def inherit_attributes_from_domain #:nodoc: self.ttl ||= self.domain.ttl if self.domain end # update the change date for automatic serial number generation # def update_change_date # self.change_date = Time.now.to_i # end # def update_soa_serial #:nodoc: # unless self.type == 'SOA' || @serial_updated || self.domain.slave? # self.domain.soa_record.update_serial! # @serial_updated = true # end # end # by default records don't support priorities, weight and port. Those who do can overwrite # this in their own classes. def supports_tag? false end def supports_prio? false end def supports_weight? false end def supports_port? false end def is_ipv6? self.type == 'AAAA' end def set_ownership(sub_component, user) if GloboDns::Config::DOMAINS_OWNERSHIP DomainOwnership::API.instance.post_domain_ownership_info(self.url, sub_component, "record", user) if DomainOwnership::API.instance.get_domain_ownership_info(self.url)[:sub_component].nil? end end def check_ownership(user, creation = false) if GloboDns::Config::DOMAINS_OWNERSHIP permission = DomainOwnership::API.instance.has_permission?(self.url, user) if (creation and !permission) sub_domain = self.domain.name splited = self.url.chomp(sub_domain).split(".") splited.delete_at(0) unless splited.empty? ended = false while(!permission and !ended) permission = DomainOwnership::API.instance.has_permission?(sub_domain, user) if splited.empty? ended = true else sub_domain = splited.pop + "." + sub_domain end end end end self.errors.add(:base, "User doesn't have ownership of '#{self.url}'") unless permission permission end def url if self.name.ends_with? '.' self.name.chomp('.') elsif self.name != '@' "#{self.name}.#{self.domain.name}" else self.domain.name end end def match_content content if self.type == "AAAA" self.content.split(":").collect{|i| i.to_i} == content.split(":").collect{|i| i.to_i} else self.content.delete("\"") == content or self.content == content or self.content == content+'.' or self.content+"."+self.domain.name == content or self.content+"."+self.domain.name+"." == content or self.content.chomp(self.domain.name+".") == content end end def domain_ttl if self.domain.ttl.ends_with? "D" return self.domain.ttl.to_i * 3600 * 24 elsif self.domain.ttl.ends_with? "H" return self.domain.ttl.to_i * 3600 elsif self.domain.ttl.ends_with? "M" return self.domain.ttl.to_i * 60 else return self.domain.ttl.to_i end end def increase_ttl if GloboDns::Config::INCREASE_TTL new_ttl = self.ttl.to_i * 3 if self.ttl.nil? Rails.logger.info "[Record] TTL of '#{self.name}' has the zone's default TTL (#{self.domain.name})" elsif new_ttl >= domain_ttl if self.update(ttl: nil) Rails.logger.info "[Record] '#{self.name}' (#{self.domain.name}) now have zone's default TTL" else Rails.logger.info "[Record] 'ERROR: Could not set TTL #{new_ttl} to #{self.name}' (#{self.domain.name})" end else if self.update(ttl: new_ttl) Rails.logger.info "[Record] '#{self.name}' (#{self.domain.name}) now have TTL of #{self.ttl}" else Rails.logger.info "[Record] 'ERROR: Could not set TTL #{new_ttl} to #{self.name}' (#{self.domain.name})" end end else Rails.logger.info "[Record] Increasing TTL is disabled" end end def ipv6_remove_leading_zeros self.content = ipv6_without_leading_zeros(self.content) end def ipv6_without_leading_zeros ip IPAddr.new(ip).to_s end def responding_from_dns_server server res = [] resolver = Resolv::DNS.new(:nameserver => server) begin Timeout::timeout(1) { answers = resolver.getresources(self.url, self.resolve_resource_class) answers.each do |answer| case self.type when "A", "AAAA" res.push({name: self.name, ttl: answer.ttl, content: answer.address.to_s}) when "TXT" res.push({name: self.name, ttl: answer.ttl, content: answer.strings.join.remove(" ")}) when "PTR" # ? when "CNAME", "NS" res.push({name: self.name, ttl: answer.ttl, content: answer.name.to_s}) when "SRV" res.push({name: self.name, ttl: answer.ttl, prio: answer.priority ,content: answer.target.to_s, port: answer.port, weight: answer.weight}) when "MX" res.push({name: self.name, ttl: answer.ttl, content: answer.exchange.to_s, prio: answer.preference}) end end } rescue res end res end def get_nameservers resolver = Resolv::DNS.new(:nameserver => GloboDns::Config::Bind::Master::IPADDR, :timeout => 5) servers = resolver.getresources(self.domain.name, Resolv::DNS::Resource::IN::NS) servers.collect {|server| server.name.to_s} end def resolve success = [] failed = [] # check authority servers response (servers from 'dig globo.com') servers = get_nameservers servers.each do |server| res = responding_from_dns_server(server) if !res.empty? res.each do |r| success.push({:content => r[:content], :prio => r[:prio], :port => r[:port], :weight => r[:weight], :server => "#{server}"}) end else failed.push({:server => server}) end end begin servers_extra = GloboDns::Config::ADDITIONAL_DNS_SERVERS rescue servers_extra = [] end # check additional servers response (additional servers should at 'globodns.yml') servers_extra.each do |server| res = responding_from_dns_server(server) if !res.empty? res.each do |r| success.push({:content => r[:content], :prio => r[:prio], :port => r[:port], :weight => r[:weight], :server => "#{server}"}) end else failed.push({:server => server}) end end return {:success => success, :failed => failed} # p = Net::Ping::External.new self.content # self.warnings.add(:content, I18n.t('a_content_invalid', content: self.content, :scope => 'activerecord.errors.messages')) unless p.ping? # [GloboDns::Resolver::MASTER.resolve(self), GloboDns::Resolver::SLAVE.resolve(self)] end # return the Resolv::DNS resource instance, based on the 'type' column def self.resolv_resource_class(type) case type when 'A'; Resolv::DNS::Resource::IN::A when 'AAAA'; Resolv::DNS::Resource::IN::AAAA when 'CNAME'; Resolv::DNS::Resource::IN::CNAME when 'LOC'; Resolv::DNS::Resource::IN::TXT # define a LOC class? when 'MX'; Resolv::DNS::Resource::IN::MX when 'NS'; Resolv::DNS::Resource::IN::NS when 'PTR'; Resolv::DNS::Resource::IN::PTR when 'SOA'; Resolv::DNS::Resource::IN::SOA when 'SPF'; Resolv::DNS::Resource::IN::TXT # define a SPF class? when 'SRV'; Resolv::DNS::Resource::IN::SRV when 'TXT'; Resolv::DNS::Resource::IN::TXT end end def resolve_resource_class self.class.resolv_resource_class(self.type) end def after_audit syslog_audit(self.audits.last) end # fixed partial path, as we don't need a different partial for each record type def to_partial_path Record._to_partial_path end def self.fqdn(record_name, domain_name) domain_name += '.' unless domain_name[-1] == '.' if record_name == '@' || record_name.nil? || record_name.blank? domain_name elsif record_name[-1] == '.' record_name # elsif record_name.end_with?(domain_name) # record_name else record_name + '.' + domain_name end end def fqdn self.class.fqdn(self.name, self.domain.name) end def fqdn_content? !self.content.nil? && self.content[-1] == '.' end def ensure_quoted_content if ['CAA', 'TXT'].include? self.type quoted_content = self.content quoted_content.insert(0,"\"") unless content.starts_with? "\"" quoted_content.insert(-1,"\"") unless content.ends_with? "\"" self.content = quoted_content end end def to_zonefile(output, format) # FIXME: fix ending '.' of content on the importer content = self.content content += '.' if self.content =~ /\.(?:com|net|org|br|in-addr\.arpa)$/ and self.type != "CAA" # content += '.' unless self.content[-1] == '.' || # self.type == 'A' || # self.type == 'AAAA' || # self.content =~ /\s\d{,3}\.\d{,3}\.\d{,3}\.\d{,3}$/ || # ipv4 # self.content =~ /\s[a-fA-F0-9:]+$/ # ipv6 # FIXME: zone2sql sets prio = 0 for all records # host ttl IN CAA prio tag content tag = (self.type == 'CAA')? self.tag : '' prio = ((self.type == 'CAA' or self.type == 'MX' or self.type == 'SRV') || (self.prio && (self.prio > 0)) ? self.prio : '') weight = (self.type == 'SRV' || self.weight)? self.weight : '' port = (self.type == 'SRV' || self.port)? self.port : '' ttl = (self.generate?)? '' : self.ttl.to_s || '' name = (self.generate?)? "\$GENERATE #{self.range} #{self.name}" : self.name type = (self.generate?)? self.type : "IN #{self.type}" output.printf(format, name, ttl, type, prio || '', tag || '', weight || '', port || '', content) end def importing? !!importing end def validate_generate if self.generate? self.errors.add(:base, I18n.t('record_generate_bad_range', :scope => 'activerecord.errors.messages')) unless valid_range? self.errors.add(:base, I18n.t('record_generate_missing_dollar', :scope => 'activerecord.errors.messages')) unless self.name.include? '$' or self.content.include? '$' end end def valid_range? format = self.range.match(/^(\d+)\-(\d+)[\/\d]*$/) return format[2] > format[1] unless format.nil? false end def validate_name_cname return if self.generate? id = self.id || 0 if self.type == 'CNAME' # check if the new cname record matches a old record name if record = Record.where(name: self.name, domain_id: self.domain_id).where("id != ?", id).first self.errors.add(:name, I18n.t('cname_name', :name => self.name, :type => record.type, :scope => 'activerecord.errors.messages')) return elsif record = Record.where(name: self.name+"."+self.domain.name+".", domain_id: self.domain_id).where("id != ?", id).first # check if there is a FQDN matching the record name self.errors.add(:name, I18n.t('cname_name', :name => self.name, :type => record.type, :scope => 'activerecord.errors.messages')) return elsif self.name.ends_with?'.' and record = Record.where(name: self.name.chomp("."+self.domain.name+"."), domain_id: self.domain_id).where("id != ?", id).first # check if there is a record name matching the FQDN self.errors.add(:name, I18n.t('cname_name', :name => self.name, :type => record.type, :scope => 'activerecord.errors.messages')) return end else # check if there is a CNAME record with the new record name unless self.domain.nil? if record = Record.where('id != ?', id).where('type = ?', 'CNAME').where('name' => self.name, 'domain_id' => self.domain_id).first self.errors.add(:name, I18n.t('cname_name_taken', :name => self.name, :scope => 'activerecord.errors.messages')) return elsif record = Record.where('id != ?', id).where('type = ?', 'CNAME').where('name' => self.name+"."+self.domain.name+".", 'domain_id' => self.domain_id).first # check if there is a FQDN matching the record name self.errors.add(:name, I18n.t('cname_name_taken', :name => self.name, :scope => 'activerecord.errors.messages')) elsif self.name.ends_with?'.' and record = Record.where('id != ?', id).where('type = ?', 'CNAME').where('name' => self.name.chomp("."+self.domain.name+"."), 'domain_id' => self.domain_id).first # check if there is a record name matching the FQDN self.errors.add(:name, I18n.t('cname_name_taken', :name => self.name, :scope => 'activerecord.errors.messages')) return end end end end def validate_name_format return if self.generate? # default implementation: validation of 'hostnames' return if self.name.blank? || self.name == '@' self.name.split('.').each_with_index do |part, index| if self.type == "SRV" or self.type == "TXT" unless (index == 0 && part == '*') || part =~ /^(?!\-)[a-zA-Z0-9\-_.]{,63}(?<!\-)$/ self.errors.add(:name, I18n.t('invalid', :scope => 'activerecord.errors.messages')) return end else unless (index == 0 && part == '*') || part =~ /^(?![0-9]+$)(?!\-)[a-zA-Z0-9\-.]{,63}(?<!\-)$/ self.errors.add(:name, I18n.t('invalid', :scope => 'activerecord.errors.messages')) return end end end end def validate_same_record id = self.id || 0 if self.type!="CNAME" && record = Record.where('id != ?', id).where('name' => self.name, 'type' => self.type, 'domain_id' => self.domain_id, 'content' => self.content).first self.errors.add(:base, I18n.t('record_same_name_and_type_and_content', :name => record.name, :type => record.type, :content => record.content, :scope => 'activerecord.errors.messages')) return end end def validate_same_name_and_type id = self.id || 0 if self.type!="CNAME" && record = Record.where('id != ?', id).where('name' => self.name, 'type' => self.type, 'domain_id' => self.domain_id, 'content' => self.content).first return elsif self.type!="CNAME" && record = self.class.where('id != ?', id).where('content != ?', self.content).where('name' => self.name, 'type' => self.type, 'domain_id' => self.domain_id).first self.warnings.add(:base, I18n.t('record_same_name_and_type', :name => record.name, :type => record.type, :content => record.content, :scope => 'activerecord.errors.messages')) end end def validate_recursive_subdomains return if self.domain.nil? || self.domain.name.blank? || self.name.blank? || self.name == '@' || self.name.index('.').nil? || self.name[-1] == '.' domain_name = self.domain.name conditions = nil self.name.split('.').reverse_each do |part| domain_name = "#{part}.#{domain_name}" condition = Domain.arel_table[:name].eq(domain_name) conditions = conditions ? conditions.or(condition) : condition end if domain = Domain.where(conditions).first self.errors.add(:name, I18n.t('recursive_subdomain', :domain => domain.name, :scope => 'activerecord.errors.messages')) end end def validate_txt if self.type == "TXT" strings = self.content.split("\"\"") strings.each do |s| self.errors.add(:content, I18n.t('string_txt_exceeds', :scope => 'activerecord.errors.messages')) if s.sub("\"","").size > 257 end end end def check_cname_content if self.type == "CNAME" and self.content.ascii_only? if self.content.ends_with? "." dns = Resolv::DNS.new url = self.content[0...-1] begin dns.getaddress(url) rescue self.warnings.add(:content, I18n.t('cname_content_fqdn_invalid', content: self.content, :scope => 'activerecord.errors.messages')) end else records = self.domain.records.map{|r| r.name} self.warnings.add(:content, I18n.t('cname_content_record_invalid', content: self.content, :scope => 'activerecord.errors.messages')) unless records.include? self.content end end return end def check_a_content if self.type == "A" p = Net::Ping::External.new self.content self.warnings.add(:content, I18n.t('a_content_invalid', content: self.content, :scope => 'activerecord.errors.messages')) unless p.ping? end return end # checks if content has only ascii characters def validate_content_characters if !self.content.ascii_only? # ascii_only self.errors.add(:content, I18n.t('ascii_only', :scope => 'activerecord.errors.messages')) end end # Checks if this record is a replica of another def same_as? other_record self.name == other_record.name && self.ttl == other_record.ttl && self.type == other_record.type && self.content == other_record.content end private def update_domain_timestamp self.transaction do Domain.where(name: self.domain.name).each(&:touch) end end def reset_prio self.prio = nil unless supports_prio? end # append the domain name to the +name+ field if missing # def append_domain_name! # self[:name] = self.domain.name if self[:name].blank? # unless self[:name].index( self.domain.name ) # puts "[append_domain_name] appending domain name (#{self[:name]} / #{self.domain.name})" # self[:name] << ".#{self.domain.name}" # end # end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/models/txt.rb
app/models/txt.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # = Text Record (TXT) # # Provides the ability to associate some text with a host or other name. The TXT # record is used to define the Sender Policy Framework (SPF) information record # which may be used to validate legitimate email sources from a domain. The SPF # record while being increasing deployed is not (July 2004) a formal IETF RFC # standard. # # Obtained from http://www.zytrax.com/books/dns/ch8/txt.html class TXT < Record def resolv_resource_class Resolv::DNS::Resource::IN::TXT end def match_resolv_resource(resource) resource.strings.join(' ') == self.content.chomp('.') end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/models/aaaa.rb
app/models/aaaa.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # = IPv6 Address Record (AAAA) # # The current IETF recommendation is to use AAAA (Quad A) RR for forward mapping # and PTR RRs for reverse mapping when defining IPv6 networks. The IPv6 AAAA RR # is defined in RFC 3596. RFC 3363 changed the status of the A6 RR (defined in # RFC 2874 from a PROPOSED STANDARD to EXPERIMENTAL due primarily to performance # and operational concerns. # # Obtained from http://www.zytrax.com/books/dns/ch8/aaaa.html class AAAA < Record validates_with IpAddressValidator, :attributes => :content, :ipv6 => true def resolv_resource_class Resolv::DNS::Resource::IN::AAAA end def match_resolv_resource(resource) resource.address.to_s == self.content end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/models/spf.rb
app/models/spf.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # = Text Record (SPF) # # In computing, Sender Policy Framework (SPF) allows software to identify # messages that are or are not authorized to use the domain name in the SMTP # HELO and MAIL FROM (Return-Path) commands, based on information published in a # sender policy of the domain owner. Forged return paths are common in e-mail # spam and result in backscatter. SPF is defined in RFC 4408 # # Obtained from http://en.wikipedia.org/wiki/Sender_Policy_Framework class SPF < Record end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/models/kx.rb
app/models/kx.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # = Key eXchanger Record (KX) # # Used with some cryptographic systems (not including DNSSEC) to identify a key # management agent for the associated domain-name. Note that this has nothing to # do with DNS Security. It is Informational status, rather than being on the # IETF standards-track. It has always had limited deployment, but is still in # use. class KX < Record def resolv_resource_class Resolv::DNS::Resource::IN::KX end def match_resolv_resource(resource) resource.strings.join(' ') == self.content.chomp('.') end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/models/srv.rb
app/models/srv.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # = Service Record (SRV) # # An SRV record or Service record is a category of data in the Internet Domain # Name System specifying information on available services. It is defined in # RFC 2782. Newer internet protocols such as SIP and XMPP often require SRV # support from clients. # # Obtained from http://en.wikipedia.org/wiki/SRV_record # # See also http://www.zytrax.com/books/dns/ch8/srv.html class SRV < Record # validates_numericality_of :prio, :greater_than_or_equal_to => 0 validates_presence_of :prio, :weight, :port validates :prio, :weight, :port, numericality: { only_integer: true } # We support priorities, weight and port def supports_prio? true end def supports_weight? true end def supports_port? true end def resolv_resource_class Resolv::DNS::Resource::IN::SRV end def match_resolv_resource(resource) # TODO: break down SRV records into multiple attributes? "#{resource.priority} #{resource.weight} #{resources.port} #{resource.target}" == self.content.chomp('.') end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/models/dnskey.rb
app/models/dnskey.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # = DNSKEY Record (NSKEY) # # The DNSKEY RR is part of the DNSSEC (DNSSEC.bis) standard. DNSKEY RRs contain # the public key (of an asymmetric encryption algorithm) used in zone signing # operations. Public keys used for other functions are defined using a KEY RR. # DNSKEY RRs may be either a Zone Signing Key (ZSK) or a Key Signing Key (KSK). # The DNSKEY RR is created using the dnssec-keygen utility supplied with BIND. # # Obtained from http://www.zytrax.com/books/dns/ch8/dskey.html class DNSKEY < Record def resolv_resource_class Resolv::DNS::Resource::IN::DNSKEY end def match_resolv_resource(resource) resource.strings.join(' ') == self.content.chomp('.') end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/models/soa.rb
app/models/soa.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # = Start of Authority Record # Defined in RFC 1035. The SOA defines global parameters for the zone (domain). # There is only one SOA record allowed in a zone file. # # Obtained from http://www.zytrax.com/books/dns/ch8/soa.html class SOA < Record # the portions of the +content+ column that make up our SOA fields SOA_FIELDS = %w{primary_ns contact serial refresh retry expire minimum} ACCESSIBLE_SOA_FIELDS = SOA_FIELDS - ['serial'] validates_presence_of :primary_ns, :content, :serial, :refresh, :retry, :expire, :minimum validates_numericality_of :serial validates_bind_time_format :refresh, :retry, :expire, :minimum # validates_numericality_of :serial, :refresh, :retry, :expire, :allow_blank => true, :greater_than_or_equal_to => 0 # validates_numericality_of :minimum, :allow_blank => true, :greater_than_or_equal_to => 0, :less_than_or_equal_to => 21600 # 10800 validates_uniqueness_of :domain_id, :on => :update validates :contact, :presence => true, :hostname => true validates :name, :presence => true, :hostname => true # before_validation :update_serial before_validation :set_name before_validation :set_content after_initialize :update_convenience_accessors attr_accessible :domain_id, :type, :name, :ttl, :prio, :content, *ACCESSIBLE_SOA_FIELDS # this allows us to have these convenience attributes act like any other # column in terms of validations SOA_FIELDS.each do |soa_entry| attr_reader soa_entry attr_reader soa_entry + '_was' define_method "#{soa_entry}_before_type_cast" do instance_variable_get("@#{soa_entry}") end define_method "#{soa_entry}=" do |value| instance_variable_set("@#{soa_entry}", value) set_content instance_variable_get("@#{soa_entry}") end end def initialize(*args) super(*args) self.serial = 0 end # hook into #reload def reload_with_content reload_without_content update_convenience_accessors end alias_method_chain :reload, :content # def update_serial # update_serial! if self.new_record? || self.changed? # end # # updates the serial number to the next logical one. Format of the generated # serial is YYYYMMDDNN, where NN is the number of the change for the day def update_serial(save = false) not_modify_serial = true if !(defined? GloboDns::Config::ENABLE_VIEW).nil? && GloboDns::Config::ENABLE_VIEW not_modify_serial = false domain_default_queryresult = Domain::DEFAULT_VIEW.domains.where(name: self.domain.name) unless domain_default_queryresult.nil? || domain_default_queryresult.first.nil? domain_default = domain_default_queryresult.first is_self_not_default = domain_default.id != self.domain.id if is_self_not_default default_updated_at = domain_default.updated_at default_soa = domain_default.records.soa default_serial = default_soa.serial if default_serial >= self.serial self.serial = default_serial not_modify_serial = default_updated_at > self.updated_at end else # is self default Domain.where(name: self.domain.name).where.not(id: domain_default.id).each do |domain| self.serial = domain.records.soa.serial if domain.records.soa.serial > self.serial not_modify_serial ||= domain.updated_at > self.domain.updated_at end end end end unless not_modify_serial current_date_zero = Time.now.strftime('%Y%m%d').to_i * 100 if self.serial >= current_date_zero self.serial += 1 else self.serial = current_date_zero end end if save set_content self.transaction do self.update_column(:content, self.content) end end end def set_content self.content = SOA_FIELDS.map { |f| instance_variable_get("@#{f}").to_s }.join(' ') end def set_name self.name ||= '@' end def resolv_resource_class Resolv::DNS::Resource::IN::SOA end def to_partial_path "#{self.class.superclass.name.underscore.pluralize}/soa_record" end def match_resolv_resource(resource) resource.mname.to_s == self.primary_ns.chomp('.') && resource.rname.to_s == self.contact.chomp('.') && resource.serial == self.serial && resource.refresh == self.refresh && resource.retry == self.retry && resource.expire == self.expire && resource.minimum == self.minimum end private # update our convenience accessors when the object has changed def update_convenience_accessors return if self.content.blank? || ACCESSIBLE_SOA_FIELDS.select{ |field| send(field).blank? }.empty? soa_fields = self.content.split(/\s+/) raise Exception.new("Invalid SOA Record content attribute: #{self.content}") unless soa_fields.size == SOA_FIELDS.size soa_fields.each_with_index do |field_value, index| field_name = SOA_FIELDS[index] field_value = field_value.try(:to_i) if field_name == 'serial' instance_variable_set("@#{field_name}", field_value) instance_variable_set("@#{field_name}_was", field_value) end # update_serial if @serial.nil? || @serial.zero? end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/models/ns.rb
app/models/ns.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # = Name Server Record (NS) # # Defined in RFC 1035. NS RRs appear in two places. Within the zone file, in # which case they are authoritative records for the zone's name servers. At the # point of delegation for either a subdomain of the zone or in the zone's # parent. Thus the zone example.com's parent zone (.com) will contain # non-authoritative NS RRs for the zone example.com at its point of delegation # and subdomain.example.com will have non-authoritative NS RSS in the zone # example.com at its point of delegation. NS RRs at the point of delegation are # never authoritative only NS RRs for the zone are regarded as authoritative. # While this may look a fairly trivial point, is has important implications for # DNSSEC. # # NS RRs are required because DNS queries respond with an authority section # listing all the authoritative name servers, for sub-domains or queries to the # zones parent where they are required to allow referral to take place. # # Obtained from http://www.zytrax.com/books/dns/ch8/ns.html class NS < Record include RecordPatterns validates_with HostnameValidator, :attributes => :content def resolv_resource_class Resolv::DNS::Resource::IN::NS end def match_resolv_resource(resource) resource.name.to_s == self.content.chomp('.') || resource.name.to_s == (self.content + '.' + self.domain.name) end # def validate_name_format # unless self.name.blank? || self.name == '@' || reverse_ipv4_fragment?(self.name) || reverse_ipv6_fragment?(self.name) # self.errors.add(:name, I18n.t('invalid', :scope => 'activerecord.errors.messages')) # end # end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/models/record_template.rb
app/models/record_template.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class RecordTemplate < ActiveRecord::Base belongs_to :domain_template, :inverse_of => :record_templates self.inheritance_column = '__unknown__' # don't use "type" as inheritance column # General validations validates_presence_of :domain_template, :name validates_presence_of :type attr_protected :domain_template_id attr_accessible :name, :type, :content, :ttl, :prio, :weight, :port, :domain_template, :tag protected_attributes.delete('type') # 'type' is a special inheritance column use by Rails and not accessible by default; before_validation :build_content, :if => :soa? before_validation :set_soa_name, :if => :soa? before_validation :set_serial, :if => :soa? after_initialize :update_convenience_accessors validate :validate_record_template scope :without_soa, ->{where('type != ?', 'SOA')} # We need to cope with the SOA convenience SOA::SOA_FIELDS.each do |field| attr_accessor field attr_reader field.to_s + '_was' end def self.record_types Record.record_types end # hook into #reload def reload_with_content reload_without_content update_convenience_accessors end alias_method_chain :reload, :content # Convert this template record into a instance +type+ with the # attributes of the template copied over to the instance def build(domain_name = nil) klass = self.type.constantize attr_names = klass.accessible_attributes.to_a.any? ? klass.accessible_attributes : klass.column_names attr_names -= klass.protected_attributes.to_a attr_names -= ['content'] if soa? attrs = attr_names.inject(Hash.new) do |hash, attr_name| if self.respond_to?(attr_name.to_sym) value = self.send(attr_name.to_sym) value = value.gsub('%ZONE%', domain_name) if domain_name && value.is_a?(String) hash[attr_name] = value end hash end hash record = klass.new(attrs) record.serial = 0 if soa? # overwrite 'serial' attribute of SOA records record end def soa? self.type == 'SOA' end def update(params) if soa? params.each do |value| field_name = value[0] field_value = value[1] field_value = field_value.try(:to_i) unless field_name == 'primary_ns' || field_name == 'contact' instance_variable_set("@#{field_name}", field_value) end end self.update_attributes(params) end # Here we perform some magic to inherit the validations from the "destination" # model without any duplication of rules. This allows us to simply extend the # appropriate record and gain those validations in the templates def validate_record_template #:nodoc: unless self.type.blank? record = build record.errors.each do |attr, message| # skip associations we don't have, validations we don't care about next if attr == :domain || attr == :name self.errors.add(attr, message) end unless record.valid? end end def to_partial_path case type when 'SOA'; "#{self.class.name.underscore.pluralize}/soa_record_template" else; "#{self.class.name.underscore.pluralize}/record_template" end end private # update our convenience accessors when the object has changed def update_convenience_accessors return if !soa? || self.content.blank? soa_fields = self.content.split(/\s+/) raise Exception.new("Invalid SOA Record content attribute: #{self.content}") unless soa_fields.size == SOA::SOA_FIELDS.size soa_fields.each_with_index do |field_value, index| field_name = SOA::SOA_FIELDS[index] field_value = field_value.try(:to_i) unless field_name == 'primary_ns' || field_name == 'contact' instance_variable_set("@#{field_name}", field_value) instance_variable_set("@#{field_name}_was", field_value) end end def set_soa_name self.name ||= '@' end def set_serial self.serial ||= 0 end def build_content self.content = SOA::SOA_FIELDS.map { |f| instance_variable_get("@#{f}").to_s }.join(' ') end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/models/sig.rb
app/models/sig.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # = Signature Record (SIG) # # Signature record used in SIG(0) (RFC 2931) and TKEY (RFC 2930).[7] RFC 3755 # designated RRSIG as the replacement for SIG for use within DNSSEC.[7] class SIG < Record def resolv_resource_class Resolv::DNS::Resource::IN::SIG end def match_resolv_resource(resource) resource.strings.join(' ') == self.content.chomp('.') end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/models/view.rb
app/models/view.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class View < ActiveRecord::Base include SyslogHelper RFC1912_NAME = '__rfc1912' ANY_NAME = '__any' attr_accessible :name audited :protect => false has_many :domains validates_presence_of :name, :key validates_associated :domains validate :clients_or_destinations before_validation :generate_key, :on => :create attr_accessible :name, :clients, :destinations scope :default, -> { default_view = View.where(name: 'default').first if default_view.nil? default_view = View.new default_view.name = 'default' default_view.clients = 'any;' default_view.save end default_view } def updated_since?(timestamp) self.updated_at > timestamp end def after_audit syslog_audit(self.audits.last) end def zones_dir 'views/' + self.name + '-' + GloboDns::Config::ZONES_DIR end def zones_file 'views/' + self.name + '-' + GloboDns::Config::ZONES_FILE end def default_zones_file 'views/' + self.name + '-' + GloboDns::Config::ZONES_DIR + '-default.conf' end def slaves_dir 'views/' + self.name + '-' + GloboDns::Config::SLAVES_DIR end def slaves_file 'views/' + self.name + '-' + GloboDns::Config::SLAVES_FILE end def default_slaves_file 'views/' + self.name + '-' + GloboDns::Config::SLAVES_DIR + '-default.conf' end def forwards_dir 'views/' + self.name + '-' + GloboDns::Config::FORWARDS_DIR end def forwards_file 'views/' + self.name + '-' + GloboDns::Config::FORWARDS_FILE end def default_forwards_file 'views/' + self.name + '-' + GloboDns::Config::FORWARDS_DIR + '-default.conf' end def reverse_dir 'views/' + self.name + '-' + GloboDns::Config::REVERSE_DIR end def reverse_file 'views/' + self.name + '-' + GloboDns::Config::REVERSE_FILE end def default_reverse_file 'views/' + self.name + '-' + GloboDns::Config::REVERSE_DIR + '-default.conf' end def self.key_name(view_name) view_name + '-key' end def key_name self.class.key_name(self.name) end def default? self == View.default end def all_domains_names domains_names = [] self.domains.each do |domain| domains_names.push domain.name end domains_names end ### views masters zones methods def domains_master_names self.domains.pluck(:name) end def domains_master_default_only # zones that are only at default view Domain.where(id: View.default.domains.master.where.not(name: self.domains_master_names).pluck(:id)) end def domains_master ids = self.domains.master.pluck(:id) + View.default.domains.master.where.not(name: self.domains_master_names).pluck(:id) Domain.where(id: ids.uniq) end ### views reverse zones methods def domains_reverse_named domains_names = [] self.domains._reverse.each do |domain| domains_names.push domain.name end domains_names end def domains_reverse ids = self.domains._reverse.pluck(:id) + View.default.domains._reverse.where.not(name: self.domains_reverse_names).pluck(:id) Domain.where(id: ids.uniq) end ### views slaves zones methods def domains_slave_names domains_names = [] self.domains.slave.each do |domain| domains_names.push domain.name end domains_names end def domains_slave ids = self.domains.slave.pluck(:id) + View.default.domains.slave.where.not(name: self.domains_slave_names).pluck(:id) Domain.where(id: ids.uniq) end ### views forwards zones methods def domains_forward_names domains_names = [] self.domains.forward.each do |domain| domains_names.push domain.name end domains_names end def domains_forward ids = self.domains.forward.pluck(:id) + View.default.domains.forward.where.not(name: self.domains_forward_names).pluck(:id) Domain.where(id: ids.uniq) end ### views masters, reverses or slaves zones methods def domains_master_or_reverse_or_slave_names domains_names = [] self.domains.master_or_reverse_or_slave.each do |domain| domains_names.push domain.name end domains_names end def domains_master_or_reverse_or_slave ids = self.domains.master_or_reverse_or_slave.pluck(:id) + View.default.domains.master_or_reverse_or_slave.where.not(name: self.domains_master_or_reverse_or_slave_names).pluck(:id) Domain.where(id: ids.uniq) end def domains_master_or_reverse_or_slave_default_only # zones that are only at default view Domain.where(id: View.default.domains.master_or_reverse_or_slave.where.not(name: self.domains_master_or_reverse_or_slave_names).pluck(:id)) end def slaves_with_view_key slaves = "" GloboDns::Config::Bind::Slaves.each do |slave| slaves << "#{slave::IPADDR} key \"#{self.key_name}\";" end slaves end def to_bind9_conf(zones_dir, indent = '', slave=false) match_clients = self.clients.present? ? self.clients.split(/\s*;\s*/) : ["any"] #Array.new if self.key.present? # use some "magic" to figure out the local address used to connect # to the master server # local_ipaddr = %x(ip route get #{GloboDns::Config::BIND_MASTER_IPADDR}) local_ipaddr = IO::popen([GloboDns::Config::Binaries::IP, 'route', 'get', GloboDns::Config::Bind::Master::IPADDR]) { |io| io.read } local_ipaddr = local_ipaddr[/src (#{RecordPatterns::IPV4}|#{RecordPatterns::IPV6})/, 1] unless self.default? # then, exclude this address from the list of "match-client" # addresses to force the view match using the "key" property match_clients.delete("!#{local_ipaddr}") match_clients.unshift("!#{local_ipaddr}") # deny masters ip match_clients.delete("!#{GloboDns::Config::Bind::Master::IPADDR}") match_clients.unshift("!#{GloboDns::Config::Bind::Master::IPADDR}") end # additionally, exclude the slave's server address (to enable it to # transfer the zones from the view that doesn't match its IP address) # unless self.default? GloboDns::Config::Bind::Slaves.each do |slave| match_clients.delete("!#{slave::IPADDR}") match_clients.unshift("!#{slave::IPADDR}") end key_str = "key \"#{self.key_name}\"" match_clients.delete(key_str) match_clients.unshift(key_str) # end end str = "" if defined? GloboDns::Config::ENABLE_VIEW and GloboDns::Config::ENABLE_VIEW str << "#{indent}key \"#{self.key_name}\" {\n" str << "#{indent} algorithm hmac-md5;\n" str << "#{indent} secret \"#{self.key}\";\n" str << "#{indent}};\n" str << "\n" str << "#{indent}view \"#{self.name}\" {\n" str << "#{indent} match-clients { #{match_clients.uniq.join('; ')}; };\n" if match_clients.present? str << "#{indent} match-destinations { key \"#{self.key_name}\"; #{self.destinations} };\n" if self.destinations.present? str << "#{indent} also-notify { #{self.slaves_with_view_key} };\n" unless slave str << "#{indent} allow-query { any; };\n" str << "\n" str << "#{indent} include \"#{File.join(zones_dir, self.zones_file)}\";\n" str << "#{indent} include \"#{File.join(zones_dir, self.slaves_file)}\";\n" str << "#{indent} include \"#{File.join(zones_dir, self.forwards_file)}\";\n" str << "#{indent} include \"#{File.join(zones_dir, self.reverse_file)}\";\n" str << "\n" unless self == View.default str << "#{indent} include \"#{File.join(zones_dir, self.default_zones_file)}\";\n" unless slave str << "#{indent} include \"#{File.join(zones_dir, self.default_slaves_file)}\";\n" if slave str << "#{indent} include \"#{File.join(zones_dir, self.default_forwards_file)}\";\n" str << "#{indent} include \"#{File.join(zones_dir, self.default_reverse_file)}\";\n" unless slave str << "\n" end str << "#{indent}};\n\n" end str end def generate_key Tempfile.open('globodns-key') do |file| GloboDns::Util::exec('rndc-confgen', GloboDns::Config::Binaries::RNDC_CONFGEN, '-a', '-r', '/dev/urandom', '-c', file.path, '-k', self.key_name) self.key = file.read[/algorithm\s+hmac\-md5;\s*secret\s+"(.*?)";/s, 1]; end end def clients_or_destinations if self.clients.blank? and self.destinations.blank? errors.add(:base, "Please, fill clients and/or destinations") end end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/models/a.rb
app/models/a.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # = IPv4 Address Record (A) # # Defined in RFC 1035. Forward maps a host name to IPv4 address. The only # parameter is an IP address in dotted decimal format. The IP address in not # terminated with a '.' (dot). Valid host name format (a.k.a 'label' in DNS # jargon). If host name is BLANK (or space) then the last valid name (or label) # is substituted. # # Obtained from http://www.zytrax.com/books/dns/ch8/a.html class A < Record validates_with IpAddressValidator, :attributes => :content def resolv_resource_class Resolv::DNS::Resource::IN::A end def match_resolv_resource(resource) resource.address.to_s == self.content end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/models/ptr.rb
app/models/ptr.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # = Name Server Record (PTR) # # Pointer records are the opposite of A and AAAA RRs and are used in Reverse Map # zone files to map an IP address (IPv4 or IPv6) to a host name. # # Obtained from http://www.zytrax.com/books/dns/ch8/ptr.html class PTR < Record include RecordPatterns validates_with HostnameValidator, :attributes => :content def resolv_resource_class Resolv::DNS::Resource::IN::PTR end def match_resolv_resource(resource) resource.name.to_s == self.content.chomp('.') || resource.name.to_s == (self.content + '.' + self.domain.name) end def validate_name_format unless self.generate? || self.name.blank? || self.name == '@' || reverse_ipv4_fragment?(self.name) || reverse_ipv6_fragment?(self.name) self.errors.add(:name, I18n.t('invalid', :scope => 'activerecord.errors.messages')) end end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/models/audits.rb
app/models/audits.rb
class Audits < ActiveRecord::Base include SyslogHelper include BindTimeFormatHelper attr_accessible :time, :user_id, :from, :action, :entity, :association, :changes; # scopes default_scope { order("#{self.table_name}.name") } # scope :updated_since, -> (timestamp) {Domain.where("#{self.table_name}.updated_at > ? OR #{self.table_name}.id IN (?)", timestamp, Record.updated_since(timestamp).select(:domain_id).pluck(:domain_id).uniq) } scope :matching, ->(action) {Audited::Adapters::ActiveRecord::Audit.where("action = ?", action)} # scope :matching, -> (userQuery){ # if userQuery.index('*') # where("#{self.table_name}.name LIKE ?", userQuery.gsub(/\*/, '%')) # else # where("#{self.table_name}.name" => userQuery) # end # } end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/models/acl.rb
app/models/acl.rb
class Acl < ActiveRecord::Base end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/models/domain.rb
app/models/domain.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # = Domain # # A #Domain is a unique domain name entry, and contains various #Record entries to # represent its data. # # The domain is used for the following purposes: # * It is the $ORIGIN off all its records # * It specifies a default $TTL class Domain < ActiveRecord::Base include SyslogHelper include BindTimeFormatHelper include GloboDns::Config # define helper constants and methods to handle domain types AUTHORITY_TYPES = define_enum(:authority_type, [:MASTER, :SLAVE, :FORWARD, :STUB, :HINT], ['M', 'S', 'F', 'U', 'H']) ADDRESSING_TYPES = define_enum(:addressing_type, [:REVERSE, :NORMAL], ['R', 'N']) REVERSE_DOMAIN_SUFFIXES = ['.in-addr.arpa', '.ip6.arpa'] DEFAULT_VIEW = View.default # virtual attributes that ease new zone creation. If present, they'll be # used to create an SOA for the domain # SOA_FIELDS = [ :primary_ns, :contact, :refresh, :retry, :expire, :minimum, :ttl ] SOA::SOA_FIELDS.each do |field| delegate field.to_sym, (field.to_s + '=').to_sym, :to => :soa_record end serialize :export_to attr_accessor :importing attr_accessible :user_id, :name, :master, :last_check, :notified_serial, :account, :ttl, :notes, :authority_type, :addressing_type, :view_id, :view, \ :primary_ns, :contact, :refresh, :retry, :expire, :minimum, :export_to audited :protect => false has_associated_audits # associations belongs_to :view # A sibling domain from where we borrow identical records. belongs_to :sibling, class_name: 'Domain' has_many :records, :dependent => :destroy, :inverse_of => :domain has_one :soa_record, :class_name => 'SOA', :inverse_of => :domain has_many :aaaa_records, :class_name => 'AAAA', :inverse_of => :domain has_many :a_records, :class_name => 'A', :inverse_of => :domain has_many :cert_records, :class_name => 'CERT', :inverse_of => :domain has_many :cname_records, :class_name => 'CNAME', :inverse_of => :domain has_many :dlv_records, :class_name => 'DLV', :inverse_of => :domain has_many :dnskey_records, :class_name => 'DNSKEY', :inverse_of => :domain has_many :ds_records, :class_name => 'DS', :inverse_of => :domain has_many :ipseckey_records, :class_name => 'IPSECKEY', :inverse_of => :domain has_many :key_records, :class_name => 'KEY', :inverse_of => :domain has_many :kx_records, :class_name => 'KX', :inverse_of => :domain has_many :loc_records, :class_name => 'LOC', :inverse_of => :domain has_many :mx_records, :class_name => 'MX', :inverse_of => :domain has_many :nsec3param_records, :class_name => 'NSEC3PARAM', :inverse_of => :domain has_many :nsec3_records, :class_name => 'NSEC3', :inverse_of => :domain has_many :nsec_records, :class_name => 'NSEC', :inverse_of => :domain has_many :ns_records, :class_name => 'NS', :inverse_of => :domain has_many :ptr_records, :class_name => 'PTR', :inverse_of => :domain has_many :rrsig_records, :class_name => 'RRSIG', :inverse_of => :domain has_many :sig_records, :class_name => 'SIG', :inverse_of => :domain has_many :spf_records, :class_name => 'SPF', :inverse_of => :domain has_many :srv_records, :class_name => 'SRV', :inverse_of => :domain has_many :ta_records, :class_name => 'TA', :inverse_of => :domain has_many :tkey_records, :class_name => 'TKEY', :inverse_of => :domain has_many :tsig_records, :class_name => 'TSIG', :inverse_of => :domain has_many :txt_records, :class_name => 'TXT', :inverse_of => :domain # validations validates_presence_of :name validates_uniqueness_of :name, :scope => :view_id validates_inclusion_of :authority_type, :in => AUTHORITY_TYPES.keys, :message => "must be one of #{AUTHORITY_TYPES.keys.join(', ')}" validates_inclusion_of :addressing_type, :in => ADDRESSING_TYPES.keys, :message => "must be one of #{ADDRESSING_TYPES.keys.join(', ')}" validates_presence_of :ttl, :if => :master? validates_bind_time_format :ttl, :if => :master? validates_associated :soa_record, :if => :master? validates_presence_of :master, :if => :slave? validates_presence_of :forwarder, :if => :forward? validate :validate_recursive_subdomains, :unless => :importing? # validations that generate 'warnings' (i.e., doesn't prevent 'saving' the record) # validation_scope :warnings do |scope| # end # callbacks before_save :name_unique? before_save :remove_spaces_from_name after_save :save_soa_record # scopes default_scope { order("#{self.table_name}.name") } scope :default_view, -> { # default_zones = DEFAULT_VIEW.all_domains_names default_zones = DEFAULT_VIEW.domains.pluck(:name) where(name: default_zones) } scope :not_default_view, -> { default_zones = DEFAULT_VIEW.all_domains_names where.not(name: default_zones) } scope :not_in_view, -> (view){ view_zones = view.domains.pluck(:name) where.not(name: view_zones) } scope :forward_export_to_ns, -> (ns_id){ ids = forward.where.not(export_to: nil).select { |d| d.export_to.include? ns_id.to_s }.collect{ |d| d.id } ids += forward.where(export_to: nil).pluck(:id) where(id: ids) } scope :master, -> {where("#{self.table_name}.authority_type = ?", MASTER).where("#{self.table_name}.addressing_type = ?", NORMAL)} scope :slave, -> {where("#{self.table_name}.authority_type = ?", SLAVE)} scope :forward, -> {where("#{self.table_name}.authority_type = ?", FORWARD)} scope :master_or_reverse_or_slave, -> {where("#{self.table_name}.authority_type = ? or #{self.table_name}.authority_type = ?", MASTER, SLAVE)} scope :reverse, -> {where("#{self.table_name}.authority_type = ?", MASTER).where("#{self.table_name}.addressing_type = ?", REVERSE)} scope :nonreverse, -> {where("#{self.table_name}.addressing_type = ?", NORMAL)} scope :noview, -> {where("#{self.table_name}.view_id IS NULL")} scope :_reverse, -> {reverse} # 'reverse' is an Array method; having an alias is useful when using the scope on associations scope :updated_since, -> (timestamp) {Domain.where("#{self.table_name}.updated_at > ? OR #{self.table_name}.id IN (?)", timestamp, Record.updated_since(timestamp).select(:domain_id).pluck(:domain_id).uniq) } scope :matching, -> (query){ if query.index('*') where("#{self.table_name}.name LIKE ?", query.gsub(/\*/, '%')) else where("#{self.table_name}.name" => query) end } def name_unique? if domain = Domain.where("id != ?", self.id).where(:name => self.name).first self.errors.add(:name, I18n.t('taken', :scope => 'activerecord.errors.messages')) return end end def self.last_update select('updated_at').reorder('updated_at DESC').limit(1).first.updated_at end # instantiate soa_record association on domain creation (this is required as # we delegate several attributes to the 'soa_record' association and want to # be able to set these attributes on 'Domain.new') def soa_record super || (self.soa_record = SOA.new.tap{|soa| soa.domain = self}) end # deprecated in favor of the 'updated_since' scope def updated_since?(timestamp) self.updated_at > timestamp end # return the records, excluding the SOA record def records_without_soa records.includes(:domain).where('type != ?', 'SOA') end def name=(value) rv = write_attribute :name, value == '.' ? value : value.chomp('.') set_addressing_type rv end def set_ownership(sub_component, user) if GloboDns::Config::DOMAINS_OWNERSHIP DomainOwnership::API.instance.post_domain_ownership_info(self.name, sub_component, "domain", user) if DomainOwnership::API.instance.get_domain_ownership_info(self.name)[:sub_component].nil? end end def check_ownership(user) if GloboDns::Config::DOMAINS_OWNERSHIP permission = DomainOwnership::API.instance.has_permission?(self.name, user) self.errors.add(:base, "User doesn't have ownership of '#{self.name}'") unless permission end permission end def addressing_type read_attribute('addressing_type').presence || set_addressing_type end # aliases to mascarade the fact that we're reusing the "master" attribute # to hold the "forwarder" values of domains with "forward" type def forwarder self.master end def forwarder=(val) self.master = val end def importing? !!importing end def has_in_default_view? defined? GloboDns::Config::ENABLE_VIEW and GloboDns::Config::ENABLE_VIEW == true and !DEFAULT_VIEW.domains.where(name: self.name).empty? end def records_zone_default ids = [] if self.has_in_default_view? DEFAULT_VIEW.domains.where(name: self.name).first.records.each do |record| if self.records.where(name: record.name).where(type: record.type).empty? r = Record.new(name: record.name, type: record.type, content: record.content, domain: self) ids.push record.id if r.valid? end end end Record.where(id: ids) end # expand our validations to include SOA details def after_validation_on_create #:nodoc: soa = SOA.new( :domain => self ) SOA_FIELDS.each do |f| soa.send( "#{f}=", send( f ) ) end soa.serial = serial unless serial.nil? # Optional unless soa.valid? soa.errors.each_full do |e| errors.add_to_base e end end end # setup an SOA if we have the requirements def save_soa_record #:nodoc: return unless self.master? soa_record.save or raise "[ERROR] unable to save SOA record (#{soa_record.errors.full_messages})" end def after_audit syslog_audit(self.audits.last) end # ------------- 'BIND9 export' utility methods -------------- def query_key_name if defined? GloboDns::Config::ENABLE_VIEW and GloboDns::Config::ENABLE_VIEW (self.view || View.first).try(:key_name) end end def query_key (self.view || View.first).try(:key) end def subdir_path #caches and returns @subdir_path ||= generate_subdir_path end def get_export_to_ns_names servers = self.export_to return "all nameservers" if servers.nil? servers = servers.each.collect{|ns| get_nameservers[ns.to_i]}.join(', ') puts servers servers end def zonefile_dir dir = if self.slave? self.view ? self.view.slaves_dir : GloboDns::Config::SLAVES_DIR elsif self.forward? self.view ? self.view.forwards_dir : GloboDns::Config::FORWARDS_DIR elsif self.reverse? self.view ? self.view.reverse_dir : GloboDns::Config::REVERSE_DIR else self.view ? self.view.zones_dir : GloboDns::Config::ZONES_DIR end File::join dir, subdir_path end def zonefile_path if self.slave? File.join(zonefile_dir, 'dbs.' + self.name) else File.join(zonefile_dir, 'db.' + self.name) end end def to_bind9_conf(zones_dir, indent = '') masters_external_ip = false view = self.view || View.first str = "#{indent}zone \"#{self.name}\" {\n" str << "#{indent} type #{self.authority_type_str.downcase};\n" str << "#{indent} file \"#{File.join(zones_dir, zonefile_path)}\";\n" unless self.forward? if self.slave? && self.master str << "#{indent} masters { #{self.master.strip.chomp(';')}; };\n" end str << "#{indent} forwarders { #{self.forwarder.strip.chomp(';')}; };\n" if self.forward? && (self.master || self.slave?) str << "#{indent}};\n\n" str end def to_zonefile(output, update_serial=true) logger.warn "[WARN] called 'to_zonefile' on slave/forward domain (#{self.id})" and return if slave? || forward? output = File.open(output, 'w') if output.is_a?(String) || output.is_a?(Pathname) output.puts "$ORIGIN #{self.name.chomp('.')}." output.puts "$TTL #{self.ttl}" output.puts output_records(output, self.sibling.records, output_soa: true, update_serial: update_serial) if sibling output_records(output, self.records, output_soa: !sibling, update_serial: update_serial) # only show this soa if the soa for the sibling hasn't been shown yet. if self.has_in_default_view? and self.view != DEFAULT_VIEW # if the zone is common to a view and the default view, the zone conf will be written only once and merge the records from the default view zone output_records(output, self.records_zone_default, output_soa: !sibling, update_serial: update_serial) end ensure output.close if output.is_a?(File) end def remove_spaces_from_name self.name.delete!(' ') end def validate_recursive_subdomains return if self.name.blank? record_name = nil domain_name = self.name.clone while suffix = domain_name.slice!(/.*?\./).try(:chop) record_name = record_name ? "#{record_name}.#{suffix}" : suffix records = Record.joins(:domain). where("#{Record.table_name}.name = ? OR #{Record.table_name}.name LIKE ?", record_name, "%.#{record_name}"). where("#{Domain.table_name}.name = ?", domain_name).all if records.any? records_excerpt = self.class.truncate(records.collect {|r| "\"#{r.name} #{r.type} #{r.content}\" from \"#{r.domain.name}\"" }.join(', ')) self.errors.add(:base, I18n.t('records_unreachable_by_domain', :records => records_excerpt, :scope => 'activerecord.errors.messages')) return end end end # Find a domain that has the same name, to search for replicated records. # The parameter 'save' tells if the method shall persist its changes in the end. def set_sibling save=false siblings = Domain::where(name: self.name) siblings.reject! do |sib| sib.id == self.id end if self.persisted? sibling = siblings.first if sibling Domain.transaction do self.sibling = sibling merge_records(sibling) if save raise ActiveRecord::Rollback unless self.save end end end end private def set_addressing_type REVERSE_DOMAIN_SUFFIXES.each do |suffix| self.reverse! and return if name.ends_with?(suffix) end self.normal! end # Output to the given output stream # the records from the given colection. # Accepts, as options, output_soa: boolean def output_records output, records, options={output_soa: true, update_serial: true} format = records_format records records.order("FIELD(type, #{GloboDns::Config::RECORD_ORDER.map{|x| "'#{x}'"}.join(', ')}), name ASC").each do |record| record.domain = self unless record.is_a?(SOA) && !options[:output_soa] record.update_serial(true) if (record.is_a?(SOA) and options[:update_serial]) record.to_zonefile(output, format) end end end def records_format records sizes = records.select('MAX(LENGTH(name)) AS name, LENGTH(MAX(ttl)) AS ttl, MAX(LENGTH(type)) AS mtype, LENGTH(MAX(prio)) AS prio, LENGTH(MAX(tag)) AS tag, LENGTH(MAX(weight)) AS weight, LENGTH(MAX(port)) AS port').first "%-#{sizes.name.to_i + 16}s %-#{sizes.ttl}s %-#{sizes.mtype.to_i + 5}s %-#{sizes.prio}s %-#{sizes.tag}s %-#{sizes.weight}s %-#{sizes.port}s %s\n" end def self.truncate(str, limit = 80) str.size > limit ? str[0..limit] + '...' : str end def generate_subdir_path config_depth = GloboDns::Config::SUBDIR_DEPTH depth = config_depth.is_a?(Integer) ? config_depth : Integer(config_depth, 10) rescue 0 # uses the first alphanumeric characters to create subdirs, up to GloboDns::Config::SUBDIR_DEPTH levels. File::join self.name.split('').select{|char| char.match /[a-zA-Z0-9]/}.first(depth) end # If a record for this domain is identical # a record for the other domain, instead of creating # a new copy of it, just uses the sibling pointing def merge_records(other_domain) other_records = other_domain.records # identical_other_records = [] # if you want to cache the records that are identical on other_domain # partition returns 2 arrays: first passes the predicate. Second doesn't identical_records, new_records = self.records.partition do |record| identical = false # is there any other record ... other_records.each do |other_record| # that is the same as ours? if other_record.same_as? record # set the flag to true identical = true # and cache it to merge # identical_other_records << other_record # if you want to cache the records that are identical on other_domain end end identical end self.records = new_records end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/models/caa.rb
app/models/caa.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # = Certification Authority Authorization (CAA) # # A CNAME record maps an alias or nickname to the real or Canonical name which # may lie outside the current zone. Canonical means expected or real name. # # Obtained from https://tools.ietf.org/html/rfc6844 class CAA < Record validates_presence_of :tag validates_presence_of :prio def supports_tag? true end def supports_prio? true end def resolv_resource_class Resolv::DNS::Resource::IN::CAA end def match_resolv_resource(resource) end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/models/nsec3.rb
app/models/nsec3.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # = NSEC3 Record version 3 (NSEC3) # # An extension to DNSSEC that allows proof of nonexistence for a name without # permitting zonewalking class NSEC3 < Record def resolv_resource_class Resolv::DNS::Resource::IN::NSEC3 end def match_resolv_resource(resource) resource.strings.join(' ') == self.content.chomp('.') end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/models/tkey.rb
app/models/tkey.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # = TSIG key Record (TKEY) # # A method of providing keying material to be used with TSIG that is encrypted # under the public key in an accompanying KEY RR.[9] class TKEY < Record def resolv_resource_class Resolv::DNS::Resource::IN::TKEY end def match_resolv_resource(resource) resource.strings.join(' ') == self.content.chomp('.') end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/models/key.rb
app/models/key.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # = Key Record (KEY) # # Provides the ability to associate some text with a host or other name. The TXT # record is used to define the Sender Policy Framework (SPF) information record # which may be used to validate legitimate email sources from a domain. The SPF # record while being increasing deployed is not (July 2004) a formal IETF RFC # standard. # # Obtained from http://www.zytrax.com/books/dns/ch8/key.html class KEY < Record def resolv_resource_class Resolv::DNS::Resource::IN::KEY end def match_resolv_resource(resource) resource.strings.join(' ') == self.content.chomp('.') end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/models/domain_template.rb
app/models/domain_template.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class DomainTemplate < ActiveRecord::Base has_many :record_templates, :dependent => :destroy, :inverse_of => :domain_template has_one :soa_record_template, -> {where(type: 'SOA')}, :class_name => 'RecordTemplate', :inverse_of => :domain_template # has_one :soa_record_template, :class_name => 'RecordTemplate', :conditions => { 'type' => 'SOA' }, :inverse_of => :domain_template belongs_to :view validates_presence_of :name validates_uniqueness_of :name validates_presence_of :ttl validates_numericality_of :ttl validates_associated :soa_record_template attr_accessible :id, :name, :ttl, :view_id, :primary_ns, :contact, :refresh, :retry, :expire, :minimum after_create :create_soa_record_template SOA::SOA_FIELDS.each do |field| delegate field.to_sym, (field.to_s + '=').to_sym, :to => :soa_record_template end scope :with_soa, ->{joins(:record_templates).where('record_templates.type = ?', 'SOA')} default_scope {order('name')} def soa_record_template super || (self.soa_record_template = RecordTemplate.new('type' => 'SOA').tap{ |soa| if self.new_record? soa.domain_template = self else soa.domain_template_id = self.id end }) end # Build a new domain using +self+ as a template. +domain+ should be valid domain # name. # # This method will throw exceptions as it encounters errors, and will use a # transaction to complete/rollback the operation. def build(domain_name) domain = Domain.new(:name => domain_name, :ttl => self.ttl, :authority_type => Domain::MASTER) record_templates.dup.each do |template| record = template.build(domain_name) domain.records << record domain.soa_record = record if record.is_a?(SOA) end domain.view_id = self.view_id if self.view_id domain end def create_soa_record_template soa_record_template.save or raise "[ERROR] unable to save SOA record template(#{soa_record_template.errors.full_messages})" end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/models/ipseckey.rb
app/models/ipseckey.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # = IPSEC key Record (IPSECKEY) # # Key record that can be used with IPSEC (http://en.wikipedia.org/wiki/IPSEC") class IPSECKEY < Record def resolv_resource_class Resolv::DNS::Resource::IN::IPSECKEY end def match_resolv_resource(resource) resource.strings.join(' ') == self.content.chomp('.') end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false
globocom/GloboDNS
https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/app/models/user_mailer.rb
app/models/user_mailer.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class UserMailer < ActionMailer::Base def signup_notification(user) setup_email(user) @subject += I18n.t(:message_user_activate_account) @body[:url] = "http://YOURSITE/activate/#{user.activation_code}" end def activation(user) setup_email(user) @subject += I18n.t(:message_user_activated) @body[:url] = "http://YOURSITE/" end protected def setup_email(user) @recipients = "#{user.email}" @from = "ADMINEMAIL" @subject = "[YOURSITE] " @sent_on = Time.now @body[:user] = user end end
ruby
Apache-2.0
d745871945c76cd26a8c926873b59690ef1ea5a7
2026-01-04T17:43:23.539268Z
false