Class: PgReports::DashboardController

Inherits:
ActionController::Base
  • Object
show all
Defined in:
app/controllers/pg_reports/dashboard_controller.rb

Instance Method Summary collapse

Instance Method Details

#create_migrationObject



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
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 324

def create_migration
  # Only allow migration creation in development environment
  unless Rails.env.development?
    render json: {
      success: false,
      error: I18n.t("pg_reports.ui.errors.migration_dev_only")
    }, status: :forbidden
    return
  end

  file_name = params[:file_name]
  code = params[:code]

  if file_name.blank? || code.blank?
    render json: {success: false, error: I18n.t("pg_reports.ui.errors.filename_code_required")}, status: :unprocessable_entity
    return
  end

  # Sanitize file name
  safe_file_name = file_name.gsub(/[^a-z0-9_.]/, "")
  unless safe_file_name.match?(/\A\d{14}_\w+\.rb\z/)
    render json: {success: false, error: I18n.t("pg_reports.ui.errors.invalid_filename_format")}, status: :unprocessable_entity
    return
  end

  # Find migrations directory
  migrations_path = Rails.root.join("db", "migrate")
  unless migrations_path.exist?
    render json: {success: false, error: I18n.t("pg_reports.ui.errors.migrations_dir_not_found")}, status: :unprocessable_entity
    return
  end

  file_path = migrations_path.join(safe_file_name)
  File.write(file_path, code)

  render json: {success: true, file_path: file_path.to_s, message: I18n.t("pg_reports.ui.success.migration_created")}
rescue => e
  render json: {success: false, error: e.message}, status: :unprocessable_entity
end

#downloadObject



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
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 146

def download
  category = params[:category].to_sym
  report_key = params[:report].to_sym
  format_type = params[:format] || "txt"

  report = execute_report(category, report_key)
  filename = "#{report.title.parameterize}-#{Time.current.strftime("%Y%m%d-%H%M%S")}"

  case format_type
  when "csv"
    send_data report.to_csv,
      filename: "#{filename}.csv",
      type: "text/csv; charset=utf-8",
      disposition: "attachment"
  when "json"
    send_data report.to_a.to_json,
      filename: "#{filename}.json",
      type: "application/json; charset=utf-8",
      disposition: "attachment"
  else
    send_data report.to_text,
      filename: "#{filename}.txt",
      type: "text/plain; charset=utf-8",
      disposition: "attachment"
  end
rescue => e
  render json: {success: false, error: e.message}, status: :unprocessable_entity
end

#download_query_monitorObject



449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 449

def download_query_monitor
  monitor = PgReports::QueryMonitor.instance

  # Allow download even when monitoring is stopped, as long as there are queries
  queries = monitor.queries
  if queries.empty?
    render json: {success: false, error: "No queries to download"}, status: :unprocessable_entity
    return
  end

  format_type = params[:format] || "txt"
  filename = "query-monitor-#{Time.current.strftime("%Y%m%d-%H%M%S")}"

  case format_type
  when "csv"
    csv_data = generate_query_monitor_csv(queries)
    send_data csv_data,
      filename: "#{filename}.csv",
      type: "text/csv; charset=utf-8",
      disposition: "attachment"
  when "json"
    send_data queries.to_json,
      filename: "#{filename}.json",
      type: "application/json; charset=utf-8",
      disposition: "attachment"
  else
    text_data = generate_query_monitor_text(queries)
    send_data text_data,
      filename: "#{filename}.txt",
      type: "text/plain; charset=utf-8",
      disposition: "attachment"
  end
rescue => e
  render json: {success: false, error: e.message}, status: :unprocessable_entity
end

#enable_pg_stat_statementsObject



15
16
17
18
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 15

def enable_pg_stat_statements
  result = PgReports.enable_pg_stat_statements!
  render json: result
end

#execute_queryObject



246
247
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
276
277
278
279
280
281
282
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
321
322
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 246

def execute_query
  query_hash = params[:query_hash]
  query_params = params[:params] || {}

  if query_hash.blank?
    render json: {success: false, error: I18n.t("pg_reports.ui.errors.query_hash_required")}, status: :unprocessable_entity
    return
  end

  # Security: Check if raw query execution is allowed
  unless PgReports.config.allow_raw_query_execution
    render json: {
      success: false,
      error: I18n.t("pg_reports.ui.errors.query_execution_disabled")
    }, status: :forbidden
    return
  end

  # Security: Retrieve and validate query by hash
  begin
    query = retrieve_query_by_hash(query_hash)

    if query.nil?
      render json: {success: false, error: I18n.t("pg_reports.ui.errors.query_not_found_expired")}, status: :not_found
      return
    end
  rescue SecurityError => e
    render json: {success: false, error: "#{I18n.t("pg_reports.ui.errors.security_violation_prefix")} #{e.message}"}, status: :forbidden
    return
  end

  # Substitute parameters if provided
  final_query = substitute_params(query, query_params)

  # Check for remaining unsubstituted parameters
  if final_query.match?(/\$\d+/)
    render json: {
      success: false,
      error: I18n.t("pg_reports.ui.errors.missing_parameter_values")
    }, status: :unprocessable_entity
    return
  end

  # Execute with LIMIT to prevent huge result sets
  limited_query = add_limit_if_missing(final_query, 100)

  start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  result = ActiveRecord::Base.connection.execute(limited_query)
  end_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  execution_time = ((end_time - start_time) * 1000).round(2)

  rows = result.to_a
  columns = rows.first&.keys || []

  # Check if we need to get total count
  total_count = rows.size
  truncated = false

  if rows.size >= 100
    # Check if there are more rows
    count_result = ActiveRecord::Base.connection.execute("SELECT COUNT(*) FROM (#{final_query}) AS count_query")
    total_count = count_result.first["count"].to_i
    truncated = total_count > 100
  end

  render json: {
    success: true,
    columns: columns,
    rows: rows,
    count: rows.size,
    total_count: total_count,
    truncated: truncated,
    execution_time: execution_time
  }
