磁盘利用率和饱和度

导读

如何观察磁盘的IO利用率以及饱和度?

看文本文给你解药!

翻译团队:知数堂藏经阁项目 – 菜鸟盟

团队成员:菜鸟盟–hades、菜鸟盟-bruce、菜鸟盟-冰焰

译文校稿:叶师傅

原文出处:https://www.percona.com/blog/2017/08/28/looking-disk-utilization-and-saturation/

原文作者:Peter Zaitsev (Percona CEO)

在这篇文章里,会介绍磁盘利用率和饱和度相关的知识。

In this blog post, I will look at disk utilization and saturation.

在之前的博客里面,我写了一些关于CPU使用率和饱和度之间有什么实质性不同,以及CPU使用率、饱和度如何从不同维度影响响应时间(RT)的文章。
现在我们来看另一个影响数据库性能重要因素:存储子系统。在下面文章里,我会用“磁盘”代替存储子系统。

In my previous blog post, I wrote about CPU utilization and saturation, the practical difference between them and how different CPU utilization and saturation impact response times.

Now we will look at another critical component of database performance: the storage subsystem. In this post, I will refer to the storage subsystem as “disk” (as a casual catch-all).

监控IO性能最常用的工具是iostat,会显示如下的信息:

The most common tool for command line IO performance monitoring is iostat, which shows information like this:

root@ts140i:~# iostat -x nvme0n1 5
Linux 4.4.0-89-generic (ts140i)         08/05/2017      _x86_64_        (4 CPU)

avg-cpu:  %user   %nice %system %iowait  %steal   %idle
          0.51    0.00    2.00    9.45    0.00   88.04

Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
nvme0n1           0.00     0.00 3555.57 5887.81 52804.15 87440.73    29.70     0.53    0.06    0.13    0.01   0.05  50.71

avg-cpu:  %user   %nice %system %iowait  %steal   %idle
          0.60    0.00    1.06   20.77    0.00   77.57

Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
nvme0n1           0.00     0.00 7612.80    0.00 113507.20     0.00    29.82     0.97    0.13    0.13    0.00   0.12  93.68

avg-cpu:  %user   %nice %system %iowait  %steal   %idle
          0.50    0.00    1.26    6.08    0.00   92.16

Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
nvme0n1           0.00     0.00 7653.20    0.00 113497.60     0.00    29.66     0.99    0.13    0.13    0.00   0.12  93.52

第一行(avg-cpu)显示的是自系统启动之后平均的性能。某些情况下,用当前系统的压力和平均性能作对比是很有用的。这篇文章的案例是测试环境,所以可以忽略对比这两种情况。
第二行(Device)显示的当前5秒钟的性能指标(在命令行中指定了每5秒输出一次)。

The first line shows the average performance since system start. In some cases, it is useful to compare the current load to the long term average. In this case, as it is a test system, it can be safely ignored. The next line shows the current performance metrics over five seconds intervals (as specified in the command line).

iostat命令用%util列显示利用率的信息,可以通过观察平均请求队列大小(the avgqu-sz 列)或者通过r_await和w_await列(显示平均的读和写的等待)来观察IO饱和度。如果超过正常值,设备就会过度饱和了。

The iostat command reports utilization information in the %util column, and you can look at saturation by either looking at the average request queue size (the avgqu-sz column) or looking at the r_await and w_await columns (which show the average wait for read and write operations). If it goes well above “normal” then the device is over-saturated.

和之前的文章一样,我们会执行Sysbench,然后观察iostat命令、Percona PMM的输出。

As in my previous blog post, we’ll perform some system Sysbench runs and observe how the iostat command line tool and Percona Monitoring and Management graphs behave.

我们用Sysbench测试文件IO,以便观察磁盘的变化。我创建了一个100GB的文件,因为用了DirectIO方式所以所有的请求都会直接打到磁盘。我也会用”sync”刷新模式以便更好的控制IO请求的并发度。

To focus specifically on the disk, we’re using the Sysbench fileio test. I’m using just one 100GB file, as I’m using DirectIO so all requests hit the disk directly. I’m also using “sync” request submission mode so I can get better control of request concurrency.

在这个实验中我用了一个Intel 750 NVME固态硬盘(虽然这并不重要)。

I’m using an Intel 750 NVME SSD in this test (though it does not really matter).

Sysbench FileIO 1线程

    root@ts140i:/mnt/data# sysbench  --threads=1 --time=600 --max-requests=0  fileio --file-num=1 --file-total-size=100G --file-io-mode=sync --file-extra-flags=direct --file-test-mode=rndrd run
     
    File operations:
       reads/s:                      7113.16
       writes/s:                     0.00
       fsyncs/s:                     0.00
     
    Throughput:
       read, MiB/s:                  111.14
       written, MiB/s:               0.00
     
    General statistics:
       total time:                          600.0001s
       total number of events:              4267910
     
    Latency (ms):
            min:                                  0.07
            avg:                                  0.14
            max:                                  6.18
            95th percentile:                      0.17

