Class: PgHero::HomeController

Inherits:
ActionController::Base
  • Object
show all
Defined in:
app/controllers/pg_hero/home_controller.rb

Instance Method Summary collapse

Instance Method Details

#connection_statsObject



206
207
208
# File 'app/controllers/pg_hero/home_controller.rb', line 206

def connection_stats
  render json: [{name: "Connections", data: @database.connection_stats(system_params), library: chart_library_options}]
end

#connectionsObject



258
259
260
261
262
263
264
265
# File 'app/controllers/pg_hero/home_controller.rb', line 258

def connections
  @title = "Connections"
  @connection_sources = @database.connection_sources
  @total_connections = @connection_sources.sum { |cs| cs[:total_connections] }

  @connections_by_database = group_connections(@connection_sources, :database)
  @connections_by_user = group_connections(@connection_sources, :user)
end

#cpu_usageObject



202
203
204
# File 'app/controllers/pg_hero/home_controller.rb', line 202

def cpu_usage
  render json: [{name: "CPU", data: @database.cpu_usage(system_params).map { |k, v| [k, v.round] }, library: chart_library_options}]
end

#enable_query_statsObject



291
292
293
294
295
296
# File 'app/controllers/pg_hero/home_controller.rb', line 291

def enable_query_stats
  @database.enable_query_stats
  redirect_backward notice: "Query stats enabled"
rescue ActiveRecord::StatementInvalid
  redirect_backward alert: "The database user does not have permission to enable query stats"
end

#explainObject



227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
# File 'app/controllers/pg_hero/home_controller.rb', line 227

def explain
  @title = "Explain"
  @query = params[:query]
  # TODO use get + token instead of post so users can share links
  # need to prevent CSRF and DoS
  if request.post? && @query
    begin
      prefix =
        case params[:commit]
        when "Analyze"
          "ANALYZE "
        when "Visualize"
          "(ANALYZE, COSTS, VERBOSE, BUFFERS, FORMAT JSON) "
        else
          ""
        end
      @explanation = @database.explain("#{prefix}#{@query}")
      @suggested_index = @database.suggested_indexes(queries: [@query]).first if @database.suggested_indexes_enabled?
      @visualize = params[:commit] == "Visualize"
    rescue ActiveRecord::StatementInvalid => e
      @error = e.message
    end
  end
end

#free_space_statsObject



221
222
223
224
225
# File 'app/controllers/pg_hero/home_controller.rb', line 221

def free_space_stats
  render json: [
    {name: "Free Space", data: @database.free_space_stats(duration: 14.days, period: 1.hour).map { |k, v| [k, (v / 1.gigabyte).round] }, library: chart_library_options},
  ]
end

#indexObject



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'app/controllers/pg_hero/home_controller.rb', line 23

def index
  @title = "Overview"
  @extended = params[:extended]

  if @replica
    @replication_lag = @database.replication_lag
    @good_replication_lag = @replication_lag ? @replication_lag < 5 : true
  else
    @inactive_replication_slots = @database.replication_slots.select { |r| !r[:active] }
  end

  @autovacuum_queries, @long_running_queries = @database.long_running_queries.partition { |q| q[:query].starts_with?("autovacuum:") }

  @total_connections = @database.total_connections
  @good_total_connections = @total_connections < @database.total_connections_threshold

  @transaction_id_danger = @database.transaction_id_danger(threshold: 1500000000)

  @readable_sequences, @unreadable_sequences = @database.sequences.partition { |s| s[:readable] }

  @sequence_danger = @database.sequence_danger(threshold: (params[:sequence_threshold] || 0.9).to_f, sequences: @readable_sequences)

  @indexes = @database.indexes
  @invalid_indexes = @indexes.select { |i| !i[:valid] }
  @duplicate_indexes = @database.duplicate_indexes(indexes: @indexes)

  if @query_stats_enabled
    @query_stats = @database.query_stats(historical: true, start_at: 3.hours.ago)
    @slow_queries = @database.slow_queries(query_stats: @query_stats)
    set_suggested_indexes((params[:min_average_time] || 20).to_f, (params[:min_calls] || 50).to_i)
  else
    @query_stats_available = @database.query_stats_available?
    @query_stats_extension_enabled = @database.query_stats_extension_enabled? if @query_stats_available
    @suggested_indexes = []
  end

  if @extended
    @index_hit_rate = @database.index_hit_rate || 0
    @table_hit_rate = @database.table_hit_rate || 0
    @good_cache_rate = @table_hit_rate >= @database.cache_hit_rate_threshold / 100.0 && @index_hit_rate >= @database.cache_hit_rate_threshold / 100.0
    @unused_indexes = @database.unused_indexes(max_scans: 0)
  end

  @show_migrations = PgHero.show_migrations
