Archive for the 'MySQL' Category

MySQL Daten nach XML exportieren

Immer wieder findet man in Foren und verschiedenen Websites kleine Scripts, die eine MySQL-Tabelle in XML konvertieren. Bereits seit frühen 4er Versionen bietet MySQL dafür die Option –xml/ -X an, welche Ergebnisse der übergebenen Select-Anweisungen in standardkonforme XML-Dateien verwandelt, welche für viele Bedürfnisse ausreichen dürften.

Ein Beispiel:

mysql --xml -e "select alias, display_name, address from nagios.nagios_hosts limit 1,2"

gibt folgendes Ergebnis:

<?xml version="1.0"?>

<resultset statement="select alias, display_name, address from nagios.nagios_hosts limit 1,2
" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <row>
	<field name="alias">Business Processe</field>
	<field name="display_name">business_processes</field>
	<field name="address">10.6.255.99             # dummy IP</field>
  </row>

  <row>
	<field name="alias">untergeordnete Business Processe</field>
	<field name="display_name">business_processes_detail</field>
	<field name="address">10.6.255.99             # dummy IP</field>
  </row>
</resultset>

Auch mysqldump unterstützt die Ausgabe in XML, exportiert die Informationen jedoch aufgabengemäß in zusätzlichen Elementen mit Datenbank- und Tabelleninformationen.

Ein Beispiel:

mysqldump nagios nagios_dbversion --xml

gibt folgendes Ergebnis:

<?xml version="1.0"?>
<mysqldump xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<database name="nagios">
	<table_structure name="nagios_dbversion">
		<field Field="name" Type="varchar(10)" Null="NO" Key="" Default="" Extra="" />
		<field Field="version" Type="varchar(10)" Null="NO" Key="" Default="" Extra="" />
		<options Name="nagios_dbversion" Engine="InnoDB" Version="10" Row_format="Compact" Rows="1" Avg_row_length="16384" Data_length="16384" Max_data_length="0" Index_length="0" Data_free="0" Create_time="2009-09-11 12:04:09" Collation="latin1_swedish_ci" Create_options="" Comment="InnoDB free: 11264 kB" />
	</table_structure>
	<table_data name="nagios_dbversion">
	<row>
		<field name="name">ndoutils</field>
		<field name="version">1.4b7</field>
	</row>
	</table_data>
</database>
</mysqldump>

MySQL command console – Myterm

We’ve  found a new project that was launched just this month called Myterm. An extensible command line client with pipe chaining, Myterm is an alternative tool for querying, filtering and graphical representation of MySQL data.

A clean and simple model, a Myterm command chain starts with a command (normally a query) which returns with a set of results that is sent through a chain of bash filters eg. awk, grep, sort. Myterm then uses libchart to generate graphics of the final data, which are sent to a destination such as a file or browser.

Myterm’s structure is based largely on a plugin concept, where for example, it uses shell exec for browser integration. In this sense it can act as a kind of nucleus where multiple tools can be connected for backup, data transfer, monitoring and more.

Myterm is definitely worth a look, for developers interested in good ideas and administrators who want a quick overview of their database without digging into deep MySQL knowledge.

By applying Unix commands to MySQL, Myterm approaches database querying from a totally different perspective – and that’s why we like it.

Check out the project on Launchpad at https://launchpad.net/myterm.

Specialised MySQL Monitoring with Kontrollbase

kontrollbase logo trans321 Specialised MySQL Monitoring with KontrollbaseWe recently started playing with Kontrollbase, a monitoring, analytics and reporting web app specifically for MySQL databases. A relatively fresh project, it presents thorough performance graphs for all the usual database parameters and performance indicators, with the option to choose time periods.

Most useful however, are its automated host performance and tuning reports which offer not only a description of the problem, but also a recommended solution. This makes Kontrollbase stand out as a monitoring tool. Although Nagios is extremely powerful as a general monitoring solution and offers a sense of capacity utilisation, the user must first know what they are looking forl. With Kontrollbase however, no prior knowledge of tuning is required. Being a MySQL specific tool, it can offer much more by way of capacity management and long term analyses for database growth.

The only drawback we’ve found (as seasoned Nagios users) is the lack of a notification system, so the administrator only gets system alerts when he is in the Kontrollbase interface – at least to our current knowledge.

Nonetheless we give Kontrollbase the thumbs up. With multi-tier authentication and client usage without root database or OS access requirements, Kontrollbase should be useful for larger corporations too. We could imagine however, connecting it to Nagios to get multichannel alert notifications that aren’t currently available.