单线程测试结果通常可以作为基线,通常只有一个请求时的响应时间通常也最快(不过一般也不是最佳吞吐量)。

A single thread run is always great as a baseline, as with only one request in flight we should expect the best response time possible (though typically not the best throughput possible).

Iostat
Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
nvme0n1           0.00     0.00 7612.80    0.00 113507.20     0.00    29.82     0.97    0.13    0.13    0.00   0.12  93.68

磁盘读写延迟

磁盘延迟图像证实了我们从iostat命令看到的磁盘IO延迟,它指定了特定设备。我们用它作为基线和更高并发做对比。

The Disk Latency graph confirms the disk IO latency we saw in the iostat command, and it will be highly device-specific. We use it as a baseline to compare changes to with higher concurrency.

磁盘IO使用率

即便我们只发起一个IO请求(队列深度),但磁盘IO使用率已很接近100%。这个是linux磁盘使用率显示的问题,它不像CPU利用率,由于IO设备的特殊设计机制linux不能直接显示其利用率。它真正有多少可执行单元?他们是怎么被使用的?当做了raid后,每个物理磁盘都可以被视为单独的执行单元,而SSD磁盘以及云存储(比如EBS)则可能有更多执行单元。

Disk IO utilization is close to 100% even though we have just one outstanding IO request (queue depth). This is the problem with Linux disk utilization reporting: unlike CPUs, Linux does not have direct visibility on how the IO device is designed. How many “execution units” does it really have? How are they utilized? Single spinning disks can be seen as a single execution unit while RAID, SSDs and cloud storage (such as EBS) are more than one.

磁盘负载

这个图片显示磁盘负载(或者请求队列大小),它和实际压到磁盘上线程的数量是大致匹配的。

This graph shows the disk load (or request queue size), which roughly matches the number of threads that are hitting disk as hard as possible.

饱和度(IO压力)

饱和度指标图上的IO负载几乎显示了相同的数值。唯一的不同是不像磁盘IO统计信息一样,它显示了整个系统的概要。

The IO load on the Saturation Metrics graph shows pretty much the same numbers. The only difference is that unlike Disk IO statistics, it shows the summary for the whole system.

Sysbench FileIO 4线程

现在让我们把IO提高到四个并发线程,再来看看磁盘的情况:

Now let’s increase IO to four concurrent threads and see how disk responds:

root@ts140i:/mnt/data# sysbench  --threads=4 --time=600 --max-requests=0  fileio --file-num=1 --file-total-size=100G --file-io-mode=sync --file-extra-flags=direct --file-test-mode=rndrd run

    File operations:  
       reads/s:                     26248.44  
       writes/s:                    0.00  
       fsyncs/s:                    0.00  
    Throughput:  
       read, MiB/s:                  410.13  
       written, MiB/s:               0.00  
    General statistics:  
       total time:                                       600.0002s  
       total number of events:                 15749205  
    Latency (ms):  
            min:                                  0.06  
            avg:                                  0.15  
            max:                                 8.73  
            95th percentile:               0.21  

我们看到请求数量线性增加,而请求延迟变化却很小:0.14ms vs 0.15ms。这表明设备内部有足够的执行单元并行处理负载,而且不存在其他瓶颈(如连接接口)。

We can see the number of requests scales almost linearly, while request latency changes very little: 0.14ms vs. 0.15ms. This shows the device has enough execution units internally to handle the load in parallel, and there are no other bottlenecks (such as the connection interface).

Iostat  
Device:        rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await   w_await  svctm  %util  
nvme0n1       0.00    0.00  28808.60    0.00   427668.00     0.00    29.69     4.05    0.14    0.14    0.00   0.03  99.92  

磁盘读写延迟

磁盘IO使用率

磁盘负载

饱和度(IO压力)

Sysbench FileIO 16线程

root@ts140i:/mnt/data# sysbench  --threads=16 --time=600 --max-requests=0  fileio --file-num=1 --file-total-size=100G --file-io-mode=sync --file-extra-flags=direct --file-test-mode=rndrd run

    File operations:  
       reads/s:                    76845.96  
       writes/s:                     0.00  
       fsyncs/s:                    0.00  
    Throughput:  
       read, MiB/s:                  1200.72  
       written, MiB/s:                0.00  
    General statistics:
       total time:                          600.0003s  
       total number of events:              46107727  
    Latency (ms):  
            min:                                  0.07  
            avg:                                  0.21  
            max:                                  9.72  
            95th percentile:                 0.36  
            

从4个线程到16个线程,我们再次看到吞吐量有较大提升而响应时间只轻微变大。如果你仔细观察结果,你将注意到一个更有趣的事情:平均响应时间从0.15ms增加到0.21ms(增加了40%),而95%的响应时间从0.21ms增加到0.36 ms(增加了71%)。我还进行了一个单独的测试来测量99%的响应时间,发现差异甚至更大:0.26ms vs 0.48ms(增加了84%)。