end

#index_bloatObject



102
103
104
105
106
# File 'app/controllers/pg_hero/home_controller.rb', line 102

def index_bloat
  @title = "Index Bloat"
  @index_bloat = @database.index_bloat
  @show_sql = params[:sql]
end

#killObject



273
274
275
276
277
278
279
# File 'app/controllers/pg_hero/home_controller.rb', line 273

def kill
  if @database.kill(params[:pid])
    redirect_to root_path, notice: "Query killed"
  else
    redirect_backward notice: "Query no longer running"
  end
end

#kill_allObject



286
287
288
289
# File 'app/controllers/pg_hero/home_controller.rb', line 286

def kill_all
  @database.kill_all
  redirect_backward notice: "Connections killed"
end

#kill_long_running_queriesObject



281
282
283
284
# File 'app/controllers/pg_hero/home_controller.rb', line 281

def kill_long_running_queries
  @database.kill_long_running_queries
  redirect_backward notice: "Queries killed"
end

#live_queriesObject



108
109
110
111
112
# File 'app/controllers/pg_hero/home_controller.rb', line 108

def live_queries
  @title = "Live Queries"
  @running_queries = @database.running_queries(all: true)
  @vacuum_progress = @database.vacuum_progress.index_by { |q| q[:pid] }
end

#load_statsObject



214
215
216
217
218
219
# File 'app/controllers/pg_hero/home_controller.rb', line 214

def load_stats
  render json: [
    {name: "Read IOPS", data: @database.read_iops_stats(system_params).map { |k, v| [k, v.round] }, library: chart_library_options},
    {name: "Write IOPS", data: @database.write_iops_stats(system_params).map { |k, v| [k, v.round] }, library: chart_library_options}
  ]
end

#maintenanceObject



267
268
269
270
271
# File 'app/controllers/pg_hero/home_controller.rb', line 267

def maintenance
  @title = "Maintenance"
  @maintenance_info = @database.maintenance_info
  @time_zone = PgHero.time_zone
end

#queriesObject



114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'app/controllers/pg_hero/home_controller.rb', line 114

def queries
  @title = "Queries"
  @sort = %w(average_time calls).include?(params[:sort]) ? params[:sort] : nil
  @min_average_time = params[:min_average_time] ? params[:min_average_time].to_i : nil
  @min_calls = params[:min_calls] ? params[:min_calls].to_i : nil

  if @historical_query_stats_enabled
    begin
      @start_at = params[:start_at] ? Time.zone.parse(params[:start_at]) : 24.hours.ago
      @end_at = Time.zone.parse(params[:end_at]) if params[:end_at]
    rescue
      @error = true
    end
  end

  @query_stats =
    if @historical_query_stats_enabled && !request.xhr?
      []
    else
      @database.query_stats(
        historical: true,
        start_at: @start_at,
        end_at: @end_at,
        sort: @sort,
        min_average_time: @min_average_time,
        min_calls: @min_calls
      )
    end

  @indexes = @database.indexes
  set_suggested_indexes

  # fix back button issue with caching
  response.headers["Cache-Control"] = "must-revalidate, no-store, no-cache, private"
  if request.xhr?
    render layout: false, partial: "queries_table", locals: {queries: @query_stats, xhr: true}
  end
end

#relation_spaceObject



94
95
96
97
98
99
100
# File 'app/controllers/pg_hero/home_controller.rb', line 94

def relation_space
  @schema = params[:schema] || "public"
  @relation = params[:relation]
  @title = @relation
  relation_space_stats = @database.relation_space_stats(@relation, schema: @schema)
  @chart_data = [{name: "Value", data: relation_space_stats.map { |r| [r[:captured_at], (r[:size_bytes].to_f / 1.megabyte).round(1)] }, library: chart_library_options}]
end

#replication_lag_statsObject



210
211
212
# File 'app/controllers/pg_hero/home_controller.rb', line 210