It boasts to be the only MySQL monitoring tool which can run on a LAMP stack, and surprisingly, it is the only open source we’ve seen specific to MySQL- which is a shame. So if you’re aware of any others, please do share.

MySQLTuner – Wenn es schnell gehen muss

Informationen zur Optimierung einer MySQL Datenbank gibt es im Web in nahezu endloser Fülle. Auch die vorhandene Lektüre, wie z.B. “High Performance MySQL” ist detailliert und gibt auch Einsteigern nützliche Tipps an die Hand um Engpässe auf dem eigenen Server zu ermitteln und idealerweise zu eliminieren.

mysqltuner logo MySQLTuner   Wenn es schnell gehen mussWer weder die Zeit hat sich intensiv einzuarbeiten, noch diverse Fachbücher zu studieren, dem kann MySQLTuner ein hilfreiches Werkzeug sein. Das Perlscript ermittelt anhand der vorhandenen Statistiken mögliche Bottlenecks und zeigt entsprechende Optimierungspotentiale im Form von Empfehlungen und konkreten Einstellungshinweisen.

Neben der Prüfung verschiedener Hit Ratios errechnet MySQLTuner auch den maximal benötigten Speicher der aktuellen Konfiguration. Hier lassen sich mögliche Probleme bei Nutzung der zugelassenen Connection erkennen und vermeiden.

Installation:

wget http://mysqltuner.com/mysqltuner.pl
chmod +x mysqltuner.pl
./mysqltuner.pl

Output:

 >>  MySQLTuner 1.0.0 - Major Hayden
 >>  Bug reports, feature requests, and downloads at http://mysqltuner.com/
 >>  Run with '--help' for additional options and output filtering

-------- General Statistics --------------------------------------------------
[--] Skipped version check for MySQLTuner script
[OK] Currently running supported MySQL version 5.0.51a-24+lenny1
[OK] Operating on 64-bit architecture

-------- Storage Engine Statistics -------------------------------------------
[--] Status: +Archive -BDB -Federated +InnoDB -ISAM -NDBCluster
[--] Data in MyISAM tables: 1G (Tables: 86)
[--] Data in InnoDB tables: 176M (Tables: 120)
[--] Data in MEMORY tables: 124K (Tables: 1)
[!!] Total fragmented tables: 17

-------- Performance Metrics -------------------------------------------------
[--] Up for: 16d 1h 27m 51s (212M q [153.460 qps], 2M conn, TX: 27B, RX: 14B)
[--] Reads / Writes: 50% / 50%
[--] Total buffers: 58.0M global + 2.6M per thread (100 max threads)
[OK] Maximum possible memory usage: 320.5M (15% of installed RAM)
[OK] Slow queries: 0% (100/212M)
[OK] Highest usage of available connections: 36% (36/100)
[OK] Key buffer size / total MyISAM indexes: 16.0M/120.5M
[OK] Key buffer hit rate: 99.8% (63M cached / 99K reads)
[OK] Query cache efficiency: 31.3% (8M cached / 27M selects)
[!!] Query cache prunes per day: 23191
[OK] Sorts requiring temporary tables: 0% (87 temp sorts / 103K sorts)
[!!] Joins performed without indexes: 3446897
[OK] Temporary tables created on disk: 0% (830 on disk / 4M total)
[OK] Thread cache hit rate: 99% (1K created / 2M connections)
[!!] Table cache hit rate: 0% (64 open / 47K opened)
[OK] Open file limit used: 1% (20/1K)
[OK] Table locks acquired immediately: 99% (60M immediate / 60M locks)
[!!] InnoDB data size / buffer pool: 176.7M/8.0M

-------- Recommendations -----------------------------------------------------
General recommendations:
    Run OPTIMIZE TABLE to defragment tables for better performance
    Enable the slow query log to troubleshoot bad queries
    Adjust your join queries to always utilize indexes
    Increase table_cache gradually to avoid file descriptor limits
Variables to adjust:
    query_cache_size (> 16M)
    join_buffer_size (> 128.0K, or always use indexes with joins)
    table_cache (> 64)
    innodb_buffer_pool_size (>= 176M)

Beachten sollte man, dass sich nach Änderung von Parametern und Neustart des Servers einige Empfehlungen ändern, die auf Basis von Laufzeitstatistiken ermittelt werden. Es macht also durchaus Sinn, dass System ein paar Stunden mit der neuen Konfiguration zu betreiben, bevor man erneut Rückschlüsse aus den gewonnenen Informationen zieht.

Weekly snap: Introducing Maatkit, Growl and Martin

