-
Notifications
You must be signed in to change notification settings - Fork 30
/
app.rb
74 lines (63 loc) · 2.13 KB
/
app.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
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
64
65
66
67
68
69
70
71
72
73
74
require 'sinatra'
require 'sequel'
require 'json'
require 'haml'
DB = Sequel.connect ENV['DATABASE_URL']
class Datascope < Sinatra::Application
if (ENV['BASIC_AUTH_USER'] && ENV['BASIC_AUTH_PASSWORD'])
use Rack::Auth::Basic, "Datascope" do |username, password|
username == ENV['BASIC_AUTH_USER'] && password == ENV['BASIC_AUTH_PASSWORD']
end
end
get '/' do
haml :index
end
get '/metric' do
selector = params[:selector]
start = DateTime.parse params[:start]
stop = DateTime.parse params[:stop]
step = params[:step].to_i
results = DB[:stats].select(:data).filter(created_at: (start..stop)).all
parsed = results.map{|row| JSON.parse(row[:data])}
if selector == 'query_1'
values = values_by_regex parsed, /with packed/i, :ms
elsif selector == 'select'
values = values_by_regex parsed, /select/i
elsif selector == 'select_ms'
values = values_by_regex parsed, /select/i, :ms
elsif selector == 'update'
values = values_by_regex parsed, /update/i
elsif selector == 'update_ms'
values = values_by_regex parsed, /update/i, :ms
elsif selector == 'insert'
values = values_by_regex parsed, /insert/i
elsif selector == 'insert_ms'
values = values_by_regex parsed, /insert/i, :ms
elsif selector == 'delete'
values = values_by_regex parsed, /delete/i
else
values = parsed.map{|d| d[selector] }
end
JSON.dump values
end
get '/queries' do
data = JSON.parse DB[:stats]
.select(:data)
.order_by(:id.desc)
.first[:data]
JSON.dump data['stat_statements'].map{|s| s['query'] = s['query'][0..50]; s}.sort{|s| s['total_time']}.reverse
end
def values_by_regex(parsed, regex, ms=false)
vals = parsed.map { |row|
row['stat_statements']
.select {|h| h['query'] =~ regex }
.sort_by {|h| h['total_time']}
.inject([0,0]) { |m,h| [m.first + h['calls'].to_i, m.last + h['total_time'].to_f ] }
}
if ms
vals.map {|pair| pair.first.zero? ? 0 : pair.last/pair.first}
else
vals.map(&:first)
end
end
end