def replication_lag_stats
  render json: [{name: "Lag", data: @database.replication_lag_stats(system_params), library: chart_library_options}]
end

#reset_query_statsObject



298
299
300
301
302
303
# File 'app/controllers/pg_hero/home_controller.rb', line 298

def reset_query_stats
  @database.reset_query_stats
  redirect_backward notice: "Query stats reset"
rescue ActiveRecord::StatementInvalid
  redirect_backward alert: "The database user does not have permission to reset query stats"
end

#show_queryObject



153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'app/controllers/pg_hero/home_controller.rb', line 153

def show_query
  @query_hash = params[:query_hash].to_i
  @user = params[:user].to_s
  @title = @query_hash

  stats = @database.query_stats(historical: true, query_hash: @query_hash, start_at: 24.hours.ago).find { |qs| qs[:user] == @user }
  if stats
    @query = stats[:query]
    @explainable_query = stats[:explainable_query]

    if @show_details
      query_hash_stats = @database.query_hash_stats(@query_hash, user: @user)

      @chart_data = [{name: "Value", data: query_hash_stats.map { |r| [r[:captured_at], (r[:total_minutes] * 60 * 1000).round] }, library: chart_library_options}]
      @chart2_data = [{name: "Value", data: query_hash_stats.map { |r| [r[:captured_at], r[:average_time].round(1)] }, library: chart_library_options}]
      @chart3_data = [{name: "Value", data: query_hash_stats.map { |r| [r[:captured_at], r[:calls]] }, library: chart_library_options}]

      @origins = Hash[query_hash_stats.group_by { |r| r[:origin].to_s }.map { |k, v| [k, v.size] }]
      @total_count = query_hash_stats.size
    end

    @tables = PgQuery.parse(@query).tables rescue []
    @tables.sort!

    if @tables.any?
      @row_counts = Hash[@database.table_stats(table: @tables).map { |i| [i[:table], i[:estimated_rows]] }]
      @indexes_by_table = @database.indexes.group_by { |i| i[:table] }
    end
  else
    render_text "Unknown query"
  end
end

#spaceObject



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'app/controllers/pg_hero/home_controller.rb', line 69

def space
  @title = "Space"
  @days = (params[:days] || 7).to_i
  @database_size = @database.database_size
  @relation_sizes = params[:tables] ? @database.table_sizes : @database.relation_sizes
  @space_stats_enabled = @database.space_stats_enabled? && !params[:tables]
  if @space_stats_enabled
    space_growth = @database.space_growth(days: @days, relation_sizes: @relation_sizes)
    @growth_bytes_by_relation = Hash[ space_growth.map { |r| [[r[:schema], r[:relation]], r[:growth_bytes]] } ]
    case params[:sort]
    when "growth"
      @relation_sizes.sort_by! { |r| s = @growth_bytes_by_relation[[r[:schema], r[:relation]]]; [s ? 0 : 1, -s.to_i, r[:schema], r[:relation]] }
    when "name"
      @relation_sizes.sort_by! { |r| r[:relation] || r[:table] }
    end
  end

  across = params[:across].to_s.split(",")
  @unused_indexes = @database.unused_indexes(max_scans: 0, across: across)
  @unused_index_names = Set.new(@unused_indexes.map { |r| r[:index] })
  @show_migrations = PgHero.show_migrations
  @system_stats_enabled = @database.system_stats_enabled?
  @index_bloat = [] # @database.index_bloat
end

#systemObject



186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
# File 'app/controllers/pg_hero/home_controller.rb', line 186

def system
  @title = "System"
  @periods = {
    "1 hour" => {duration: 1.hour, period: 60.seconds},
    "1 day" => {duration: 1.day, period: 10.minutes},
    "1 week" => {duration: 1.week, period: 30.minutes},
    "2 weeks" => {duration: 2.weeks, period: 1.hours}
  }
  @duration = (params[:duration] || 1.hour).to_i
  @period = (params[:period] || 60.seconds).to_i

  if @duration / @period > 1440
    render_text "Too many data points"
  end
end

#tuneObject



252
253
254
255
256
# File 'app/controllers/pg_hero/home_controller.rb', line 252

def tune
  @title = "Tune"
  @settings = @database.settings
  @autovacuum_settings = @database.autovacuum_settings if params[:autovacuum]
end