Going from four to 16 threads, we again see a good throughput increase with a mild response time increase. If you look at the results closely, you will notice one more interesting thing: the average response time has increased from 0.15ms to 0.21ms (which is a 40% increase), while the 95% response time has increased from 0.21ms to 0.36ms (which is 71%). I also ran a separate test measuring 99% response time, and the difference is even larger: 0.26ms vs. 0.48ms (or 84%).

这是一个重要的观察:一旦趋于饱和,方差可能会增加,而且其中一些请求会受到不同程度的影响(不仅仅只是我们看到的平均响应时间)。

This is an important observation to make: once saturation starts to happen, the variance is likely to increase and some of the requests will be disproportionately affected (beyond what the average response time shows).

Iostat  
Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util  
nvme0n1           0.00     0.00 82862.20    0.00 1230567.20     0.00    29.70    16.33    0.20    0.20    0.00   0.01 100.00  

磁盘读写延迟

磁盘IO使用率

磁盘负载

饱和度(IO压力)

上面的图表结果符合预期:磁盘负载和IO负载从基本饱和增长到约为16,磁盘IO利用率则保持在100%。

The graphs show an expected figure: the disk load and IO load from saturation are up to about 16, and utilization remains at 100%.

需要注意的是图形中的抖动有所增加。IO利用率飙到100%以上,磁盘IO负载峰值上升到18,而请求队列却并不是很大。这就需要先从这些信息如何去收集的角度去考虑问题。尝试每秒对这些数据进行采样,但是在有实际负载的系统中,这个采集进程也需要费些时间:我们本来希望每秒采集一次数据,而实际上间隔则是1.05 ~ 0.95秒。当数学应用于数据采集时,我们所看到的图表中就可能会有本不应该出现的波峰、波谷(或刺点)。所以从大的角度来看,是可以忽略这些波动的。

One thing to notice is increased jitter in the graphs. IO utilization jumps to over 100% and disk IO load spikes to 18, when there should not be as many requests in flight. This comes from how this information is gathered. An attempt is made to sample this data every second, but with the loaded system it takes time for this process to work: sometimes when we try to get the data for a one-second interval but really get data for 1.05- or 0.95-second intervals. When the math is applied to the data, it creates the spikes and dips in the graph when there should be none. You can just ignore them if you’re looking at the big picture.

Sysbench FileIO 64 Threads

最后,让我们用sysbench跑64个并发线程的情况:

Finally, let’s run sysbench with 64 concurrent threads hitting the disk:

root@ts140i:/mnt/data# sysbench  --threads=64 --time=600 --max-requests=0  fileio --file-num=1 --file-total-size=100G --file-io-mode=sync --file-extra-flags=direct --file-test-mode=rndrd run

    File operations:  
       reads/s:                      127840.59  
       writes/s:                     0.00  
       fsyncs/s:                     0.00  
    
    Throughput:  
       read, MiB/s:                  1997.51  
       written, MiB/s:               0.00  
    
    General statistics:  
       total time:                          600.0014s  
       total number of events:              76704744  
    
    Latency (ms):  
            min:                                  0.08  
            avg:                                  0.50  
            max:                                  9.34  
            95th percentile:                      1.25  

我们可以看到平均响应耗时从0.21ms上升到0.50ms(两倍多),此外95%的响应时间从0.36ms跃升到1.25ms。实际上,我们可以看到IO负载开始饱和了,以前我们看到随着CPU饱和度的增加,并发线程数越多则响应耗时也越久,但这次随着并发线程数的增加,我们并未看到响应耗时随着线性增加。猜测是因为我们测试IO设备有不错的内部IO并行能力,所以响应请求效率很高(即便并发线程从16增加到64)。

We can see the average has risen from 0.21ms to 0.50 (more than two times), and 95% almost tripped from 0.36ms to 1.25ms. From a practical standpoint, we can see some saturation starting to happen, but we’re still not seeing a linear response time increase with increasing numbers of parallel operations as we have seen with CPU saturation. I guess this points to the fact that this IO device has a lot of parallel capacity inside and can process requests more effectively (even going from 16 to 64 concurrent threads).

在这个测试中,当我们将并发性从1个增加到64个时,我们看到响应耗时从0.14ms增加到0.5ms(约三倍)。此时95%的响应耗时从0.17ms增加到1.25ms(约七倍)。实际上,从这时开始看到IO设备趋于饱和了。

Over the series of tests, as we increased concurrency from one to 64, we saw response times increase from 0.14ms to 0.5ms (or approximately three times). The 95% response time at this time grew from 0.17ms to 1.25ms (or about seven times). For practical purposes, this is where we see the IO device saturation start to show.

