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



213
214
215
# File 'app/controllers/pg_hero/home_controller.rb', line 213

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

#connectionsObject



283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
# File 'app/controllers/pg_hero/home_controller.rb', line 283

def connections
  @title = "Connections"
  connections = @database.connections

  @total_connections = connections.count
  @connection_sources = group_connections(connections, [:database, :user, :source, :ip])
  @connections_by_database = group_connections_by_key(connections, :database)
  @connections_by_user = group_connections_by_key(connections, :user)

  if params[:security] && @database.server_version_num >= 90500
    connections.each do |connection|
      connection[:ssl_status] =
        if connection[:ssl]
          # no way to tell if client used verify-full
          # so connection may not be actually secure
          "SSL"
        else
          # variety of reasons for no SSL
          if !connection[:database].present?
            "Internal Process"
          elsif !connection[:ip]
            if connection[:state]
              "Socket"
            else
              # tcp or socket, don't have permission to tell
              "No SSL"
            end
          else
            # tcp
            # could separate out localhost since this should be safe
            "No SSL"
          end
        end
    end

    @connections_by_ssl_status = group_connections_by_key(connections, :ssl_status)
  end
end

#cpu_usageObject



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

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

#enable_query_statsObject



347
348
349
350
351
352
# File 'app/controllers/pg_hero/home_controller.rb', line 347

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



248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
# File 'app/controllers/pg_hero/home_controller.rb', line 248

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

      if @error.include?("bind message supplies 0 parameters")
        @error = "Can't explain queries with bind parameters"
      end
    end
  end
end

#free_space_statsObject



242
243
244
245
246
# File 'app/controllers/pg_hero/home_controller.rb', line 242

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

#indexObject



14
15
16
17
18
19
20
21
22
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
# File 'app/controllers/pg_hero/home_controller.rb', line 14

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:") }

  connection_states = @database.connection_states
  @total_connections = connection_states.values.sum
  @idle_connections = connection_states["idle in transaction"].to_i

  @good_total_connections = @total_connections < @database.total_connections_threshold
  @good_idle_connections = @idle_connections < 100

  @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 = @database.invalid_indexes(indexes: @indexes)
  @invalid_constraints = @database.invalid_constraints
  @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



98
99
100
101
102
# File 'app/controllers/pg_hero/home_controller.rb', line 98

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

#killObject



329
330
331
332
333
334
335
# File 'app/controllers/pg_hero/home_controller.rb', line 329

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

#kill_allObject



342
343
344
345
# File 'app/controllers/pg_hero/home_controller.rb', line 342

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

#kill_long_running_queriesObject



337
338
339
340
# File 'app/controllers/pg_hero/home_controller.rb', line 337

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

#live_queriesObject



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

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

  if params[:state]
    @running_queries.select! { |q| q[:state] == params[:state] }
  end
end

#load_statsObject



221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# File 'app/controllers/pg_hero/home_controller.rb', line 221

def load_stats
  stats =
    case @database.system_stats_provider
    when :azure
      [
        {name: "IO Consumption", data: @database.azure_stats("io_consumption_percent", **system_params), library: chart_library_options}
      ]
    when :gcp
      [
        {name: "Read Ops", data: @database.read_iops_stats(**system_params).map { |k, v| [k, v ? v.round : v] }, library: chart_library_options},
        {name: "Write Ops", data: @database.write_iops_stats(**system_params).map { |k, v| [k, v ? v.round : v] }, library: chart_library_options}
      ]
    else
      [
        {name: "Read IOPS", data: @database.read_iops_stats(**system_params).map { |k, v| [k, v ? v.round : v] }, library: chart_library_options},
        {name: "Write IOPS", data: @database.write_iops_stats(**system_params).map { |k, v| [k, v ? v.round : v] }, library: chart_library_options}
      ]
    end
  render json: stats
end

#maintenanceObject



322
323
324
325
326
327
# File 'app/controllers/pg_hero/home_controller.rb', line 322

def maintenance
  @title = "Maintenance"
  @maintenance_info = @database.maintenance_info
  @time_zone = PgHero.time_zone
  @show_dead_rows = params[:dead_rows]
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



90
91
92
93
94
95
96
# File 'app/controllers/pg_hero/home_controller.rb', line 90

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].change(sec: 0), r[:size_bytes].to_i] }, library: chart_library_options}]
end

#replication_lag_statsObject



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

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

#reset_query_statsObject



354
355
356
357
358
359
# File 'app/controllers/pg_hero/home_controller.rb', line 354

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].change(sec: 0), (r[:total_minutes] * 60 * 1000).round] }, library: chart_library_options}]
      @chart2_data = [{name: "Value", data: query_hash_stats.map { |r| [r[:captured_at].change(sec: 0), r[:average_time].round(1)] }, library: chart_library_options}]
      @chart3_data = [{name: "Value", data: query_hash_stats.map { |r| [r[:captured_at].change(sec: 0), 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



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

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
201
202
203
204
205
206
207
# 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}
  }
  if @database.system_stats_provider == :azure
    # doesn't support 10, just 5 and 15
    @periods["1 day"][:period] = 15.minutes
  end

  @duration = (params[:duration] || 1.hour).to_i
  @period = (params[:period] || 60.seconds).to_i

  if @duration / @period > 1440
    render_text "Too many data points"
  elsif @period % 60 != 0
    render_text "Period must be a multiple of 60"
  end
end

#tuneObject



277
278
279
280
281
# File 'app/controllers/pg_hero/home_controller.rb', line 277

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