Class: PgHero::HomeController
- Inherits:
-
ActionController::Base
- Object
- ActionController::Base
- PgHero::HomeController
- Defined in:
- app/controllers/pg_hero/home_controller.rb
Instance Method Summary collapse
- #connection_stats ⇒ Object
- #connections ⇒ Object
- #cpu_usage ⇒ Object
- #enable_query_stats ⇒ Object
- #explain ⇒ Object
- #free_space_stats ⇒ Object
- #index ⇒ Object
- #index_bloat ⇒ Object
- #kill ⇒ Object
- #kill_all ⇒ Object
- #kill_long_running_queries ⇒ Object
- #live_queries ⇒ Object
- #load_stats ⇒ Object
- #maintenance ⇒ Object
- #queries ⇒ Object
- #relation_space ⇒ Object
- #replication_lag_stats ⇒ Object
- #reset_query_stats ⇒ Object
- #show_query ⇒ Object
- #space ⇒ Object
- #system ⇒ Object
- #tune ⇒ Object
Instance Method Details
#connection_stats ⇒ Object
273 274 275 |
# File 'app/controllers/pg_hero/home_controller.rb', line 273 def connection_stats render json: [{name: "Connections", data: @database.connection_stats(**system_params), library: }] end |
#connections ⇒ Object
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 |
# File 'app/controllers/pg_hero/home_controller.rb', line 372 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] 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_usage ⇒ Object
269 270 271 |
# File 'app/controllers/pg_hero/home_controller.rb', line 269 def cpu_usage render json: [{name: "CPU", data: @database.cpu_usage(**system_params).map { |k, v| [k, v ? v.round : v] }, library: }] end |
#enable_query_stats ⇒ Object
436 437 438 439 440 441 |
# File 'app/controllers/pg_hero/home_controller.rb', line 436 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 |
#explain ⇒ Object
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 |
# File 'app/controllers/pg_hero/home_controller.rb', line 304 def explain unless @explain_enabled render_text "Explain not enabled", status: :bad_request return end @title = "Explain" @query = params[:query] @explain_analyze_enabled = PgHero.explain_mode == "analyze" # TODO use get + token instead of post so users can share links # need to prevent CSRF and DoS if request.post? && @query.present? begin generic_plan = @database.server_version_num >= 160000 && @query.include?("$1") = case params[:commit] when "Analyze" {analyze: true} when "Visualize" if @explain_analyze_enabled && !generic_plan {analyze: true, costs: true, verbose: true, buffers: true, format: "json"} else {costs: true, verbose: true, format: "json"} end else {} end [:generic_plan] = true if generic_plan if [:analyze] && !@explain_analyze_enabled render_text "Explain analyze not enabled", status: :bad_request return end @explanation = @database.explain(@query, **) @suggested_index = @database.suggested_indexes(queries: [@query]).first if @database.suggested_indexes_enabled? @visualize = params[:commit] == "Visualize" rescue ActiveRecord::StatementInvalid => e = e. @error = if == "Unsafe statement" "Unsafe statement" elsif .start_with?("PG::UndefinedParameter") "Can't explain queries with bind parameters" elsif .include?("EXPLAIN options ANALYZE and GENERIC_PLAN cannot be used together") "Can't analyze queries with bind parameters" elsif .start_with?("PG::SyntaxError") "Syntax error with query" elsif .start_with?("PG::QueryCanceled") "Query timed out" else # default to a generic message # since data can be extracted through the Postgres error message "Error explaining query" end end end end |
#free_space_stats ⇒ Object
298 299 300 301 302 |
# File 'app/controllers/pg_hero/home_controller.rb', line 298 def free_space_stats render json: [ {name: "Free Space", data: @database.free_space_stats(duration: 14.days, period: 1.hour), library: } ] end |
#index ⇒ Object
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 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
# File 'app/controllers/pg_hero/home_controller.rb', line 28 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 @walsender_queries, long_running_queries = @database.long_running_queries.partition { |q| q[:backend_type] == "walsender" } @autovacuum_queries, @long_running_queries = 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) sequences, @sequences_timeout = rescue_timeout([]) { @database.sequences } @readable_sequences, @unreadable_sequences = sequences.partition { |s| s[:readable] } @sequence_danger = @database.sequence_danger(threshold: (params[:sequence_threshold] || 0.9).to_f, sequences: @readable_sequences) @indexes, @indexes_timeout = if @sequences_timeout # skip indexes for faster loading [[], true] else rescue_timeout([]) { @database.indexes } end @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, min_size: @database.unused_index_bytes) end @show_migrations = PgHero.show_migrations end |
#index_bloat ⇒ Object
125 126 127 128 129 |
# File 'app/controllers/pg_hero/home_controller.rb', line 125 def index_bloat @title = "Index Bloat" @index_bloat = @database.index_bloat @show_sql = params[:sql] end |
#kill ⇒ Object
418 419 420 421 422 423 424 |
# File 'app/controllers/pg_hero/home_controller.rb', line 418 def kill if @database.kill(params[:pid]) redirect_backward notice: "Query killed" else redirect_backward notice: "Query no longer running" end end |
#kill_all ⇒ Object
431 432 433 434 |
# File 'app/controllers/pg_hero/home_controller.rb', line 431 def kill_all @database.kill_all redirect_backward notice: "Connections killed" end |
#kill_long_running_queries ⇒ Object
426 427 428 429 |
# File 'app/controllers/pg_hero/home_controller.rb', line 426 def kill_long_running_queries @database.kill_long_running_queries redirect_backward notice: "Queries killed" end |
#live_queries ⇒ Object
131 132 133 134 135 136 137 138 139 |
# File 'app/controllers/pg_hero/home_controller.rb', line 131 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_stats ⇒ Object
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 |
# File 'app/controllers/pg_hero/home_controller.rb', line 281 def load_stats stats = case @database.system_stats_provider when :gcp [ {name: "Read Ops", data: @database.read_iops_stats(**system_params).map { |k, v| [k, v ? v.round : v] }, library: }, {name: "Write Ops", data: @database.write_iops_stats(**system_params).map { |k, v| [k, v ? v.round : v] }, library: } ] else [ {name: "Read IOPS", data: @database.read_iops_stats(**system_params).map { |k, v| [k, v ? v.round : v] }, library: }, {name: "Write IOPS", data: @database.write_iops_stats(**system_params).map { |k, v| [k, v ? v.round : v] }, library: } ] end render json: stats end |
#maintenance ⇒ Object
411 412 413 414 415 416 |
# File 'app/controllers/pg_hero/home_controller.rb', line 411 def maintenance @title = "Maintenance" @maintenance_info = @database.maintenance_info @time_zone = PgHero.time_zone @show_dead_rows = params[:dead_rows] end |
#queries ⇒ Object
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 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 |
# File 'app/controllers/pg_hero/home_controller.rb', line 141 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 @user = params[:user] ? params[:user].to_s : nil @link_user = !@user 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 @link_options = {sort: @sort} if @historical_query_stats_enabled # use same format as JavaScript @link_options[:start_at] = @start_at.utc.iso8601 if params[:start_at] @link_options[:end_at] = @end_at.utc.iso8601 if params[:end_at] 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 if @user # filter in Ruby for accurate percent of total time @query_stats = @query_stats.select { |v| v[:user] == @user } end if !@historical_query_stats_enabled || request.xhr? set_suggested_indexes else @debug = params[:debug].present? end # 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_space ⇒ Object
117 118 119 120 121 122 123 |
# File 'app/controllers/pg_hero/home_controller.rb', line 117 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: "Size", data: relation_space_stats.map { |r| [r[:captured_at].change(sec: 0), r[:size_bytes].to_i] }, library: }] end |
#replication_lag_stats ⇒ Object
277 278 279 |
# File 'app/controllers/pg_hero/home_controller.rb', line 277 def replication_lag_stats render json: [{name: "Lag", data: @database.replication_lag_stats(**system_params), library: }] end |
#reset_query_stats ⇒ Object
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 |
# File 'app/controllers/pg_hero/home_controller.rb', line 443 def reset_query_stats # also disable when upgrading if @database.historical_query_stats_enabled? || @database.query_stats_table_exists? render_text "Cannot reset when historical query stats are enabled", status: :bad_request return end success = @database.reset_query_stats if success redirect_backward notice: "Query stats reset" else redirect_backward alert: "The database user does not have permission to reset query stats" end end |
#show_query ⇒ Object
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 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 |
# File 'app/controllers/pg_hero/home_controller.rb', line 197 def show_query query_hash = params[:query_hash].to_s # v needed for ambiguous values hash_format = if params[:v] != "2" && query_hash.size <= 20 && /\A-?\d{1,19}\z/.match?(query_hash) 1 elsif query_hash.size == 16 && /\A[0-9a-f]{16}\z/.match?(query_hash) 2 end @query_hash = case hash_format when 2 # this format uses big endian to match Postgres to_hex [query_hash].pack("H16").unpack1("q>") when 1 query_hash.to_i end if @query_hash stats = @database.query_stats(historical: true, user: @user, query_hash: @query_hash, start_at: 24.hours.ago).first end if stats @query = stats[:query] @title = @query.truncate(70) @explainable_query = stats[:query] if @database.send(:explainable?, stats[:query]) if @show_details query_hash_stats = @database.query_hash_stats(@query_hash, user: @user) @chart_data = [{name: "Total Time", data: query_hash_stats.map { |r| [r[:captured_at].change(sec: 0), r[:total_time].round] }, library: }] @chart2_data = [{name: "Average Time", data: query_hash_stats.map { |r| [r[:captured_at].change(sec: 0), r[:average_time].round(1)] }, library: }] @chart3_data = [{name: "Calls", data: query_hash_stats.map { |r| [r[:captured_at].change(sec: 0), r[:calls]] }, library: }] @origins = query_hash_stats.group_by { |r| r[:origin].to_s }.to_h { |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 = @database.table_stats(table: @tables).to_h { |i| [i[:table], i[:estimated_rows]] } indexes, @indexes_timeout = rescue_timeout([]) { @database.indexes } @indexes_by_table = indexes.group_by { |i| i[:table] } end else render_text "Unknown query", status: :not_found end end |
#space ⇒ Object
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 |
# File 'app/controllers/pg_hero/home_controller.rb', line 87 def space @title = "Space" @days = (params[:days] || 7).to_i @database_size = @database.database_size @only_tables = params[:tables].present? @relation_sizes, @sizes_timeout = rescue_timeout([]) { @only_tables ? @database.table_sizes : @database.relation_sizes } @space_stats_enabled = @database.space_stats_enabled? && !@only_tables if @space_stats_enabled space_growth = @database.space_growth(days: @days, relation_sizes: @relation_sizes) @growth_bytes_by_relation = space_growth.to_h { |r| [[r[:schema], r[:relation]], r[:growth_bytes]] } if params[:sort] == "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]] } end end if params[:sort] == "name" @relation_sizes.sort_by! { |r| r[:relation] || r[:table] } end @header_options = @only_tables ? {tables: "t"} : {} 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] }) @unused_indexes = @unused_indexes.select { |r| r[:size_bytes] >= @database.unused_index_bytes } @show_migrations = PgHero.show_migrations @system_stats_enabled = @database.system_stats_enabled? @index_bloat = [] # @database.index_bloat end |
#system ⇒ Object
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 |
# File 'app/controllers/pg_hero/home_controller.rb', line 250 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", status: :bad_request elsif @period % 60 != 0 render_text "Period must be a multiple of 60", status: :bad_request end end |
#tune ⇒ Object
366 367 368 369 370 |
# File 'app/controllers/pg_hero/home_controller.rb', line 366 def tune @title = "Tune" @settings = @database.settings @autovacuum_settings = @database.autovacuum_settings if params[:autovacuum] end |