rescue => e
  render json: {success: false, error: e.message}, status: :unprocessable_entity
end

#explain_analyzeObject



175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 175

def explain_analyze
  query_hash = params[:query_hash]
  query_params = params[:params] || {}

  if query_hash.blank?
    render json: {success: false, error: I18n.t("pg_reports.ui.errors.query_hash_required")}, status: :unprocessable_entity
    return
  end

  # Security: Check if raw query execution is allowed
  unless PgReports.config.allow_raw_query_execution
    render json: {
      success: false,
      error: I18n.t("pg_reports.ui.errors.query_execution_disabled")
    }, status: :forbidden
    return
  end

  # Security: Retrieve and validate query by hash
  begin
    query = retrieve_query_by_hash(query_hash)

    if query.nil?
      render json: {success: false, error: I18n.t("pg_reports.ui.errors.query_not_found_expired")}, status: :not_found
      return
    end
  rescue SecurityError => e
    render json: {success: false, error: "#{I18n.t("pg_reports.ui.errors.security_violation_prefix")} #{e.message}"}, status: :forbidden
    return
  end

  # Check for trigger variables (NEW, OLD) which are only available in trigger context
  if query.match?(/\b(NEW|OLD)\./i)
    render json: {
      success: false,
      error: I18n.t("pg_reports.ui.errors.trigger_variables_not_allowed")
    }, status: :unprocessable_entity
    return
  end

  # Substitute parameters if provided
  final_query = substitute_params(query, query_params)

  # Check for remaining unsubstituted parameters
  if final_query.match?(/\$\d+/)
    render json: {
      success: false,
      error: I18n.t("pg_reports.ui.errors.missing_parameter_values")
    }, status: :unprocessable_entity
    return
  end

  result = ActiveRecord::Base.connection.execute("EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT) #{final_query}")
  explain_output = result.map { |r| r["QUERY PLAN"] }.join("\n")

  # Analyze the EXPLAIN output
  analyzer = ExplainAnalyzer.new(explain_output)
  analysis = analyzer.to_h

  render json: {
    success: true,
    explain: explain_output,
    stats: analysis[:stats],
    annotated_lines: analysis[:annotated_lines],
    problems: analysis[:problems],
    summary: analysis[:summary]
  }
rescue => e
  render json: {success: false, error: e.message}, status: :unprocessable_entity
end

#indexObject



10
11
12
13
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 10

def index
  @pg_stat_status = PgReports.pg_stat_statements_status
  @current_database = PgReports.system.current_database
end

#live_metricsObject



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_reports/dashboard_controller.rb', line 27

def live_metrics
  threshold = params[:long_query_threshold]&.to_i || 60

  # Check if we have access to required statistics
  begin
    data = Modules::System.live_metrics(long_query_threshold: threshold)

    # Validate that we got actual data
    if data[:connections][:total].nil? && data[:transactions][:total].nil?
      render json: {
        success: false,
        error: I18n.t("pg_reports.ui.errors.fetch_metrics_check_perms"),
        available: false
      }, status: :service_unavailable
      return
    end

    render json: {
      success: true,
      metrics: data,
      timestamp: Time.current.to_i,
      available: true
    }
  rescue PG::InsufficientPrivilege
    render json: {
      success: false,
      error: I18n.t("pg_reports.ui.errors.insufficient_database_perms"),
      available: false
    }, status: :forbidden
  rescue => e
    render json: {
      success: false,
      error: e.message,
      available: false
    }, status: :unprocessable_entity
  end
end

#load_query_historyObject



432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 432

def load_query_history
  monitor = PgReports::QueryMonitor.instance

  limit = params[:limit]&.to_i || 50
  session_id = params[:session_id]

  queries = monitor.load_from_log(limit: limit, session_id: session_id)

  render json: {
    success: true,
    queries: queries,
    timestamp: Time.current.to_i
  }
rescue => e
  render json: {success: false, error: e.message}, status: :unprocessable_entity
end

#query_monitor_feedObject



409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 409