Iostat  
Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await   w_await  svctm  %util  
nvme0n1           0.00     0.00 138090.20    0.00   2049791.20     0.00    29.69    65.99    0.48    0.48    0.00   0.01 100.24  

我们将略过相关图表,因为它们基本雷同,只是在64并发线程下有更高的延迟。

We’ll skip the rest of the graphs as they basically look the same, just with higher latency and 64 requests in flight.

Sysbench FileIO 256线程

    root@ts140i:/mnt/data# sysbench  --threads=256 --time=600 --max-requests=0  fileio --file-num=1 --file-total-size=100G --file-io-mode=sync --file-extra-flags=direct --file-test-mode=rndrd run
     
    File operations:
       reads/s:                      131558.79
       writes/s:                     0.00
       fsyncs/s:                     0.00
     
    Throughput:
       read, MiB/s:                  2055.61
       written, MiB/s:               0.00
     
    General statistics:
       total time:                          600.0026s
       total number of events:              78935828
     
    Latency (ms):
            min:                                  0.10
            avg:                                  1.95
            max:                                 17.08
            95th percentile:                      3.89            
Iostat
Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
nvme0n1           0.00     0.00 142227.60    0.00 2112719.20     0.00    29.71   268.30    1.89    1.89    0.00   0.0

最后,当并发256个线程时,从平均响应耗时的线性增长结果表明了设备已经过载,且IO请求开始排队。这里没有简单的办法判断它是由于IO总线饱和(此时IO读速率为2GB/sec),还是由于设备内部处理能力所限导致的。

With 256 threads, finally we’re seeing the linear growth of the average response time that indicates overload and queueing to process requests. There is no easy way to tell if it is due to the IO bus saturation (we’re reading 2GB/sec here) or if it is the internal device processing ability.

正如我们所见,并发数从16个到64个时,响应耗时小于线性增长,当从64到256则是线性增长,我们可以看到这个设备最佳的并发是介于16个和64之间。这时的吞吐量可以达到峰值,且没有大量的请求排队。

As we’ve seen a less than linear increase in response time going from 16 to 64 connections, and a linear increase going from 64 to 256, we can see the “optimal” concurrency for this device: somewhere between 16 and 64 connections. This allows for peak throughput without a lot of queuing.

在总结之前,我想对这次特别的测试先做一个重要的说明。这是个随机读的测试,对于很多数据库来说是个重要的工作负载模式,但可能不是最主要负载场景。可能是写为主,或者顺序IO读 (则会有相应不同的表现)。对于其它的工作负载模式,我希望本文可以帮助你在分析时提供些参考、思路。

Before we get to the summary, I want to make an important note about this particular test. The test is a random reads test, which is a very important pattern for many database workloads, but it might not be the dominant load for your environment. You might be write-bound as well, or have mainly sequential IO access patterns (which could behave differently). For those other workloads, I hope this gives you some ideas on how to also analyze them.

另一种思考饱和度的方法

Another Way to Think About Saturation

当我问起他Percona的同学对本文的反馈意见时,Yves Trudeau同学提供了另外一种思考饱和度的方法:与单线程模式相比,平均响应耗时的增长百分比作为饱和度的衡量指标 。例如:

When I asked the Percona staff for feedback on this blog post by, my colleague Yves Trudeau provided another way to think about saturation: measure saturation as percent increase in the average response time compared to the single user. Like this:

Threads Avg Response Time Saturation
1 0.14
4 0.15 1.07x or 7%
16 0.21 1.5x or 50%
64 0.50 3.6x or 260%
256 1.95 13.9x or 1290%

总结

Summary

  • 我们可以看到如何理解磁盘利用率和饱和度要比CPU复杂的多;
  • We can see how understanding disk utilization and saturation is much more complicated than for the CPU:
  • 利用率指标(由iostat和PMM输出的%Util)对理解真实的IO设备利用率是没啥作用。因为它只是衡量在运行中至少有一个请求时的耗时。如果是CPU的这个指标,它将相当于运行在至少一个核上(对于高度并发系统不是很有用);
  • The Utilization metric (as reported by iostat and by PMM) is not very helpful for showing true storage utilization, as it only measures the time when there is at least one request in flight. If you had the same metric for the CPU, it would correspond to something running on at least one of the cores (not very useful for highly parallel systems).
  • 不同于CPU,Linux工具不给我们提供关于存储设备的底层结构和在不饱和的情况下还可以处理多少并行负载的信息。更甚的是,存储设备可能有不同的底层源头会导致饱和。例如,它可能是网络连接,SATA总线,甚至是老内核的内核IO栈去处理高速存储设备(译者注:跟不上时代发展啦)。
  • Unlike a CPU, Linux tools do not provide us with information about the structure of the underlying storage and how much parallel load it should be able to handle without saturation. Even more so, storage might well have different low-level resources that cause saturation. For example, it could be the network connection, SATA BUS or even the kernel IO stack for older kernels and very fast storage.
  • 根据运行中的请求数量来测量饱和有助于判断是否饱和,但是由于我们不知道设备可以高效的并发处理多少请求,只看基础指标我们不能确定设备是否过载;
  • Saturation as measured by the number of requests in flight is helpful for guessing if there might be saturation, but since we do not know how many requests the device can efficiently process concurrently, just looking the raw metric doesn’t let us determine that the device is overloaded
  • 平均响应耗时对于观察饱和度是一个很好的指标,但是和响应耗时一样,您无法判断这个设备的响应耗时是高是低。您需要在上下文中查看它并将其与基线进行比较。当你查看平均响应耗时时,确保你分别查看读响应时间和写响应时间,并且记下平均请求队列大小以确保是相同角度的比较。
  • Avg Response Time is a great metric for looking at saturation, but as with the response time you can’t say what response time is good or bad for this device. You need to look at it in context and compare it to the baseline. When you’re looking at the Avg Response Time, make sure you’re looking at read request response time vs. write request response time separately, and keep the average request size in mind to ensure we are comparing apples to apples.

