space_usage_dimension.rb 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. # frozen_string_literal: true
  2. class Admin::Metrics::Dimension::SpaceUsageDimension < Admin::Metrics::Dimension::BaseDimension
  3. include Redisable
  4. include ActionView::Helpers::NumberHelper
  5. def key
  6. 'space_usage'
  7. end
  8. protected
  9. def perform_query
  10. [postgresql_size, redis_size, media_size, search_size].compact
  11. end
  12. def postgresql_size
  13. value = ActiveRecord::Base.connection.execute('SELECT pg_database_size(current_database())').first['pg_database_size']
  14. {
  15. key: 'postgresql',
  16. human_key: 'PostgreSQL',
  17. value: value.to_s,
  18. unit: 'bytes',
  19. human_value: number_to_human_size(value),
  20. }
  21. end
  22. def redis_size
  23. value = redis_info['used_memory']
  24. {
  25. key: 'redis',
  26. human_key: 'Redis',
  27. value: value.to_s,
  28. unit: 'bytes',
  29. human_value: number_to_human_size(value),
  30. }
  31. end
  32. def media_size
  33. value = [
  34. MediaAttachment.sum(Arel.sql('COALESCE(file_file_size, 0) + COALESCE(thumbnail_file_size, 0)')),
  35. CustomEmoji.sum(:image_file_size),
  36. PreviewCard.sum(:image_file_size),
  37. Account.sum(Arel.sql('COALESCE(avatar_file_size, 0) + COALESCE(header_file_size, 0)')),
  38. Backup.sum(:dump_file_size),
  39. Import.sum(:data_file_size),
  40. SiteUpload.sum(:file_file_size),
  41. ].sum
  42. {
  43. key: 'media',
  44. human_key: I18n.t('admin.dashboard.media_storage'),
  45. value: value.to_s,
  46. unit: 'bytes',
  47. human_value: number_to_human_size(value),
  48. }
  49. end
  50. def redis_info
  51. @redis_info ||= if redis.is_a?(Redis::Namespace)
  52. redis.redis.info
  53. else
  54. redis.info
  55. end
  56. end
  57. def search_size
  58. return unless Chewy.enabled?
  59. client_info = Chewy.client.info
  60. value = Chewy.client.indices.stats['indices'].values.sum { |index_data| index_data['primaries']['store']['size_in_bytes'] }
  61. {
  62. key: 'search',
  63. human_key: client_info.dig('version', 'distribution') == 'opensearch' ? 'OpenSearch' : 'Elasticsearch',
  64. value: value.to_s,
  65. unit: 'bytes',
  66. human_value: number_to_human_size(value),
  67. }
  68. rescue Faraday::ConnectionFailed, Elasticsearch::Transport::Transport::Error
  69. nil
  70. end
  71. end