Class: Detector::Addons::Redis

Inherits:
Base
  • Object
show all
Defined in:
lib/detector/addons/redis.rb

Instance Attribute Summary

Attributes inherited from Base

#keys, #uri

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#asn, #connection?, #connection_usage_percentage, #databases?, detect, #geo, #geography, #host, #infrastructure, #initialize, #ip, #kind, #ping, #port, #region, register_addon, #sql?, #summary, #tables, #tables?, #tcp_test, #transport?, #udp_test, #valid?, #with_connection

Constructor Details

This class inherits a constructor from Detector::Base

Class Method Details

.capabilities_for(url) ⇒ Object



11
12
13
# File 'lib/detector/addons/redis.rb', line 11

def self.capabilities_for(url)
  { kv: true, sql: false, url: url, kind: :redis, databases: true, tables: false }
end

.handles_uri?(uri) ⇒ Boolean

Returns:

  • (Boolean)


7
8
9
# File 'lib/detector/addons/redis.rb', line 7

def self.handles_uri?(uri)
  uri.scheme.downcase == 'redis' || uri.scheme.downcase == 'rediss'
end

Instance Method Details

#cli_nameObject



87
88
89
# File 'lib/detector/addons/redis.rb', line 87

def cli_name
  "redis-cli"
end

#closeObject



230
231
232
233
234
235
# File 'lib/detector/addons/redis.rb', line 230

def close
  if @conn
    @conn.quit rescue nil
    @conn = nil
  end
end

#connectionObject



15
16
17
18
19
20
21
22
# File 'lib/detector/addons/redis.rb', line 15

def connection
  # Create a new connection each time without caching
  if uri.scheme == 'rediss'
    ::Redis.new(url: @url, port: uri.port, timeout: 5.0, ssl_params: { verify_mode: OpenSSL::SSL::VERIFY_NONE }) rescue nil
  else
    ::Redis.new(url: @url, timeout: 5.0) rescue nil
  end
end

#connection_countObject



61
62
63
64
# File 'lib/detector/addons/redis.rb', line 61

def connection_count
  return nil unless info
  info['connected_clients'].to_i rescue 0
end

#connection_infoObject



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/detector/addons/redis.rb', line 71

def connection_info
  return nil unless info
  begin
    # Redis doesn't have per-user connection limits, so user = global
    global_count = info['connected_clients'].to_i rescue 0
    global_limit = info['maxclients'].to_i rescue 0
    
    {
      connection_count: { user: global_count, global: global_count },
      connection_limits: { user: global_limit, global: global_limit }
    }
  rescue => e
    nil
  end
end

#connection_limitObject



66
67
68
69
# File 'lib/detector/addons/redis.rb', line 66

def connection_limit
  return nil unless info
  info['maxclients'].to_i rescue 0
end

#database_countObject



42
43
44
45
# File 'lib/detector/addons/redis.rb', line 42

def database_count
  return nil unless connection
  connection.info['keyspace'].keys.size
end

#databasesObject



47
48
49
50
51
52
53
54
# File 'lib/detector/addons/redis.rb', line 47

def databases
  return [] unless info && info['keyspace']
  
  info['keyspace'].map do |db_name, stats|
    keys, expires = stats.split(',').map { |s| s.split('=').last.to_i }
    { name: db_name, keys: keys, expires: expires, stats: stats }
  end.sort_by { |db| -db[:keys] }
end

#estimated_row_count(table:, database: nil) ⇒ Object



191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
# File 'lib/detector/addons/redis.rb', line 191

def estimated_row_count(table:, database: nil)
  return nil unless connection
  
  # In Redis, the database is a number (0-15 typically) and "table" concept is closest to key patterns
  # We'll interpret table parameter as a key pattern
  
  begin
    # Set the database if specified
    if database
      # Redis db numbers are integers
      db_num = database.to_s.gsub(/[^0-9]/, '').to_i
      connection.select(db_num) rescue nil
    end
    
    # Count keys matching the pattern (consider this a heuristic approximation)
    # Use SCAN for larger datasets, as it doesn't block the server
    count = 0
    cursor = "0"
    
    begin
      # Timeout after a reasonable time to prevent long-running operations
      Timeout.timeout(5) do
        loop do
          cursor, keys = connection.scan(cursor, match: table, count: 1000)
          count += keys.size
          break if cursor == "0"
        end
      end
    rescue Timeout::Error
      # If we time out, return the partial count with a note
      return count
    end
    
    count
  rescue => e
    nil
  end