weekly snapJuly 13-17 was a week of introductions. From personal to serial, new and nifty – Systems Engineering, MySQL, Nagios and Macs were all in there.

Michael introduced us to his new find: Maatkit, a collection of handy tools to make working with MySQL easier and safer. From replication monitoring for installations of all sizes to database dumps with multiple tables in parallel, Maatkit was Michael’s tip for all busy MySQL buffs.

Stepping into the spotlight, Martin S shared a little on his life as our Systems Engineer- running between internal systems duties and servicing the managed services at our data center.

Reliably there, Julian kicked off a new blog series on Nagios Notifications – to get alerts faster, through better channels and improve in accuracy. He started with Growl for Macs, running through a quick installation and configuration how-to. Next week, he’ll unveil the fastest and simplest way to send SMS alerts. Hang in there!

Maatkit – die Toolbox für MySQL Server

maatkit 300x281 Maatkit   die Toolbox für MySQL ServerEin Kollege hat mich vor kurzem auf Maatkit aufmerksam gemacht, eine Sammlung von Tools die laut dem Ersteller (Baron Schwartz) das Leben bzw. Arbeiten mit MySQL deutlich einfacher und sicherer machen.

Maatkit enthält viele nützliche Werkzeuge sowohl für single instance Installationen als auch komplexere Replikationsszenarien, so gibt es z.B. mk-heartbeat welches die Replikation überwacht. Hierbei wird auf dem Master ein kontiunierliches UPDATE mit dem aktuellen Timestamp auf einen Eintrag ausgeführt, ein zweiter mk-heartbeat Prozess überwacht auf den Slaves den Replication lag. Die Überwachung beruht also nicht auf dem MySQL internen ‘SHOW SLAVE STATUS;‘ Kommando.

Folgende Kommandos erzielen das gewünschte Ergebnis:

  • Master
# mk-heartbeat -D test --table maatkit --update
  • Slave
# mk-heartbeat -h &lt;slave-host&gt; -D test --table maatkit --monitor
3s [  0.08s,  0.02s,  0.01s ]
4s [  0.15s,  0.03s,  0.01s ]
5s [  0.23s,  0.05s,  0.02s ]
6s [  0.33s,  0.07s,  0.02s ]

Ein weiteres mitgeliefertes Programm ist mk-parallel-dump, eine deutlich performantere Alternative zu mysqldump. Wie der Name schon andeutet ermöglicht es dem Benutzer das Sichern einer Datenbank mit mehreren Tabellen in parallel, mit mysqldump werden die Tabellen sequentiell nacheinander gesichert. Zusätzlich erlaubt es “Backup Sets” zu erstellen um logisch zusammenhängende Tabellen (auch Datenbankübergreifen und mit Prioritäten versehen) gleichzeitig zu sichern.

mk-parallel-dump –base-dir /var/tmp –password t3fzpcay
default:            397 tables,   397 chunks,   397 successes,  0 failures,  22.79 wall-clock time,  33.41 dump time
# mk-parallel-dump --base-dir /var/tmp
default:  397 tables, 397 chunks, 397 successes, 0 failures, 22.79 wall-clock time, 33.41 dump time

Ein Tool zum Restore der erstellten Backups ist selbstverständlich ebenfalls enthalten: mk-parallel-restore.

Zusätzlich zu den hier genannten gibt es noch Tools um MySQL Query EXPLAINs übersichtlicher darzustellen, Table Checksummen zu errechnen, Tabellen nach Filtern zu Archivieren und noch vieles mehr. Ein Blick auf die Webseite des Projektes loht in jedem Fall.

Als Fazit lässt sich festhalten das Maatkit die Arbeit mit MySQL deutlich vereinfacht. Jeder der täglich mit MySQL zu tun hat wird dieses Toolkit kennen und lieben lernen, es vereint viele  nützliche Funktionen in einem und ist obendrein bei einigen Distributionen enthalten.

Weekly snap: Install, review and release – NConf, Workbench and Heatmap

Weekly snap

June 29 – July 3 saw the release of MySQL Workbench 5.1 with a few honest thoughts from Bernd E on the former DBDesigner. After testing the community version, he discovered that Reverse Engineering is also available there just as in the standard version, contrary to the official website’s feature list. All in all Bernd gave us the thumbs up – if only for the colour coded foreign key relationships in the ER Modeller. To add to this, Bernd posted his Linux Day presentation slides on ‘XEN in high availability environments’ with praxis oriented solutions, free for all.

Julian showed us how to install NConf on Debian Lenny in 6 easy steps while hardware guru Martin K introduced the Mess PC alternative to email and SMS monitoring notifications – Switch Module 230V 16A won’t go unnoticed with acoustic and visual alerts for those noisy workplaces.

