Jump to content

Toolserver:Mytop-all

From mediawiki.org

This page was moved from the Toolserver wiki.
Toolserver has been replaced by Toolforge. As such, the instructions here may no longer work, but may still be of historical interest.
Please help by updating examples, links, template links, etc. If a page is still relevant, move it to a normal title and leave a redirect.

mytop-all is a Python script written by Bryan that shows all active connections on the toolserver's MySQL servers.

To run it, copy the code to a place in your $PATH, call it mytop-all and make it writable.

In case more servers are added later try incrementing the 3 near the end of the script.

Source

[edit]
#!/usr/bin/python

import MySQLdb
import curses

class MyTop(object):
	def __init__(self, server_count, mysql_config):
		self.servers = dict([(i + 1, MySQLdb.connect(host = 'sql-s%s' % (i + 1), **mysql_config)) for i in xrange(server_count)])
		self.cursors = dict([(i, self.servers[i].cursor()) for i in self.servers])
		curses.setupterm()

	def header(self):
		print curses.tigetstr('clear')
		print ' ' + self.pad_header('', 4) + self.pad_header('Id', 12) + self.pad_header('Database', 12) + \
			self.pad_header('Cmd', 8) + self.pad_header('Time', 6) +  self.pad_header('State', 8) + '  Info'
		print '-' * (1 + 4 + 4 + 12 + 12 + 8 + 6 + 8 + 2 + 4 + 2)
	def pad_header(self, name, length):
		return (' ' + name + ' ' * length)[:length]
	def pad(self, data, length):
		return (str(data) + ' ' * length)[:length]

	def format_row(self, server, id, user, host, db, command, time, state, info):
		print ' ' + self.pad('s%s' % server, 4) + self.pad(id, 12) + self.pad(db, 12) + \
			self.pad(command, 8) + self.pad(time, 6) + self.pad(state, 8) + \
			self.truncate(info, 2 * curses.tigetnum('cols') - (1 + 4 + 4 + 12 + 12 + 8 + 6 + 8))

	def truncate(self, data, length):
		if not data: return ''
		if len(str(data)) > length: return str(data)[:length]
		return data

	def next(self):
		self.header()
		for server, cursor in self.cursors.iteritems():
			cursor.execute('SHOW FULL PROCESSLIST')
			for row in cursor:
				self.format_row(server, *row)

	def __iter__(self):
		return self

if __name__ == '__main__':
	import sys, time
	mytop = MyTop(7, {'read_default_file': '~/.my.cnf'})
	for i in mytop:
		try:
			time.sleep(1)
		except KeyboardInterrupt:
			sys.exit()
		except:
			raise

Category:Documentation