Let’s examine some of the basic reporting tools first.The following are the most popular tools you can use to diagnose and monitor formance issues in Windows: per-• Windows Experience In
Trang 1Indeed, there are a great many tools available to the Windows administrator We won’ttry to cover them all here, but instead we’ll focus on tools that let you monitor a Win-dows system in real time Let’s examine some of the basic reporting tools first.
The following are the most popular tools you can use to diagnose and monitor formance issues in Windows:
per-• Windows Experience Index
• System Health Report
The Windows Experience
If you want a quick glance at how your system is performing compared to the ations of Microsoft’s hardware performance indexes, you can run the Windows Expe-rience report
expect-To launch the report, click Start, then select Control Panel→System and nance→Performance Information and Tools You will have to acknowledge the UserAccount Control (UAC) to continue
Mainte-You can also access the System Health Report using the search feature on the Startmenu Click Start and enter “performance” in the search box, then click PerformanceInformation and Tools Click Advanced Tools and then click the link “Generate a sys-tem health report” at the bottom of the dialog You will have to acknowledge the UAC
to continue
Microsoft has changed the Windows Experience in Windows 7 The report is very similar to that of earlier Windows versions, but it supplies more information that you can use to judge the performance of your system.
The report is run once after installation, but you can regenerate the report by clickingUpdate My Score
This report rates five areas of your system’s performance: processor (CPU), memory,video controller (graphics), video graphics accelerator (gaming graphics), and the pri-mary hard drive Figure 7-24 shows an example of the Windows Experience report
Microsoft Windows Monitoring | 277
Trang 2There is a little-known feature of this report you may find valuable—click on the link
“Learn how you can improve your computer’s performance” to get a list of best tices for improving each of these scores
prac-You should run this report and regenerate the metrics every time you change the configuration of your system This will help you identify situations where configuration changes affect the performance of your server.
The best use for this tool is to get a general impression of how your system is performingwithout analyzing a ton of metrics A low score in any of the categories can indicate aperformance issue If you examine the report in Figure 7-24, for instance, you will seethat the system has a very low graphics and gaming graphics score This is not unex-pected for a Windows system running as a virtual machine or a headless server, but itmight be alarming to someone who just shelled out several thousand dollars for a high-end gaming system
The System Health Report
One of the unique features and diagnostic improvements in Windows Vista and dows 7 is the ability to generate a report that takes a snapshot of all of the software,hardware, and performance metrics for your system It is analogous to the System Pro-filer of Mac OS X, but also contains performance counters
Win-To launch the System Health Report, click Start, then select Control Panel→System andMaintenance→Performance Information and Tools Next, select Advanced Tools, then
Figure 7-24 The Windows Experience report
278 | Chapter 7: Getting Started with Monitoring
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Trang 3click the link “Generate a system health report” at the bottom of the dialog You willhave to acknowledge the UAC to continue.
You can also access the System Health Report using the search feature on the Startmenu Click Start and enter “performance” in the search box, then click PerformanceInformation and Tools Click Advanced Tools and select the link “Generate a systemhealth report” at the bottom of the dialog Another way to access the System HealthReport is to use the search feature on the Start menu Click Start and enter “systemhealth report” in the search box, then click the link in the Start menu You will have toacknowledge the UAC to continue Figure 7-25 shows an example of the System HealthReport
This report has everything—all of the hardware, software, and many other aspects ofyour system are documented here Notice the report is divided into sections that youcan expand or collapse for easier viewing The following list briefly describes the in-formation displayed by each section:
System Diagnostics Report
The system name and the date the report was generated
Diagnostic Results
Warning messages generated while the report was being run, identifying potentialproblem areas on your computer Also included is a brief overview of the perform-ance of your system at the time the report was run
Trang 4The System Health Report is your key to understanding how your system is configuredand is performing at a glance It is a static report, representing a snapshot of the system.There is a lot of detailed information in the Hardware Configuration, CPU, Network,Disk, and Memory sections Feel free to explore those areas for greater details aboutyour system.
The best use of this tool, beyond examining the performance counters, is to save thereport for later comparison to other reports when your system is performing poorly.You can save an HTML version of the report by selecting File→Save As
You can use the saved report as a baseline for performance of your system If yougenerate the report several times over the course of low, medium, and high usage, youshould be able to put together a general expectation for performance These expecta-tions are important because you can use them to determine whether your performanceissues are within the bounds of expectations When a system enters a period of un-usually high load during a time when it is expected to have a low load, the users’experience may generate complaints If you have these reports to compare to, you cansave yourself a lot of time investigating the exact source of the slowdown
Figure 7-25 The System Health Report
280 | Chapter 7: Getting Started with Monitoring
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Trang 5The Event Viewer
The Windows Event Viewer shows all the messages logged for application, security,and system events It is a great source of information about events that have occurred(or continue to occur) and should be one of the primary tools you use to diagnose andmonitor your system
You can accomplish a great deal with the Event Viewer For example, you can generatecustom views of any of the logs, save the logs for later diagnosis, and set up alerts forspecific events in the future We will concentrate on viewing the logs For more infor-mation about the Event Viewer and how you can set up custom reports and subscribe
to events, consult your Windows help files
To launch the Event Viewer, click the Start button, then right-click Computer andchoose Manage You will have to acknowledge the UAC to continue You can thenclick the Event Viewer link in the left panel You can also launch the Event Viewer byclicking Start, typing “event viewer,” and pressing Enter
The dialog has three panes by default The left pane is a tree view of the custom views, logfiles, and applications and services logs The logs are displayed in the center pane,and the right pane contains the Action menu items The log entries are sorted, by de-fault, in descending order by date and time This allows you to see the most recentmessages first
You can customize the Event Viewer views however you like You can even group and sort events by clicking on the columns in the log header.
Open the tree for the Windows logs to see the base logfiles for the applications, security,and system (among others) Figure 7-26 shows the Event Viewer open and the log treeexpanded
The logs available to view and search include:
Trang 6infor-“memory,” which will then be shown in the center pane.
Each log message falls into one of the following three categories These apply to userprocesses, system components, and applications alike
Error
Indicates a failure of some magnitude, such as a failed process, out-of-memoryproblem, or system fault
Figure 7-26 The Windows Event Viewer
282 | Chapter 7: Getting Started with Monitoring
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Trang 7To view a log, open the corresponding tree in the left pane To view the details aboutany message, click on the message The message will be displayed below the log entries,
as shown in Figure 7-26 In the lower part of the center pane, you can click the Generaltab to see general information about the message, such as the statement logged, when
it occurred, what log it is in, and the user who was running the process or application.You can click the Details tab to see a report of the data logged You can view theinformation as text (Friendly View) or XML (XML View) You can also save the infor-mation for later review; the XML View is useful to pass the report to tools that recognizethe format
The Reliability Monitor
The most interesting monitoring tool in Windows is the Reliability Monitor This is aspecialized tool that plots the significant performance and error events that have oc-curred over time in a graph
A vertical bar represents each day over a period of time The horizontal bar is an gregate of the performance index for that day If there are errors or other significantevents, you will see a red X on the graph Below the bar is a set of drop-down lists thatcontain the software installations and removals, any application failures, hardwarefailures, Windows failures, and any additional failures
ag-This tool is great for checking the performance of the system over a period of time Itcan help diagnose situations when an application or system service has performed cor-rectly in the past but has started performing poorly, or when a system starts generatingerror messages The tool can help locate the day the event first turned up, as well asgive you an idea of how the system was performing when it was running well
Another advantage of this tool is that it gives you a set of daily baselines of your systemover time This can help you diagnose problems related to changing device drivers (one
of the banes of Windows administration), which could go unnoticed until the systemdegrades significantly
In short, the Reliability Monitor gives you the opportunity to go back in time and seehow your system was performing The best part of all? You don’t have to turn it on—
it runs automatically, gleaning much of its data from the logs, and therefore ically knowing your system’s history
automat-Microsoft Windows Monitoring | 283
Trang 8One big source of problems on Windows is connecting and configuring hardware We will not discuss this subject here, as it can easily fill a book in its own right If you have problems with hardware and drivers,
one excellent reference is Microsoft Windows XP Inside Out, by Ed Bott
et al (Microsoft Press).
You can access the Reliability Monitor by clicking Start, typing “reliability,” and ing Enter or clicking on Reliability and Performance Monitor You will have to ac-knowledge the UAC Click Reliability Monitor in the tree pane on the left Fig-ure 7-27 shows an example of the Reliability Monitor
press-In Windows 7, you can launch the Reliability Monitor by clicking Start, entering “action center” in the search box, and pressing Enter You can then select Maintenance→View reliability report The report differs from previous versions of Windows, but offers the same information in a tidier package For example, instead of the drop-down lists, the new Reliability Monitor report lists known incidents in a single list.
Figure 7-27 The Reliability Monitor
284 | Chapter 7: Getting Started with Monitoring
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Trang 9The Task Manager
The Windows Task Manager displays a dynamic list of running processes It has beenaround for a long time and has been improved over various versions of Windows.The Task Manager offers a tabbed dialog with displays for running applications, pro-cesses (this is most similar to the Linux top command), services active on the system,
a CPU performance meter, a network performance meter, and a list of users Unlikesome other reports, this tool generates its data dynamically, refreshing periodically.This makes the tool a bit more useful in observing the system during periods of lowperformance
The reports display the same information as the System Health Report, but in a muchmore compact form, and are updated continuously You can find all of the criticalmetrics needed to diagnose performance issues with CPU, resource-hogging processes,memory, and the network Conspicuously missing is a report on disk performance.One of the interesting features of the Task Manager is that it shows a miniature per-formance meter in the notification area on the Start bar that gives you a chance to watchfor peaks in usage
Running a dynamic performance monitoring tool consumes resources and can affect a system that already suffers poor performance.
You can launch the Task Manager any time by pressing Ctrl+Alt+Del and choosingTask Manager from the menu Figure 7-28 shows an example of the Task Manager andthe process list
The Performance Monitor
The Performance Monitor is the premier tool for tracking performance in a Windowssystem It allows you to select key metrics and plot their values over time It can alsostore the session so you can later review it and create a baseline for your system.The Performance Monitor has metrics for just about everything in your system Thereare counters for many of the smaller details having to do with the basic areas of per-formance: CPU, memory, disk, and network There are a great many other categories
as well
To launch the Performance Monitor, click Start, then select Control Panel→System andMaintenance→Performance Information and Tools Click Advanced Tools and thenclick the link Open Reliability and Performance Monitor near the middle of the dialog.You will have to acknowledge the UAC to continue Click Reliability Monitor in thetree pane on the left to access the Performance Monitor feature
Microsoft Windows Monitoring | 285
Trang 10You can also launch the Performance Monitor by clicking Start, typing “reliability,”and pressing Enter or clicking on Reliability and Performance Monitor You will have
to acknowledge the UAC Click Reliability Monitor in the tree pane on the left to accessthe Performance Monitor feature Figure 7-29 shows an example of the PerformanceMonitor
Microsoft has two levels of metrics: objects that offer a high-level view of an area such
as the processor or memory, and counters that represent a specific detail of the system.Thus, you can monitor the CPU’s performance as a whole or watch the finer details,such as percentage of time idle or the number of user processes running Add theseobjects or counters to the main chart by clicking the green plus sign on the toolbar.This opens a dialog that allows you to choose from a long list of items to add to thechart Adding the items is a simple matter of selecting the object and expanding thedrop-down list on the left, then dragging the desired object to the list on the right
Figure 7-28 The Task Manager
286 | Chapter 7: Getting Started with Monitoring
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Trang 11You can add as many items as you want; the chart will change its axis accordingly Ifyou add too many items to track or the values are too diverse, however, the chart maybecome unreliable It is best to stick to a few related items at a time (such as onlymemory counters) to give you the best and most meaningful chart.
A full description of the features of the Performance Monitor is well beyond the scope
of this chapter We encourage you to investigate additional features such as Data lector Sets and changing the chart’s display characteristics There are many excellenttexts that describe these features and more in great detail
Col-The versatility of the Performance Monitor makes it the best choice for forming lines and recording the behavior of the system over time You can use it as a real-timediagnostic tool
base-Figure 7-29 The Performance Monitor
Microsoft Windows Monitoring | 287
Trang 12If you have used the Reliability or Performance Monitor, you may have noticed a seldom-commented-on feature called the Resource Overview.
This is the default view of the Reliability and Performance Monitor It provides four dynamic performance graphs for CPU, disk, network, and memory Below the graphs are drop-down detail panes containing in- formation about these areas This report is an expanded form of the Task Manager performance graphs and provides yet another point of reference for performance monitoring and diagnosis on Microsoft Windows.
This brief introduction to monitoring performance on Microsoft Windows should suade you that the belief that Microsoft’s Windows platform is difficult to monitor andlacks sophisticated tools is a myth The tools are very extensive (some could argue toomuch so) and provide a variety of views of your system’s data
per-Monitoring as Preventive Maintenance
The techniques discussed so far give you a snapshot of the status of the system ever, most would agree that monitoring is normally an automated task that samplesthe available statistics for anomalies When an anomaly is found, an alert is sent to anadministrator (or group of administrators) to let someone know there may be a prob-lem This turns the reactive task of checking the system status into a proactive task
How-A number of third-party utilities combine monitoring, reporting, and alerts into to-use interfaces There are even monitoring and alert systems for an entire infrastruc-ture For example, Nagios can monitor an entire IT infrastructure and set up alerts foranomalies
easy-There are also monitoring and alert systems available either as part of or an add-on foroperating systems and database systems We will examine the Enterprise Monitor forMySQL in Chapter 13
Conclusion
There are a great many references on both performance tuning and security monitoring.This chapter provides a general introduction to system monitoring While it is notcomprehensive, the material presented is an introduction to the tools, techniques, andconcepts of monitoring your operating system and server performance In the nextchapter, we will take on the task of monitoring a MySQL system and discuss somecommon practices to help keep your MySQL system running at peak performance
288 | Chapter 7: Getting Started with Monitoring
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Trang 13He knew that voice and that tone Joel’s boss was headed his way and about to conductanother drive-by tasking He turned to face his office door as his boss stepped through
it “Did you read Sally’s email about the slowdown?”
Joel recalled that Sally was one of the employees who sent him a message asking whyher application was running slowly He had just finished checking the low-hangingfruit—there was plenty of memory and disk space wasn’t an issue
“Yes, I was just looking into the problem now.”
“Make it your top priority Marketing has a deadline to produce their quarterly salesprojections Let me know what you find.” His boss nodded once and stepped away.Joel sighed and returned to examining the reports on CPU usage while wondering how
to describe technology to the nontechnical
Conclusion | 289
Trang 15CHAPTER 8
Monitoring MySQL
Joel had a feeling today was going to be a better day Everything was going well: theperformance measurements for the servers were looking good and the user complaintswere down He had successfully reconfigured the server and improved performancegreatly There was only one application still performing poorly, but he was sure theproblem wasn’t hardware- or operating-system-related; more likely it was an issue with
a poorly written query Nevertheless, he had sent his boss an email message explaininghis findings and that he was working on the remaining problems
Joel heard quickened footsteps approaching his office He instinctively looked towardhis door, awaiting the now-routine appearance of his boss He was shocked as Mr.Summerson zipped by without so much as a nod in his direction
He shrugged his shoulders and returned to reading his email messages Just then a newmessage appeared with “HIGH PRIORITY” in the subject line in capital letters It wasfrom his boss Chiding himself for holding his breath, Joel relaxed and opened themessage He could hear his boss’s voice in his mind as he read through the message
“Joel, good work on those reports I especially like the details you included aboutmemory and disk performance I’d like you to generate a similar report about the da-tabase server I’d also like you to look into a problem one of the developers is havingwith a query Susan will send you the details.”
With a deep sigh, Joel once again opened his favorite MySQL book to learn more aboutmonitoring the database system “I hope it has something about drilling down intoindividual components,” he mumbled, knowing he needed to get up to speed quickly
on an advanced feature of MySQL
Now that you understand how monitoring works and how to keep your host’s ating systems at peak efficiency, how do you know if your MySQL servers are per-forming at their peak efficiency? Better still, how do you know when they aren’t?
oper-In this chapter, we begin with a look at monitoring MySQL, and then move on tomonitoring and improving performance in your databases We conclude with a lookinto best practices for improving database performance
291
Trang 16What Is Performance?
Before we begin discussions about database performance and general best practices formonitoring and tuning a MySQL server, it is important to define what we mean byperformance For the purposes of this chapter, good performance is defined as meetingthe needs of the user such that the system performs as expediently as the user expects,whereas poor performance is defined as anything less Typically, good performancemeans response time and throughput meet the users’ expectations While this may notseem very scientific, savvy administrators know the best gauge of how well things aregoing is the happiness of the users
That doesn’t mean we don’t measure performance On the contrary, we can and mustmeasure performance in order to know what to fix, when, and how Furthermore, ifyou measure performance regularly, you can even predict when your users will begin
to be unhappy Your users won’t care if you reduce your cache hit rate by 3 percent,beating your best score to date You may take pride in such things, but metrics andnumbers are meaningless when compared to the user’s experience at the keyboard.There is a very important philosophy that you should adopt when dealing with per-formance Essentially, you should never adjust the parameters of your server, database,
or storage engine unless you have a deliberate plan and a full understanding of theexpectations of the change as well as the consequences More importantly, never adjustwithout measuring the effects of the change over time It is entirely possible that youcan improve the performance of the server in the short run but negatively impact per-formance in the long run Finally, you should always consult references from severalsources, including the reference manuals
Now that we’ve issued that stern warning, let’s turn our attention to monitoring andimproving performance of the MySQL server and databases
MySQL Server Monitoring
Managing the MySQL server falls in the category of application monitoring This isbecause most of the performance parameters are generated by the MySQL softwareand are not part of the host operating system As mentioned previously, you shouldalways monitor your base operating system in tandem with monitoring MySQL becauseMySQL is very sensitive to performance issues of the host operating system
There is an entire chapter in the online MySQL Reference Manual that covers all aspects
of monitoring and performance improvement, intriguingly titled “Optimization.” See
http://dev.mysql.com/doc/refman/5.5/en/optimization.html for more details Rather thanrepeat the facts and rhetoric of that excellent reference, we will discuss a general ap-proach to monitoring the MySQL server and examine the various tools available.This section is an introduction to the finer details of monitoring the MySQL server.We'll start with a short discussion of how to change and monitor the behavior of the
292 | Chapter 8: Monitoring MySQL
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Trang 17system, then discuss monitoring primarily for the purposes of diagnosing performanceissues and forming a performance benchmark We will also discuss best practices fordiagnosing performance issues and take a look at monitoring the storage engine sub-layer in MySQL—an area not well understood or covered by other reference sources.
How MySQL Communicates Performance
There are two mechanisms you can use to govern and monitor behavior in the MySQLserver You use server variables to control behavior and status variables to read behaviorconfiguration and statistical information regarding features and performance
There are many variables you can use to configure the server Some can be set only atstartup (called startup options, which can also be set in option files) Others can be set
at the global level (across all connections), the session level (for a single connection),
or both the global and session levels
Session variable settings are not persistent beyond the current tion and are reset when the connection is closed.
connec-You can read server variables using the following commands:
SHOW [GLOBAL | SESSION] VARIABLES;
You can change those variables that are not static (read-only) using the following mands (you can include multiple settings on a single line using a comma separator):
com-SET [GLOBAL | SESSION] <variable_name> = <value>;
SET [@@global | @@session | @@]<variable_name> = <value>;
You can read status variables using the following commands The first two commandsdisplay the value of all local or session scope variables (the default is session) The thirdcommand displays those variables that are global in scope
SHOW STATUS;
SHOW SESSION STATUS;
SHOW GLOBAL STATUS;
We discuss how and when to use these commands in the next section
Performance Monitoring
Performance monitoring in MySQL is the application of the previous commands—specifically, setting and reading system variables and reading status variables TheSHOW and SET commands are only two of the possible tools you can use to accomplishthe task of monitoring the MySQL server
MySQL Server Monitoring | 293
Trang 18Indeed, there are several tools you can use to monitor your MySQL server The toolsavailable in the standard distributions are somewhat limited in that they are consoletools and include special commands you can execute from a MySQL client (e.g., SHOW STATUS) and utilities you can run from a command line (e.g., mysqladmin).
The MySQL client tool is sometimes called the MySQL monitor, but should not be confused with a monitoring tool.
There are also GUI tools available that make things a little easier if you prefer or requiresuch options You can also download the MySQL GUI tools, which include advancedtools that you can use to monitor your system, manage queries, and migrate your datafrom other database systems
We begin by examining how to use the SQL commands and then discuss the MySQLAdministrator GUI and Query Browser tools We also take a look at one of the mostoverlooked tools available to the administrator—the server logs
Some savvy administrators may consider the server logs the first and primary tool foradministering the server Although they are not nearly as vital for performance moni-toring, they can be an important asset in diagnosing performance issues
SQL Commands
All of the SQL monitoring commands are a variant of the SHOW command, which plays internal information about the system and its subsystems While there are manyforms of the SHOW command, the following lists the most common SQL commands youcan use to monitor the MySQL server:
dis-SHOW INDEX FROM <table>
Displays the index cardinality statistics for the specified table, which are used bythe optimizer to estimate join selectivity This command can also be very helpfulwhen diagnosing poorly performing queries, specifically whether the query is for-mulated in such a way as to make use of the indexes available
SHOW PLUGINSDisplays the list of all known plug-ins It shows the name of the plug-in and itscurrent status The storage engines in newer releases of MySQL are implemented
as plug-ins Use this command to get a snapshot of the currently available plug-insand their statuses
SHOW [FULL] PROCESSLIST
Displays data for all threads (including connections) running on the system Thiscommand resembles the process commands of the host operating system The in-formation displayed includes connection data along with the command executing,how long it has been executing, and its current state Like the operating system
294 | Chapter 8: Monitoring MySQL
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Trang 19command it resembles, it can diagnose poor response (too many threads), a zombieprocess (long running or nonresponding), or even connection issues When dealingwith poor performance or unresponsive threads, use the KILL command to termi-nate them The default behavior is to show the processes for the current user TheFULL keyword displays all processes.
You must have the global SUPER privilege to see all processes ning on the system.
run-SHOW [GLOBAL | SESSION] STATUS
Displays the values of all of the system variables You will probably use this mand more frequently than any other Use this command to read all of the statis-tical information available on the server Combined with the GLOBAL or SESSIONkeyword, you can limit the display to those statistics that are global- or session-only
com-SHOW TABLE [FROM <db>] STATUS
Displays detailed information about the tables in a given database This includesthe storage engine, collation, creation data, index data, and row statistics You canuse this command along with the SHOW INDEX command to examine tables whendiagnosing poorly performing queries
SHOW [GLOBAL | SESSION] VARIABLES
Displays the system variables These are typically configuration options for theserver and while they do not display statistical information, viewing the variablescan be very important when determining whether the current configuration haschanged or if certain options are set Some variables are read-only and can only bechanged via the configuration file or the command line on startup, while otherscan be changed globally or set locally You can combine this command with theGLOBAL or SESSION keyword to limit the display to those variables that are global-
or session-only
Limit the Output of SHOW Commands
The SHOW commands in MySQL are very powerful However, they often display toomuch information This is especially true for the SHOW STATUS and SHOW VARIABLES
commands
To see less information, you can use the LIKE <pattern> clause, which permits you toview only those rows matching the pattern specified The most common example isusing the LIKE clause to see only variables for a certain subset, such as replication orlogging You can use the standard MySQL pattern symbols and controls in the LIKE
clause in the same manner as a SELECT query
MySQL Server Monitoring | 295
Trang 20For example, the following displays the status variables that include the name “log”:mysql> SHOW SESSION STATUS LIKE '%log%';
+ -+ -+
| Variable_name | Value | + -+ -+
11 rows in set (0.11 sec)
The commands specifically related to storage engines include the following:
SHOW ENGINE <engine_name> LOGS
Displays the log information for the specified storage engine The information played is dependent on the storage engine This can be very helpful in tuning stor-age engines Some storage engines do not provide this information
dis-SHOW ENGINE <engine_name> STATUS
Displays the status information for the specified storage engine The informationdisplayed depends on the storage engine Some storage engines display more orless information than others For example, the InnoDB storage engine displaysdozens of status variables, while the NDB storage engine shows a few, and theMyISAM storage engine displays no information This command is the primarymechanism for viewing statistical information about a given storage engine andcan be vital for tuning certain storage engines (e.g., InnoDB)
The older synonyms for the SHOW ENGINE commands (SHOW
<engine> LOGS and SHOW <engine> STATUS) have been deprecated.
SHOW ENGINESDisplays a list of all known storage engines for the MySQL release and their statuses(i.e., whether the storage engine is enabled) This can be helpful when decidingwhich storage engine to use for a given database or in replication to determine ifthe same storage engines exist on both the master and the slave
296 | Chapter 8: Monitoring MySQL
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Trang 21The commands specifically related to MySQL replication include the following:
SHOW BINLOG EVENTS [IN '<log_file>'] [FROM <pos>] [LIMIT [<offset>,]
<row count>]
Displays the events as they were recorded to the binary log You can specify a logfile
to examine (leaving off the file tells the system to use the current logfile), and limitoutput to the last events from a particular position or to the first number of rowsafter an offset into the file This command is the primary command used in diag-nosing replication problems It comes in very handy when an event occurs thatdisrupts replication or causes an error during replication
If you do not use a LIMIT clause and your server has been running and logging events for some time you could get a very lengthy out- put If you need to examine a large number of events, you should consider using the mysqlbinlog utility instead.
SHOW BINARY LOGSDisplays the list of the binary logs on the server Use this command to get infor-mation about past and current binlog filenames The size of each file is alsodisplayed This is another useful command for diagnosing replication problemsbecause it will permit you to specify the binlog file for the SHOW BINLOG EVENTScommand, thereby reducing the amount of data you must explore to determinethe problem The SHOW MASTER LOGS command is a synonym
SHOW RELAYLOG EVENTS [IN '<log_file>'] [FROM <pos>] [LIMIT [<offset>,]
<row count>]
Available in MySQL version 5.5.0, this command does the same thing as SHOW BINLOG EVENTS, only with relay logs on the slave If you do not supply a filenamefor the log, events from the first relay log are shown This command has no effectwhen run on the master
SHOW MASTER STATUSDisplays the current configuration of the master It shows the current binlog file,the current position in the file, and all inclusive or exclusive replication settings.Use this command when connecting or reconnecting slaves
SHOW SLAVE HOSTSDisplays the list of slaves connected to the master that used the report-hostoption Use this information to determine which slaves are connected to yourmaster
SHOW SLAVE STATUSDisplays the status information for the system acting as a slave in replication This
is the primary command for tracking the performance and status of your slaves Aconsiderable amount of information is displayed that is vital to maintaining ahealthy slave See Chapter 2 for more information about this command
MySQL Server Monitoring | 297
Trang 22The two most important commands in this list are SHOW VARIABLES and SHOW STATUS.There are a great many variables (over 290 status variables alone), so once you learn tomaster the LIKE clause, you can target the results to specific aspects of the system youwant to monitor.
The variable lists are generally in alphabetical order and are often grouped by feature.However, sometimes the variables are not neatly arranged; in this case you can findthem using a keyword search For example, SHOW STATUS LIKE '%thread%' shows all ofthe status variables related to thread execution Example 8-1 shows this command on
a recent beta release of MySQL
Example 8-1 Showing thread status variables
mysql> SHOW VARIABLES LIKE '%thread%';
+ -+ -+
| Variable_name | Value | + -+ -+
12 rows in set (0.00 sec)
This example shows not only those status variables for thread management, but alsothe thread control for the InnoDB storage engine While you sometimes get moreinformation than you expected, a keyword-based LIKE clause is sure to help you findthe specific variable you need
Knowing which variables to change and which variables to monitor can be the mostchallenging part of monitoring a MySQL server As mentioned, a great deal of valuableinformation on this topic is included in the online MySQL Reference Manual
To illustrate the kinds of features you can monitor in a MySQL server, let us examinethe variables that control the query cache The query cache is one of the most importantperformance features in MySQL if you use the MyISAM storage engine for your appli-cation data It allows the server to buffer frequently used queries and their results inmemory Thus, the more often a query is run, the more likely it is that the results can
be read from the cache rather than reexamining the index structures and tables toretrieve the data Clearly, reading the results from memory is much faster than readingthem from disk every time This can be a performance improvement if your data is readmuch more frequently than it is written (updated)
298 | Chapter 8: Monitoring MySQL
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Trang 23Each time you run a query, it is entered into the cache and has a lifetime governed byhow recently it was used (old queries are dumped first) and how much memory there
is available for the query cache Additionally, there are a number of events that caninvalidate (remove) queries from the cache We include a partial list of these events here:
• Frequent changes (to data or indexes)
• Different forms of the query, which can cause missed cache hits Thus, it is portant to use standardized queries for commonly accessed data You will see later
im-in this chapter how views can help im-in this area
• When a query derives data from temporary tables
• Transaction events that can invalidate queries in the cache (e.g., COMMIT)
You can determine if the query cache is configured and available in your MySQL stallation by examining the have_query_cache variable This is a system variable withglobal scope, but it is read-only You control the query cache using one of several var-iables Example 8-2 shows the server variables for the query cache
in-Example 8-2 Query cache server variables
mysql> SHOW VARIABLES LIKE '%query_cache%';
+ -+ -+
| Variable_name | Value | + -+ -+
6 rows in set (0.00 sec)
As you can see, there are several things you can change to affect the query cache Mostnotable is the ability to temporarily turn off the query cache by setting thequery_cache_size variable—this sets the amount of memory available for the querycache If you set this variable to 0, it effectively turns off the query cache This is notrelated to the have_query_cache variable, which merely indicates that the feature isavailable For more information about configuring the query cache, see the section titled
“Query Cache Configuration” in the online MySQL Reference Manual.You can observe the performance of the query cache by examining several status vari-ables, as shown in Example 8-3
MySQL Server Monitoring | 299
Trang 24Example 8-3 Query cache status variables
mysql> SHOW STATUS LIKE '%Qcache%';
+ -+ -+
| Variable_name | Value | + -+ -+
8 rows in set (0.00 sec)
Here we see one of the more subtle inconsistencies in the MySQL server You cancontrol the query cache using variables that start with query_cache, but the status var-iables start with Qcache While the inconsistency was intentional (to help distinguish aserver variable from a status variable), oddities like this can make searching for the rightitems a challenge
You can and should periodically defragment the query cache with the FLUSH QUERY CACHE command This does not remove results from the cache, but instead allows for internal reorganization to better utilize memory.
There are many nuances to the query cache that allow you to manage and configure itand monitor its performance This makes the query cache an excellent example todemonstrate the complexity of monitoring the MySQL server No single volume (orchapter in a broader work) can cover all such topics The practices described in thischapter therefore are general and are designed to be used with any feature in the MySQLserver However, the specific details may require additional research and a good readthrough the online MySQL Reference Manual
Another pair of commands that can be very useful in monitoring replication are theSHOW MASTER STATUS and SHOW SLAVE STATUS commands We will examine these in moredetail later in this chapter
The mysqladmin Utility
The mysqladmin command-line utility is the workhorse of the suite of command-linetools There are many options and tools (called commands) this utility can perform.The online MySQL Reference Manual discusses the mysqladmin utility briefly In thissection, we examine the options and tools for monitoring a MySQL server
300 | Chapter 8: Monitoring MySQL
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Trang 25Since the utility runs from the command line, it allows administrators to script sets ofoperations much more easily than they can process SQL commands Indeed, some ofthe third-party monitoring tools use a combination of the mysqladmin and SQL com-mands to gather information for display in other forms.
You must specify connection information (user, password, host, etc.) to connect to arunning server The following is a list of commonly used commands As you will see,most of these have equivalent SQL commands that produce the same information.status
Displays a concise description of the status of the server, including uptime, number
of threads (connections), number of queries, and general statistical data Thiscommand provides a quick snapshot of the server’s health
extended-statusDisplays the entire list of system statistics and is similar to the SQL SHOW STATUScommand
processlistDisplays the list of current processes and works the same way as the SQL SHOW PROCESSLIST command
kill <thread id>
Allows you to kill a specified thread Use this in conjunction with processlist tohelp manage runaway or hung processes
variablesDisplays the system server variables and values This is equivalent to the SQL SHOW VARIABLES command
There are many options and other commands not listed here, including commands tostart and stop a slave during replication and manage the various system logs
One of the best features of the mysqladmin utility is its comparison of information overtime The sleep n option tells the utility to execute the specified command once every
n seconds For example, to see the process list refreshed every three seconds on the
local host, use the following command:
mysqladmin -uroot password socket=<sock> processlist sleep 3
This command will execute until you cancel the utility using Ctrl+C
Perhaps the most powerful option is the comparative results for the extended statuscommand Use the relative option to compare the previous execution values withthe current values For example, to see the previous and current values for the systemstatus variables, use this command:
mysqladmin -uroot password socket=<sock> extended-status -relative sleep 3
You can also combine commands to get several reports at the same time For example,
to see the process list and status information together, issue the following command:
mysqladmin root processlist status
MySQL Server Monitoring | 301