Just in case one new release is not enough, William proudly presented the Generate-a-Heatmap-with-data-from-the-NDO-Database Addon for Nagios / Icinga, aptly dubbed NETWAYS Heatmap for all to download.

MySQL Workbench 5.1

Seit heute ist die neue MySQL Workbench in der Version 5.1 verfügbar. MySQL Workbench, früher DBDesigner, ist ein Werkzeug zur Erstellung von ER-Modellen, deren Pflege und Dokumentation. Die in der Community lang erwartete Version bringt viele Neuigkeiten und Unterstützung der aktuellen MySQL Features wie z.B. Partitions, welche jetzt direkt im Modeller verwaltet werden können.

Auf der Features-Seite von MySQL wird entsprechend nach Community und Standard-Version unterschieden, wobei ich das nicht unterstütze Reverse-Engineering der Community-Version korrigieren muss, da ich das gerade erfolgreich getestet habe. Die Workbench ist für alle gängigen Betriebssysteme verfügbar und machte bei den ersten Tests einen schnellen und auch stabilen Eindruck. Das DBDoc-Feature das auch die Dokumentation und den Export komplexer Modell erlaubt ist leider nur für die Standard-Version verfügbar, wobei der Preis von 79,oo € pro User und Jahr dafür aus meiner Sicht in Ordnung geht.

Besonders gut ist aus meiner Sicht die Darstellung der Schlüsselfremdbeziehungen im ER-Modeller gelöst. Hier werden die Beziehungen zu anderen Tabellen, abhängig von Primär- oder diversen Sekundärschlüssel farblich dargestellt, so dass man auch in komplexen Modellen den Überblick behält.

Hier noch ein paar Screenshots, aber der eigene Test lohnt sich auf jeden Fall.

MySQL Performance Serie – Addon: Analyze Table

performance serie4 MySQL Performance Serie   Addon: Analyze TableIm MySQL-Umfeld gibt es, wie in unsere Performance-Serie ausführlich geschildert, eine Vielzahl an Stellschrauben zur Optimierung.

Ein ganz wichtiger Punkte zur Optimierung von Joined-Selects ist die regelmässige Pflege der der internen Datenbankstatistiken. Hierfür gibt es den Befehl Analyze Table, welcher die Tabelleninhalte analysiert und entsprechende Statistiken über die Schlüsselverteilung speichert.

Der Befehl “show index from table” ermöglicht einen Blick auf die aktuellen Statistiken und die entsprechende Index-Kardinalität. Kardinalität ist quasi der “Grad” der Eindeutigkeit eines bestimmten Tabellenattributs. So sollte z. B. die Kardinalität eines Unique-Key-Attributes nach Aktualisierung durch Analyse Table der Menge der vorhandenen Rows entsprechen.

Diese Statistiken sind für die Datenbank extrem wichtig, um bei verknüpften Abfragen den “richtigen Weg” zur Verringerung der zu verarbeitenden Daten einzuschlagen. Auch wenn der Explain-Befehl vermuten lässt, dass ein angelegter Index nicht verwendet, kann ein Analyze hier Abhilfe schaffen.

Wichtig ist, dass ein Analyze Table einen entsprechenden Lock der Tabelle zur Folge hat und über das Binlog auch in Replikationsumgebungen verteilt wird.

mysqlslap – Datenbanklast erzeugen

Seit der Version 5.1.4 bringt MySQL das Tool mysqlslap mit. Wörtlich übersetzt würde dies dann folgendes bedeuten:

MySQL eine klatschen

Und genau das macht das Tool auch. Mit mysqlslap kann man die Datenbank so richtig unter Last bringen und zum einen Bottlenecks finden oder auch bereits vollzogene Tuningarbeit auf Tauglichkeit prüfen. Über eine Vielzahl von Parametern kann der Aufruf, die Art und Anzahl der Statements als auch der für die Analyse notwendige Debug-Ouptut beeinflusst werden. Die Kenntnis über das Nutzungsprofil der Datenbank ist zwar Voraussetzung für die richtige Konfiguration der Datenbank, jedoch kann das Tool Out-of-the-Box diverse Nutzungsprofile “abspielen”.

Oft fehlt es auch den Entwicklern an adäquaten Werkzeugen um ihre aktuelle Version hinsichtlich Query-Performance zu testen und die Auslastung des Datenbank-Servers, mit bereits in der MySQL-Serie erwähnten Tools wie InnoTop und MyTop, zu beobachten.