pgmonitor 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,18 @@
1
+ *.gem
2
+ *.rbc
3
+ .bundle
4
+ .config
5
+ .yardoc
6
+ Gemfile.lock
7
+ InstalledFiles
8
+ _yardoc
9
+ coverage
10
+ doc/
11
+ lib/bundler/man
12
+ pkg
13
+ rdoc
14
+ spec/reports
15
+ test/tmp
16
+ test/version_tmp
17
+ tmp
18
+ *.swp
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'http://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in pgmonitor.gemspec
4
+ gemspec
@@ -0,0 +1,21 @@
1
+ PG Monitor
2
+ ==========
3
+
4
+ In a multitenant postgres user environment PG Monitor aims to normalize performance between users based on the resources (mainly cpu) that they're using.
5
+
6
+ Caveats
7
+ =======
8
+
9
+ It only works in Linux because of the `ps` command arguments.
10
+
11
+ License
12
+ =======
13
+
14
+ The MIT License (MIT)
15
+ Copyright (c) 2011 Ricardo Chimal, Jr.
16
+
17
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
18
+
19
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
20
+
21
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env rake
2
+ require "psych"
3
+ require "bundler/gem_tasks"
@@ -0,0 +1,34 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ lib = File.expand_path(File.dirname(__FILE__) + '/../lib')
4
+ $LOAD_PATH.unshift(lib) if File.directory?(lib) && !$LOAD_PATH.include?(lib)
5
+
6
+ require 'optparse'
7
+ require 'pgmonitor'
8
+
9
+ Pgmonitor.settings = {
10
+ :debug => false,
11
+ :delay => 2,
12
+ :log_items => nil
13
+ }
14
+
15
+ ARGV.options do |o|
16
+ o.set_summary_indent(" ")
17
+ o.banner = "Usage pgmonitor [OPTIONS]"
18
+ o.on("-d", "--debug", "Enable debug messages") do
19
+ ::Pgmonitor.settings[:debug] = true
20
+ end
21
+ o.on("-r", "--delay SECS", Integer, "Sampling interval, default is #{::Pgmonitor.delay}") do |d|
22
+ ::Pgmonitor.settings[:delay] = d.to_i
23
+ end
24
+ o.on("-l", "--logitems KEYVALPAIRS", Array, "key=val comma delimited pairs to append to log output") do |l|
25
+ ::Pgmonitor.settings[:log_items] = l
26
+ end
27
+
28
+ o.on("-h", "--help", "Show this help message") { $stderr.puts(o); exit }
29
+ o.parse!
30
+ end
31
+
32
+ ::EM.run {
33
+ ::Pgmonitor::PS.run
34
+ }
@@ -0,0 +1,34 @@
1
+ require "pgmonitor/version"
2
+
3
+ module Pgmonitor
4
+ def self.settings=(opts)
5
+ @@settings = opts
6
+ end
7
+
8
+ def self.settings
9
+ @@settings ||= {}
10
+ end
11
+
12
+ def self.debug?
13
+ settings[:debug] == true
14
+ end
15
+
16
+ def self.delay
17
+ settings[:delay] || 2
18
+ end
19
+
20
+ def self.log_items
21
+ return "" unless settings[:log_items]
22
+
23
+ @@log_items ||= if settings[:log_items].kind_of?(Hash)
24
+ " " + settings[:log_items].map { |k,v| "#{k}=#{v}" }.join(" ")
25
+ elsif settings[:log_items].kind_of?(Array)
26
+ " " + settings[:log_items].join(" ")
27
+ else
28
+ " #{settings[:log_items]}"
29
+ end
30
+ end
31
+ end
32
+
33
+ require 'pgmonitor/usagedata'
34
+ require 'pgmonitor/ps'
@@ -0,0 +1,159 @@
1
+ require 'eventmachine'
2
+
3
+ require 'pgmonitor/usagedata'
4
+
5
+ module Pgmonitor::PS
6
+ extend self
7
+
8
+ def log(level, *args)
9
+ if level == :debug
10
+ $stderr.puts(*args) if ::Pgmonitor.debug?
11
+ else
12
+ if level == :error
13
+ $stderr.puts(*args)
14
+ else
15
+ $stdout.puts(*args)
16
+ end
17
+ end
18
+ end
19
+
20
+ def processes(&blk)
21
+ ::EM.system("ps h -u postgres -o user,pid,ni,cp,rss,command") do |output, status|
22
+ data = []
23
+ output.split("\n").each do |line|
24
+ d = line_to_data(line)
25
+ data << d if d
26
+ end
27
+ blk.call(data)
28
+ end
29
+ end
30
+
31
+ @@last_renice = Time.now
32
+
33
+ def need_to_renice?
34
+ @@last_renice < Time.now - 60
35
+ end
36
+
37
+ def renice(&blk)
38
+ unless need_to_renice?
39
+ blk.call if blk
40
+ return
41
+ end
42
+
43
+ databases = ::Pgmonitor::UsageData.avg
44
+ databases.delete('postgres')
45
+ databases.each do |db, d|
46
+ if d['cpu'] > 200
47
+ d['nice'] = 19
48
+ elsif d['cpu'] > 100
49
+ d['nice'] = 15
50
+ else
51
+ d['nice'] = 5
52
+ end
53
+
54
+ # if the number of connections is "high"
55
+ # you're probably stressing the machine just by
56
+ # having open connections
57
+ if d['connections'] > 20 && d['nice'] < 15
58
+ d['nice'] = 15
59
+ end
60
+ end
61
+
62
+ databases.each do |db, d|
63
+ log(:notice, "usage db_name='#{db}' cpu=#{d['cpu']} mem=#{d['mem']} nice=#{d['nice']} elapsed=#{d['elapsed_time']} connections=#{d['connections']}#{::Pgmonitor.log_items}")
64
+ end
65
+
66
+ processes do |psdata|
67
+ @@last_renice = Time.now
68
+ psdata.each do |ps|
69
+ db = ps['database']
70
+ next unless databases.has_key?(db)
71
+ nice = databases[db]['nice']
72
+ next if nice == ps['nice'].to_i
73
+
74
+ log(:debug, "renicing db_name='#{db}' pid=#{ps['pid']} from=#{ps['nice']} to=#{nice}")
75
+ `renice #{nice} -p #{ps['pid']} > /dev/null 2>&1`
76
+ end
77
+
78
+ renice_writer_process
79
+
80
+ EM.next_tick(&blk) if blk
81
+ end
82
+ end
83
+
84
+ def queue
85
+ EM.add_timer(::Pgmonitor.delay) { ::Pgmonitor::PS.run }
86
+ end
87
+
88
+ def run
89
+ processes do |data|
90
+ ::Pgmonitor::PS.scrape(data) { renice { ::Pgmonitor::PS.queue } }
91
+ end
92
+ end
93
+
94
+ def scrape(data, &blk)
95
+ t1 = Time.now
96
+ cdata = cummulate_data(data, t1)
97
+ add_cummulative_data(cdata)
98
+ blk.call
99
+ end
100
+
101
+ def add_cummulative_data(cdata)
102
+ cdata.each do |database, data|
103
+ ::Pgmonitor::UsageData.add(database, data)
104
+ end
105
+ ::Pgmonitor::UsageData.clean
106
+ end
107
+
108
+ def cummulate_data(data, timeslice)
109
+ databases = {}
110
+ data.each do |d|
111
+ db = d['database']
112
+ databases[db] ||= {
113
+ 'pids' => [],
114
+ 'cpu' => 0,
115
+ 'mem' => 0,
116
+ 'connections' => 0,
117
+ 'sources' => [],
118
+ 'timeslice' => timeslice,
119
+ }
120
+
121
+ databases[db]['pids'] << d['pid']
122
+ databases[db]['cpu'] += d['cpu'].to_i
123
+ databases[db]['mem'] += d['mem'].to_i
124
+ databases[db]['connections'] += 1
125
+ databases[db]['sources'] << "#{d['ip']}:#{d['port']}"
126
+ end
127
+ databases
128
+ end
129
+
130
+ def line_to_data(line)
131
+ tokens = line.split(/\s+/)
132
+
133
+ pdata = { }
134
+ pdata['user'] = tokens.shift
135
+ pdata['pid'] = tokens.shift
136
+ pdata['nice'] = tokens.shift
137
+ pdata['cpu'] = tokens.shift
138
+ pdata['mem'] = tokens.shift
139
+ command = tokens.join(' ')
140
+
141
+ data = command_to_data(command)
142
+ return unless data
143
+
144
+ data.merge!(pdata)
145
+ data
146
+ end
147
+
148
+ def command_to_data(command)
149
+ regex = /^postgres: ([\w\d]+) ([\w\d]+) ((:?\d{1,3}\.){3}(?:\d{1,3}))\((\d+)\)/
150
+ if m = regex.match(command)
151
+ { 'database' => m[1], 'ip' => m[3], 'port' => m[4] }
152
+ end
153
+ end
154
+
155
+ def renice_writer_process
156
+ `ps aux | grep 'postgres: writer process' | awk '{print $2}' | xargs renice 4 -p > /dev/null 2>&1`
157
+ `ps aux | grep 'postgres: wal writer process' | awk '{print $2}' | xargs renice 4 -p > /dev/null 2>&1`
158
+ end
159
+ end
@@ -0,0 +1,55 @@
1
+ module Pgmonitor::UsageData
2
+ extend self
3
+ @@data = {}
4
+
5
+ def data
6
+ @@data
7
+ end
8
+
9
+ # @@data = {
10
+ # mem and cpu are aggregated among all the different postgres processes
11
+ # 'database' => [ { 'mem' => '50024', 'cpu' => '05', 'connections' => 1, 'timeslice' => Time.now } ]
12
+ # }
13
+
14
+ def add(database, data)
15
+ @@data[database] ||= []
16
+ @@data[database] << data
17
+ end
18
+
19
+ def clean
20
+ cutoff = Time.now - 60*2
21
+ @@data.each do |database, d|
22
+ d.reject! { |d| d['timeslice'] < cutoff }
23
+ @@data.delete(database) if d.size == 0
24
+ end
25
+ end
26
+
27
+ def avg
28
+ avgs = {}
29
+ @@data.each do |database, d|
30
+ next if d.size == 0
31
+ avgs[database] = avg_data(d)
32
+ end
33
+ avgs.each { |db, d| avgs.delete(db) if db.nil? or d.nil? }
34
+ avgs
35
+ end
36
+
37
+ def avg_data(mdata)
38
+ fields = %w[mem cpu connections]
39
+ avgs = {}
40
+ num = mdata.size
41
+ fields.each do |field|
42
+ avgs[field] ||= 0
43
+ mdata.each do |d|
44
+ avgs[field] += d[field]
45
+ end
46
+ avgs[field] = avgs[field] / num
47
+ end
48
+
49
+ avgs['timeslice'] = mdata.collect { |d| d['timeslice'] }.sort
50
+ t1 = avgs['timeslice'].first
51
+ t2 = avgs['timeslice'].last
52
+ avgs['elapsed_time'] = (t2 - t1).to_i
53
+ avgs
54
+ end
55
+ end
@@ -0,0 +1,3 @@
1
+ module Pgmonitor
2
+ VERSION = "1.0.0"
3
+ end
@@ -0,0 +1,20 @@
1
+ # -*- encoding: utf-8 -*-
2
+ require File.expand_path('../lib/pgmonitor/version', __FILE__)
3
+
4
+ Gem::Specification.new do |gem|
5
+ gem.authors = ["Ricardo Chimal, Jr."]
6
+ gem.email = ["ricardo@heroku.com"]
7
+ gem.description = %q{Monitor pg connections on a postgres server}
8
+ gem.summary = %q{Monitor pg connections on a postgres server}
9
+ gem.homepage = "http://github.com/ricardochimal/pgmonitor"
10
+
11
+ gem.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
12
+ gem.files = `git ls-files`.split("\n")
13
+ gem.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
14
+ gem.name = "pgmonitor"
15
+ gem.require_paths = ["lib"]
16
+ gem.bindir = "bin"
17
+ gem.version = Pgmonitor::VERSION
18
+
19
+ gem.add_dependency "eventmachine", ">= 0.12.4"
20
+ end
metadata ADDED
@@ -0,0 +1,94 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: pgmonitor
3
+ version: !ruby/object:Gem::Version
4
+ prerelease: false
5
+ segments:
6
+ - 1
7
+ - 0
8
+ - 0
9
+ segments_generated: true
10
+ version: 1.0.0
11
+ platform: ruby
12
+ authors:
13
+ - Ricardo Chimal, Jr.
14
+ autorequire:
15
+ bindir: bin
16
+ cert_chain: []
17
+
18
+ date: 2011-11-17 00:00:00 -08:00
19
+ default_executable:
20
+ dependencies:
21
+ - !ruby/object:Gem::Dependency
22
+ name: eventmachine
23
+ requirement: &id001 !ruby/object:Gem::Requirement
24
+ none: false
25
+ requirements:
26
+ - - ">="
27
+ - !ruby/object:Gem::Version
28
+ segments:
29
+ - 0
30
+ - 12
31
+ - 4
32
+ segments_generated: true
33
+ version: 0.12.4
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: *id001
37
+ description: Monitor pg connections on a postgres server
38
+ email:
39
+ - ricardo@heroku.com
40
+ executables:
41
+ - pgmonitor
42
+ extensions: []
43
+
44
+ extra_rdoc_files: []
45
+
46
+ files:
47
+ - .gitignore
48
+ - Gemfile
49
+ - README.md
50
+ - Rakefile
51
+ - bin/pgmonitor
52
+ - lib/pgmonitor.rb
53
+ - lib/pgmonitor/ps.rb
54
+ - lib/pgmonitor/usagedata.rb
55
+ - lib/pgmonitor/version.rb
56
+ - pgmonitor.gemspec
57
+ has_rdoc: true
58
+ homepage: http://github.com/ricardochimal/pgmonitor
59
+ licenses: []
60
+
61
+ post_install_message:
62
+ rdoc_options: []
63
+
64
+ require_paths:
65
+ - lib
66
+ required_ruby_version: !ruby/object:Gem::Requirement
67
+ none: false
68
+ requirements:
69
+ - - ">="
70
+ - !ruby/object:Gem::Version
71
+ hash: -2644295259675393237
72
+ segments:
73
+ - 0
74
+ segments_generated: true
75
+ version: "0"
76
+ required_rubygems_version: !ruby/object:Gem::Requirement
77
+ none: false
78
+ requirements:
79
+ - - ">="
80
+ - !ruby/object:Gem::Version
81
+ hash: -2644295259675393237
82
+ segments:
83
+ - 0
84
+ segments_generated: true
85
+ version: "0"
86
+ requirements: []
87
+
88
+ rubyforge_project:
89
+ rubygems_version: 1.3.7
90
+ signing_key:
91
+ specification_version: 3
92
+ summary: Monitor pg connections on a postgres server
93
+ test_files: []
94
+