定制Linux使用的提示符

作者:吴炳锡 来源:http://wubx.net/ 联系方式: wubingxi#163.com 转载请注明作/译者和出处,并且不能用于商业用途,违者必究.

本文发在fireflyclub.org 和 wubx.net 上

用于记录一下提示符:
添加到/etc/profile

zst_ps1()
{
    Date=$(date +%F)
    Time=$(date +%H:%M:%S)

    PS1="\\n\[\e[1;37m[\e[m\]\[\e[1;32m\u\e[m\]\[\e[1;33m@\e[m\]\[\e[1;35m\h $Time \e[m\]\e[1;36m\`pwd\`\e[m\e[1;37m]\e[m\n\\$"
}

PROMPT_COMMAND=zst_ps1

执行:
source /etc/profile

后补知识:

prompt 参数含义:

\d :#代表日期,格式为weekday month date,例如:"Mon Aug 1"
\H :#完整的主机名称
\h :#仅取主机的第一个名字
\t :#显示时间为24小时格式,如:HH:MM:SS
\T :#显示时间为12小时格式
\A :#显示时间为24小时格式:HH:MM
\u :#当前用户的账号名称
\v :#BASH的版本信息
\w :#完整的工作目录名称
\W :#利用basename取得工作目录名称,所以只会列出最后一个目录
# :#下达的第几个命令
\$ :#提示字符,如果是root时,提示符为:# ,普通用户则为:$

终端下色彩:

前景    背景
30      40      黑色
31      41      红色
32      42      绿色
33      43      黄色
34      44      蓝色
35      45      紫红色
36      46      青蓝色
37      47      白色

效果控制

代码              意义   
-------------------------   
0                 OFF   
1                 高亮显示   
4                 underline   
5                 闪烁   
7                 反白显示   
8                 不可见