end

#generic_redis_access_checkObject



133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/detector/addons/redis.rb', line 133

def generic_redis_access_check
  # Check for admin commands
  admin_access = false
  begin
    # Try an admin command (CONFIG GET)
    connection.call('CONFIG', 'GET', 'maxmemory')
    admin_access = true
  rescue => e
    admin_access = false
  end
  
  # Check for write ability
  write_access = false
  begin
    # Use a random key name to avoid conflicts
    test_key = "__test_key_#{rand(1000000)}"
    connection.call('SET', test_key, 'test_value')
    connection.call('DEL', test_key)
    write_access = true
  rescue => e
    write_access = false
  end
  
  if admin_access
    "Administrator (config access)"
  elsif write_access
    "Regular user (read/write)"
  else
    # Try a read command
    begin
      connection.call('PING')
      "Read-only user"
    rescue => e
      "Limited access"
    end
  end
end

#infoObject



24
25
26
27
# File 'lib/detector/addons/redis.rb', line 24

def info
  return nil unless connection
  @info ||= connection.info
end

#protocol_typeObject



91
92
93
# File 'lib/detector/addons/redis.rb', line 91

def protocol_type
  :tcp
end

#replication_available?Boolean

Returns:

  • (Boolean)


171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
# File 'lib/detector/addons/redis.rb', line 171

def replication_available?
  return nil unless connection && info
  
  begin
    # Check if this is a master in a replication setup
    if info['role'] == 'master'
      return true
    end
    
    # Check if server has replication enabled
    if info['connected_slaves'].to_i > 0 || info['slave_read_only'] == '0'
      return true
    end
    
    false
  rescue => e
    nil
  end
end

#table_countObject



56
57
58
59
# File 'lib/detector/addons/redis.rb', line 56

def table_count
  return nil unless connection
  connection.dbsize rescue 0
end

#usageObject



34
35
36
37
38
39
40
# File 'lib/detector/addons/redis.rb', line 34

def usage
  return nil unless info
  
  per = (info['used_memory'].to_f / info['maxmemory'].to_f) * 100
  percent = sprintf("%.2f%%", per)
  "#{info['used_memory_human']} of #{info['maxmemory_human']} used (#{percent})" rescue -1
end

#user_access_levelObject



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/detector/addons/redis.rb', line 95

def user_access_level
  return nil unless connection
  
  # Redis 6.0+ supports ACLs, older versions just have auth or no auth
  redis_version = info['redis_version'].to_s
  
  if Gem::Version.new(redis_version) >= Gem::Version.new('6.0.0')
    begin
      acl_info = connection.call('ACL', 'LIST')
      default_user = acl_info.grep(/default/).first
      
      if default_user.include?('on') && default_user.include?('nopass')
        return "Administrator (open access)"
      elsif default_user.include?('on') && default_user.include?('~*')
        return "Administrator (password protected)"
      elsif default_user.include?('allkeys')
        if default_user.include?('allcommands')
          return "Full access (all commands, all keys)"
        else
          return "Limited command access (all keys)"
        end
      else
        if default_user.include?('reset')
          "No access (default rights)"
        else
          "Custom ACL pattern"
        end
      end
    rescue => e
      # Try to determine rights by test commands for older Redis
      self.generic_redis_access_check
    end
  else
    # Older Redis version
    self.generic_redis_access_check
  end
end

#versionObject



29
30
31
32
# File 'lib/detector/addons/redis.rb', line 29

def version
  return nil unless info
  "Redis #{info['redis_version']} on #{info['os']} #{info['arch']}, compiled by #{info['gcc_version']}, #{info['arch_bits']}-bit"
end