def query_monitor_feed
  monitor = PgReports::QueryMonitor.instance

  unless monitor.enabled
    Rails.logger.warn("PgReports: query_monitor_feed called but monitoring not active. Instance: #{monitor.object_id}, enabled: #{monitor.enabled}, session_id: #{monitor.session_id}")
    render json: {success: false, message: "Monitoring not active"}
    return
  end

  limit = params[:limit]&.to_i || 50
  session_id = params[:session_id]

  queries = monitor.queries(limit: limit, session_id: session_id)

  render json: {
    success: true,
    queries: queries,
    timestamp: Time.current.to_i
  }
rescue => e
  render json: {success: false, error: e.message}, status: :unprocessable_entity
end

#query_monitor_statusObject



395
396
397
398
399
400
401
402
403
404
405
406
407
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 395

def query_monitor_status
  monitor = PgReports::QueryMonitor.instance
  status = monitor.status

  render json: {
    success: true,
    enabled: status[:enabled],
    session_id: status[:session_id],
    query_count: status[:query_count]
  }
rescue => e
  render json: {success: false, error: e.message}, status: :unprocessable_entity
end

#reset_statisticsObject



20
21
22
23
24
25
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 20

def reset_statistics
  PgReports.reset_statistics!
  render json: {success: true, message: I18n.t("pg_reports.ui.success.statistics_reset")}
rescue => e
  render json: {success: false, error: e.message}, status: :unprocessable_entity
end

#runObject



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
116
117
118
119
120
121
122
123
124
125
126
127
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 89

def run
  category = params[:category].to_sym
  report_key = params[:report].to_sym

  # Extract filter parameters from request
  filter_params = extract_filter_params

  report = execute_report(category, report_key, **filter_params)
  thresholds = Dashboard::ReportsRegistry.thresholds(report_key)
  problem_fields = Dashboard::ReportsRegistry.problem_fields(report_key)
  problem_explanations = load_problem_explanations(category, report_key)

  # Add query hashes for security
  data_with_hashes = report.data.first(100).map do |row|
    row_hash = row.dup

    # If this row contains a query column, store it with a hash
    if row_hash.key?("query") && row_hash["query"].present?
      query_hash = store_query_with_hash(row_hash["query"])
      row_hash["query_hash"] = query_hash
    end

    row_hash
  end

  render json: {
    success: true,
    title: report.title,
    columns: report.columns,
    data: data_with_hashes,
    total: report.size,
    generated_at: report.generated_at.strftime("%Y-%m-%d %H:%M:%S"),
    thresholds: thresholds,
    problem_fields: problem_fields,
    problem_explanations: problem_explanations
  }
rescue => e
  render json: {success: false, error: e.message}, status: :unprocessable_entity
end

#send_to_telegramObject



129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 129

def send_to_telegram
  category = params[:category].to_sym
  report_key = params[:report].to_sym

  report = execute_report(category, report_key)

  if report.size > 50
    report.send_to_telegram_as_file
  else
    report.send_to_telegram
  end

  render json: {success: true, message: I18n.t("pg_reports.ui.success.telegram_sent")}
rescue => e
  render json: {success: false, error: e.message}, status: :unprocessable_entity
end

#showObject



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

def show
  @category = params[:category].to_sym
  @report_key = params[:report].to_sym
  @report_info = Dashboard::ReportsRegistry.find(@category, @report_key)

  if @report_info.nil?
    redirect_to root_path, alert: I18n.t("pg_reports.ui.errors.report_not_found")
    return
  end

  # Get documentation for the report
  @documentation = Dashboard::ReportsRegistry.documentation(@report_key)
  @thresholds = Dashboard::ReportsRegistry.thresholds(@report_key)
  @problem_fields = Dashboard::ReportsRegistry.problem_fields(@report_key)

  # Load filter parameters from YAML
  @report_filters = load_report_filters(@category, @report_key)

  @report = execute_report(@category, @report_key)
rescue => e
  @error = e.message
  @report = nil
end

#start_query_monitoringObject



364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 364

def start_query_monitoring
  monitor = PgReports::QueryMonitor.instance
  Rails.logger.info("PgReports: start_query_monitoring called. Instance: #{monitor.object_id}")

  result = monitor.start
  Rails.logger.info("PgReports: start result: #{result.inspect}")

  if result[:success]
    render json: result
  else
    render json: result, status: :unprocessable_entity
  end
rescue => e
  Rails.logger.error("PgReports: start_query_monitoring error: #{e.message}\n#{e.backtrace.first(5).join("\n")}")
  render json: {success: false, error: e.message}, status: :unprocessable_entity
end

#stop_query_monitoringObject



381
382
383
384
385
386
387
388
389
390
391
392
393
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 381

def stop_query_monitoring
  monitor = PgReports::QueryMonitor.instance

  result = monitor.stop

  if result[:success]
    render json: result
  else
    render json: result, status: :unprocessable_entity
  end
rescue => e
  render json: {success: false, error: e.message}, status: :unprocessable_entity
end