定义色的开始及结束:
开始: [\e[N;Mm     # 其中N可以指效果或是背景色, M是前景色
结束: [\e[m             #终止特效

练习:

echo -e "\e[1;34m 蓝色字 fireflyclub.org  \e[m"
echo -e "\e[1;35m 紫色字 fireflyclub.org  \e[m"
echo -e "\e[1;36m 天蓝字 fireflyclub.org  \e[m"
echo -e "\e[1;37m 白色字 fireflyclub.org  \e[m"

玩的开心:) 去定制你自已喜欢的提示符吧。

[TIPS]安装数据库提示无法解析机器名处理

作者:吴炳锡 来源:http://www.mysqlsupport.cn/ 联系方式: wubingxi#163.com 转载请注明作/译者和出处,并且不能用于商业用途,违者必究.

在做MySQL初始化时,如果机器的名不能进行反解会出现以下错误:

WARNING: The host 'node2' could not be looked up with resolveip.
This probably means that your libc libraries are not 100 % compatible
with this binary MySQL version. The MySQL daemon, mysqld, should work
normally with the exception that host name resolving will not work.
This means that you should use IP addresses instead of hostnames
when specifying MySQL privileges !
#/usr/local/mysql/bin/resolveip node2

/usr/local/mysql/bin/resolveip: Unable to find hostid for ‘node2’: host not found

处理过程如下

1. 查看机器的名

#hostanme

node2

2. 查看/etc/hosts文件

#cat /etc/hosts

127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6

可见/etc/hosts中无相应的机器名

添ip(本机的ip) 到机器的对应到/etc/hosts中:

最终/etc/hosts内容如下:

127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
10.10.60.148 node2

3.使用resolveip确认是否ok

#/usr/local/mysql/bin/resolveip node2

IP address of node2 is 10.10.60.148

4. 在次运行初始化程序

cd /usr/local/mysql
./script/mysql_db_install

Good luck!

cpuspeed和irqbalance服务器的两大性能杀手

作者:吴炳锡 来源:http://www.mysqlsupport.cn/ 联系方式: wubingxi#gmail.com 转载请注明作/译者和出处,并且不能用于商业用途,违者必究.

最近在一个性能测试中遇到机器的CPU频率不对。查了一下原来是irqbalance和cpuspeed搞出来问题。
irqbalance 理论上:
启用 irqbalance 服务,既可以提升性能,又可以降低能耗。
irqbalance 用于优化中断分配,它会自动收集系统数据以分析使用模式,并依据系统负载状况将工作状态置于 Performance mode 或 Power-save mode。
处于 Performance mode 时,irqbalance 会将中断尽可能均匀地分发给各个 CPU core,以充分利用 CPU 多核,提升性能。
处于 Power-save mode 时,irqbalance 会将中断集中分配给第一个 CPU,以保证其它空闲 CPU 的睡眠时间,降低能耗。
但实际中往往影响cpu的使用均衡,建议服务器环境中关闭。

cpuspeed这个也算是遇到一个大坑,如果bios中已经开启了max performance但cpu主频还是不对,那就是cpuspeed搞出来的鬼(笔记本可以保留这些服务用于省电)。

service irqbalance stop
service cpuspeed stop
chkconfig irqbalance off
chkconfig cpuspeed off

其实相对一个数据库服务器对Linux服务可以进行以下操作:

cd /etc/rc3.d/
mkdir ~/rc3
mv * ~/rc3/
chkconfig --level 3 crond
chkconfig --level 3 sshd on
chkconfig --level 3 rsyslog on
chkconfig --level 3 network on
ln -s /etc/rc.local S99local

最小化的开启服务,如果在需要其它可以手工再开启。

Good Luck.

产生10个随机密码

作者:吴炳锡 来源:http://www.mysqlsupport.cn/ 联系方式: wubingxi#gmail.com 转载请注明作/译者和出处,并且不能用于商业用途,违者必究.

cat /dev/urandom | LC_ALL=C tr -dc "[:alnum:]" | fold -w 10 |head -10

Si1N9kUyuZ
ddzsRXFgxA
caDRBRT4Px
buGk6LkX4d
N5Xod1TOyr
1645cBxAjl
KRjwJR2Txu
nhQedXagL9
RraDEZgfhY
QxCurm5eZF

 

Expression Semantics
alnum Matches alpha-numeric characters
alpha Matches alphabetic characters
blank Matches spaces or tabs
cntrl Matches control characters
digit Matches numeric digits
graph Matches non-space printing characters
lower Matches lower case letters
print Matches printable characters
punct Matches punctuation symbols
space Matches spaces, tabs, returns, and newlines
upper Matches upper case letters
xdigit Matches hexadecimal digits

 

如果需要特别复杂的密码可以试一下:

cat /dev/urandom | LC_ALL=C tr -dc "[:graph:]" | fold -w 10 |head -10

y#@uDo.g-w
RP\oq.8?)e
2R~CCIsLPr
*/V4″%H9WE
!iP2Jj:vqL
zb!w}DZ|lN
2*%|/;X$?>
R7;-Bam|~L
Ps83,_`8Xz
C?mnpUzn*I

另一种方法可以利用uuid 来产生一个密码,一次只能产生一个:

cat /proc/sys/kernel/random/uuid|tr -d "-"

d9d01c59d22f4ebbac16b759103f4fc6

针对跑MySQL的Linux优化经验

译者:吴炳锡 来源:http://www.mysqlsupport.cn/ 联系方式: wubingxi#gmail.com 转载请注明作/译者和出处,并且不能用于商业用途,违者必究.

原文: http://www.mysqlperformanceblog.com/2013/12/07/linux-performance-tuning-tips-mysql/
因为很多MySQL的生产环境都在Linux下,我决定指出一些Linux下跑MySQL的很重要的优化点。这些是大家都知道的,也没什么新东西,但我想在这一个blog里收集整理一下Linux相关的配置优化经验。

文件系统:
ext4(or xfs) mount时使用notime选项
文件系统调度策略: 使用deadline or noop

# echo deadline >/sys/block/sda/queue/scheduler
add "elevator=deadline" to grub.conf

译者推荐: XFS , 目前来看Red hat Enterprise 7 后面XFS成为了默认的文件系统。

内存:
Swappiness and NUMA
译者注: 最好禁掉swappiness 或是在系统标识不使用他。

# echo 0 >/proc/sys/vm/swappiness
add "vm.swapiness=0" to /etc/sysctl.conf

使用numa的interleave all 模式
numactl –interleave=all 启动mysqld
如果使用Percona-server 在mysql_safe里有关于使用numa_interleave的选项。更多关于信息可以查看Percona Server对numa的支持

(并且别忘了使用innodb_flush_method=O_DIRECT)rformance/innodb_numa_s

译者注: 内存优化这块可以考虑使用jemalloc( tokudb,percona都有使用这个方式,官方版本需要自已加载)

CPU:
请确认关闭节能模式
检查:

/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor

确认这里显示是不是ondemand,如查是则启用了节能模式。

另外检查/proc/cpuinfo并对比cpu MHZ的数字和”model name”后面显示的数字是否一样
如果使用了ondemand请禁用他。

例如: “ondemand” 在服务器上运行:

$ps ax|grep kondmand|wc -l
65
$ cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
ondemand

另外查看CPU的标注频率是否和实际频率相符:

/proc/cpuinfo:
model name : Intel(R) Xeon(R) CPU E5-4640 0 @ 2.40GHz
..
cpu MHz : 1200.000

如果不符请禁用ondemand(需要更改bois里的配置)

译者注: 如果CPU超过24个核,建议使用MySQL5.6后面的版本。
这是一个简单的针对Linux跑MySQL的一个优化能增强MySQL的性能及更好用。我也你们知道的Linux,MySQL配置优化方法很感兴趣。请在回复里分享一下:)

尝试mysqlbinlog的flashback功能

作者:吴炳锡 来源:http://www.mysqlsupport.cn/ 联系方式: wubingxi#gmail.com 转载请注明作/译者和出处,并且不能用于商业用途,违者必究.

简介:
mysqlbinlog flashback功能是淘宝彭立勋(http://www.penglixun.com/)的一个很强劲的作品.
主要功能: 对rows格式的binlog可以进行逆向操作.delete反向生成insert, update生成反向的update,insert反向生成delete.让dba同学们也有机会简单的恢复数据.可恢复:insert, update,delete相关的操作

演示一下使用过程:

生成带有flashback mysqlbinlog 工具:

项止主页:http://mysql.taobao.org/index.php/Patch_source_code#Add_flashback_feature_for_mysqlbinlog

准备好MySQL-5.5.18的源码,这里用的Percona-MySQL-5.5.18源码

cd mysql-5.5.18
wget http://mysql.taobao.org/images/0/0f/5.5.18_flashback.diff
patch -p0<5.5.18_flashback.diff

即可以看到了mysqlbinlog , 因这里只为要mysqlbinlog这个程序,所以编译MySQL时没加特别的参数.该工具是否具备flashback功能可以确认一下是否有 "-B" 这个参数.

开始实验

mysql test
mysql> select count(*) from pic_url;
+----------+
| count(*) |
+----------+
| 786476 |
+----------+
1 row in set (0.11 sec)
mysql>delete from pic_url;
Query OK, 786476 rows affected (22.81 sec)
mysql>select count(*) from pic_url;
+----------+
| count(*) |
+----------+
| 0 |
+----------+
1 row in set (0.03 sec)

mysql>show binary logs;
...
| mysql-bin.000011 | 195001447 |
| mysql-bin.000012 | 106 |
+------------------+-----------+

Tips:
定位日值,一般看当前的log如果当前的log文件比较小,那么就是上一个文件至于为什么,这里就不讲了.也可以用mysqlbinlog 去实际查看确认一下.

接下来就是要找到这个delete在log中position的变化区间了.这个没什么技巧,通常使用:

./mysqlbinlog -v --base64-output=decode-rows  /u1/mysql/logs/mysql-bin.000011 >11.sql

然后对11.sql文件进行搜索了表名,找到相应的节点.大表删除通常最后的stop点都在文件最后.找到节点后就可以:

./mysqlbinlog -v --base64-output=decode-rows -B --start-position=377 --stop-position=195001377 /u1/mysql/logs/mysql-bin.000011>B11.sql

同样对B11.sql这个文件验证一下.看看结尾是和预期一样.验证OK后就可以:

./mysqlbinlog -B --start-position=377 --stop-position=195001377 /u1/mysql/logs/mysql-bin.000011|mysql test

如果表比较大,则执行着比较慢.如不出错请耐心等待.执行完毕后:

mysql>select count(*) from pic_url;
+----------+
| count(*) |
+----------+
| 786476 |
+----------+
1 row in set (0.11 sec)

数据又恢复了.

注意:
为防止恢复报错需要把:max_allowed_packet 改到最大值1G;
mysql>set global max_allowed_packet=1024*1024*1024;

#max_allow_packet大小不够时报错如下:
ERROR 1153 (08S01) at line 403133: Got a packet bigger than 'max_allowed_packet' bytes

恢复操作有风险,请在备库操作或是在经验丰富的同学指导下进行.

二进制文件上传不到服务器上,传到github上一个二进制文件:https://github.com/wubx/mysql-binlog-statistic/tree/master/bin  在64的位的linux系统编译的. 有需要的直接下载.

MySQL数据库负载很高连接数很多怎么处理

作者:吴炳锡 来源:http://www.mysqlsupport.cn/ 联系方式: wubingxi#gmail.com 转载请注明作/译者和出处,并且不能用于商业用途,违者必究.

在MySQL数据库连接数很多,而且大多属于活跃的状态时MySQL机器基本上负载很高,属于基本上快要死去的状态了.
这时怎么办呢?

有可能两个办法.
第一先限制Innodb的并发处理.如果innodb_thread_concurrency = 0 可以先改成 16或是64 看机器压力,如果
非常大,先改成16让机器的压力下来,然后慢慢增达,适应自已的业务.
处理方法: set global innodb_thread_concurrency=16;

第二: 对于连接数已经超过600或是更多的情况,可以考虑适当的限制一下连接数,让前端报一下错,也别让DB挂了.
DB在了,总是可以用来加载一下数据,当数据加载到了nosql里了,慢慢的DB压力也会降下来的.
限制单用户连接数在500以下. 如:
set global max_user_connections=500;

(MySQL随着连接数的增加性能会是下降的,这也是thread_pool出现的原因)
另外对于有的监控程序会读取information_schema下面的表的程序可以考虑关闭下面的参数
innodb_stats_on_metadata=0
set global innodb_stats_on_metadata=0;

这个参数主要防止对读取information_schema时造成大量读取磁盘进行信息统计(如果慢查询中出现关于information_schema中表时,也可以考虑禁用该参数)

处理依据:
当学校的一个食堂一分钟只能为两个打饭, 忽然来了100个时人来打饭,又没排队, 不出会现了打饭的师傅要用点时间
去选择为那个用户服务了, 人越多,场面就越乱, 难免出现用户大吼该他的场面, 最后有可能就出现不是打饭了,而时之间相互
打架了,打饭的师傅也将收到同时有90个以上的Server too busy. 如果能排一下队.最多也就50分钟能处理完了.

以前办法,应该可以让MySQLD不会挂掉.如果业务支撑受到限制,还是想办法处理一下.

问题:
高峰期的业务业务支撑数就是服务器的最终需求数吗?

如何查看mysqld进程的Profiler

作者:吴炳锡 来源:http://www.mysqlsupport.cn/ 联系方式: wubingxi#gmail.com 转载请注:译者和出处,并且不能用于商业用途,违者必究.

在mysqld中运行中有时偶而出有点看不出来原因的问题,想看看MySQLD中在执行什么,可以用下来的脚本查一下profiler

#PMP 
#http://poormansprofiler.org/
#!/bin/bash
nsamples=1
sleeptime=0
pid=$(pidof mysqld)

for x in $(seq 1 $nsamples)
  do
    gdb -ex "set pagination 0" -ex "thread apply all bt" -batch -p $pid
    sleep $sleeptime
  done | \
awk '
  BEGIN { s = ""; } 
  /Thread/ { print s; s = ""; } 
  /^\#/ { if (s != "" ) { s = s "," $4} else { s = $4 } } 
  END { print s }' | \
sort | uniq -c | sort -r -n -k 1,1

Perl DBI操作MySQL的Tips

作者:吴炳锡 来源:http://www.mysqlsupport.cn/ 联系方式: wubingxi#gmail.com 转载请注:译者和出处,并且不能用于商业用途,违者必究.

 使用perl连接mysql,这个网上有很多案例了,一般大家都是DBI下的DBD::MySQL这个模块进行.这里做一个mask弄一个TIPS:
 Perl DBI MySQL的字符集为UTF8
 Perl DBI 特殊字符写入时报错
 Perl DBI 连接自动重连或是连接超时

 
1. 当MySQL的字符集是UTF8时需要引入:

use utf8;
binmode(STDOUT, ':encoding(utf8)');
binmode(STDIN, ':encoding(utf8)');
binmode(STDERR, ':encoding(utf8)');

目的: 
解决perl连接mysql到数据后读取显示结果为乱码的问题.
 
2.对于特殊字符的写入,最好使用:

 my $sth=$dbh->prepare("insert into wubx.WeekEvent values(?,?,?,?,?,?,?)");
 $sth->execute($OId,$CId,qq/$Time/,$EventType,qq/$CDesc/,$PId,$RFlag);

对于字符串有可能是用户提交的用qq//包裹,减少特殊字符造成SQL不能执行的情况
3. 如果连接两个数据库有交换的操作或是迁数据,要考虑连连超时的情况.
 报错: MySQL server has gone away
  处理办法:
  在DBD::mysql 4.012以后支持DBI连接的自动重连.需要设置:

  $dbh->{mysql_auto_reconnect} = 1;

  在早期的模块中不支持,简单的方法:

   $dbh->do('set SESSION wait_timeout=72000');
   $dbh->do('set SESSION interactive_timeout=72000');

  此方法适用别的语言连MySQL连接短期丢失或是Server的timeout时间设置太短.