tar and netcat

 

stdin and stdout with tar

While archiving, we can specify stdout as the output file so another command in a pipe can read it as stdin and process the archive.

This technique will transfer data through a Secure Shell (SSH) connection, for example:

    $ tar cvf - files/ | ssh user@example.com "tar xv -C Documents/"

In the preceding example, the files/directory is added to a tar archive which is output to stdout (denoted by -) and extracted to the Documents folder on the remote system.

Receiving server(open port 44023)

root@Receiver:/StoragePool/data/logs/Firewalls/2020/11# nc -l 44023 | pv | tar x

2.27GiB 0:01:16 [46.6MiB/s] [                                                                                                                                         <=>                   ]




Sending server (send dir named 12 to 22)

root@Sender:/opt/immune/storage/logs/Firewalls/2020/11# ls

01  02  03  04  05  06  07  08  09  10  11  12  13  14  15  16  17  18  19  20  21  22

root@Sender:/opt/immune/storage/logs/Firewalls/2020/11# tar cf - 13  14  15  16  17  18  19  20  21 | nc 172.16.104.39 44023 

The sender server should run the following command


$ tar cf - logs/ | netcat 192.168.0.1 9000

and the receiveing server should listen with with this command

$ netcat -l -p 9000 | tar x

zfs send receive using netcat

zfs sender part

zfs send tank/test@snap100 | nc -w 20 10.0.1.2 8023

This means that the dataset “test” from my ZFS pool “tank” and snapshot “manual-2020-08-27_19-18” are being sent via netcat to host 10.0.1.2 on port 8023.


zfs receive side

nc -l 8023 -w 120 | zfs receive tank/test

This means that netcat is listening on port 8023 for the dataset “test” and adding it to the ZFS pool “tank”.


to see progress use pv eg.

nc -l 8023 -w 120 | pv | zfs receive tank/test


Send Incremenatl Snapshots

root@141:# zfs list -t snapshot

NAME                  USED  AVAIL  REFER  MOUNTPOINT

LP_Pool/storage@100  2.16M      -  1.38G  -             ## this is already sent 

LP_Pool/storage@101   136K      -  1.89G  -             # new snap 1

LP_Pool/storage@102      0      -  2.91G  -             # new snap 2


root@141:# zfs send -I LP_Pool/storage@100 LP_Pool/storage@102 | nc -w 120 10.45.9.148 44022


It will send @100 @101 and @102.

the recv command will be same

Speed will depend on disk on sendeer side, Eg. below stats show that disk performance is saturated.

iostat -xz 1


avg-cpu:  %user   %nice %system %iowait  %steal   %idle

          49.70    0.00    8.48    0.00    0.00   41.82


Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util

sda               0.00     0.00   13.59    0.00    73.79     0.00    10.86     2.71  196.29  196.29    0.00  73.71 100.19

sdb               0.00     0.00   14.56    0.00   166.99     0.00    22.93     2.58  177.33  177.33    0.00  68.80 100.19


avg-cpu:  %user   %nice %system %iowait  %steal   %idle

          48.51    0.00   10.45    2.99    0.00   38.06


Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util

sda               0.00     0.00   15.00    0.00   124.00     0.00    16.53     2.52  181.33  181.33    0.00  65.33  98.00

sdb               0.00     0.00   15.00    0.00   120.00     0.00    16.00     2.66  189.87  189.87    0.00  65.33  98.00


avg-cpu:  %user   %nice %system %iowait  %steal   %idle

          38.69    0.00   13.69    0.00    0.00   47.62


Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util

sda               0.00     0.00   25.00    0.00   188.00     0.00    15.04     2.57  105.12  105.12    0.00  36.96  92.40

sdb               0.00     0.00   26.00    0.00   192.00     0.00    14.77     2.85  107.38  107.38    0.00  39.38 102.40

dstat

 dstat -- 

output

...network recv=123B | send 297k ==> this means 

download 123 Bytes , upload or sent is 297 KiloBYTES

kdump on ubuntu 20.04 part 2

 Debugging the Panic with crash

Time to figure out what went wrong and to find where in the source code the problem occurs.

To be able to start crash, we need a kernel with debugging symbols built in. Now, this kernel has to exactly match the production kernel that we crashed, and cannot be compressed. For Ubuntu systems, we are looking for the kernel ddeb.


We can add the ddeb repository to our system with:

$ sudo tee /etc/apt/sources.list.d/ddebs.list << EOF

deb http://ddebs.ubuntu.com/  $(lsb_release -cs) main restricted universe multiverse

deb http://ddebs.ubuntu.com/  $(lsb_release -cs)-security main restricted universe multiverse

deb http://ddebs.ubuntu.com/  $(lsb_release -cs)-updates  main restricted universe multiverse

deb http://ddebs.ubuntu.com/  $(lsb_release -cs)-proposed main restricted universe multiverse

EOF

if you get below error

Reading package lists... Done

E: The repository 'http://ddebs.ubuntu.com xenial-security Release' does not have a Release file.

N: Updating from such a repository can't be done securely, and is therefore disabled by default.

N: See apt-secure(8) manpage for repository creation and user configuration details.


add [trusted=yes] for example


/# cat /etc/apt/sources.list.d/ddebs.list 

deb [trusted=yes] http://ddebs.ubuntu.com/ xenial          main restricted universe multiverse

deb [trusted=yes] http://ddebs.ubuntu.com/ xenial-security main restricted universe multiverse

deb [trusted=yes] http://ddebs.ubuntu.com/ xenial-updates  main restricted universe multiverse

deb [trusted=yes] http://ddebs.ubuntu.com/ xenial-proposed main restricted universe multiverse

We can then import the GPG key for the repo, refresh package lists and install the vmlinux package with:-

$ sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys C8CAB6595FDFF622

$ sudo apt update

$ sudo apt install linux-image-$(uname -r)-dbgsym

Starting crash ....................

# crash <vmlinux>  <dumpfile>

# crash /usr/lib/debug/boot/vmlinux-5.4.0-42-generic /var/crash/202008290918/dump.202008290918 


crash 7.2.8

Copyright (C) 2002-2020  Red Hat, Inc.

Copyright (C) 2004, 2005, 2006, 2010  IBM Corporation

Copyright (C) 1999-2006  Hewlett-Packard Co

Copyright (C) 2005, 2006, 2011, 2012  Fujitsu Limited

Copyright (C) 2006, 2007  VA Linux Systems Japan K.K.

Copyright (C) 2005, 2011  NEC Corporation

Copyright (C) 1999, 2002, 2007  Silicon Graphics, Inc.

Copyright (C) 1999, 2000, 2001, 2002  Mission Critical Linux, Inc.

This program is free software, covered by the GNU General Public License,

and you are welcome to change it and/or distribute copies of it under

certain conditions.  Enter "help copying" to see the conditions.

This program has absolutely no warranty.  Enter "help warranty" for details.

 

GNU gdb (GDB) 7.6

Copyright (C) 2013 Free Software Foundation, Inc.

License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software: you are free to change and redistribute it.

There is NO WARRANTY, to the extent permitted by law.  Type "show copying"

and "show warranty" for details.

This GDB was configured as "x86_64-unknown-linux-gnu"...


WARNING: kernel relocated [556MB]: patching 114875 gdb minimal_symbol values

      KERNEL: /usr/lib/debug/boot/vmlinux-5.4.0-42-generic             

    DUMPFILE: /var/crash/202008290918/dump.202008290918  [PARTIAL DUMP]

        CPUS: 4

        DATE: Sat Aug 29 09:16:55 2020

      UPTIME: 00:04:40

LOAD AVERAGE: 1.97, 1.79, 0.80

       TASKS: 504

    NODENAME: user1-HP-Pavilion-dv4-Notebook-PC

     RELEASE: 5.4.0-42-generic

     VERSION: #46-Ubuntu SMP Fri Jul 10 00:24:02 UTC 2020

     MACHINE: x86_64  (2494 Mhz)

      MEMORY: 7.9 GB

       PANIC: "Kernel panic - not syncing: sysrq triggered crash"

         PID: 4488

     COMMAND: "bash"

        TASK: ffff89dec9895d00  [THREAD_INFO: ffff89dec9895d00]

         CPU: 3

       STATE: TASK_RUNNING (PANIC)


crash> log

[    0.000000] microcode: microcode updated early to revision 0x21, date = 2019-02-13

[    0.000000] Linux version 5.4.0-42-generic (buildd@lgw01-amd64-038) (gcc version 9.3.0 (Ubuntu 9.3.0-10ubuntu2)) #46-Ubuntu SMP Fri Jul 10 00:24:02 UTC 2020 (Ubuntu 5.4.0-42.46-generic 5.4

.44)

[    0.000000] Command line: BOOT_IMAGE=/boot/vmlinuz-5.4.0-42-generic root=UUID=eb00fc0a-fab7-42a7-a272-7ba7b07dd94d ro quiet splash crashkernel=512M-:192M vt.handoff=7

[    0.000000] KERNEL supported cpus:

[    0.000000]   Intel GenuineIntel

[    0.000000]   AMD AuthenticAMD

[    0.000000]   Hygon HygonGenuine

[    0.000000]   Centaur CentaurHauls

[    0.000000]   zhaoxin   Shanghai  

[    0.000000] x86/fpu: Supporting XSAVE feature 0x001: 'x87 floating point registers'

[    0.000000] x86/fpu: Supporting XSAVE feature 0x002: 'SSE registers'

[    0.000000] x86/fpu: Supporting XSAVE feature 0x004: 'AVX registers'

[    0.000000] x86/fpu: xstate_offset[2]:  576, xstate_sizes[2]:  256

[    0.000000] x86/fpu: Enabled xstate features 0x7, context size is 832 bytes, using 'standard' format.

[    0.000000] BIOS-provided physical RAM map:

[    0.000000] BIOS-e820: [mem 0x0000000000000000-0x0000000000087fff] usable

[    0.000000] BIOS-e820: [mem 0x0000000000088000-0x00000000000bffff] reserved

[    0.000000] BIOS-e820: [mem 0x0000000000100000-0x000000001fffffff] usable

[    0.000000] BIOS-e820: [mem 0x0000000020000000-0x00000000201fffff] reserved

[    0.000000] BIOS-e820: [mem 0x0000000020200000-0x0000000040003fff] usable

[    0.000000] BIOS-e820: [mem 0x0000000040004000-0x0000000040004fff] reserved

[    0.000000] BIOS-e820: [mem 0x0000000040005000-0x00000000aa26efff] usable

Note that the crashed process is shown with ‘>’.

The " log " command brings up the contents of dmesg, for that particular session.

[  132.749323] audit: type=1400 audit(1598706924.030:74): apparmor="DENIED" operation="open" profile="snap.snap-store.ubuntu-software" name="/var/lib/snapd/hostfs/usr/share/icons/Yaru/8x8/emblems/" pid=3997 comm="pool-org.gnome." requested_mask="r" denied_mask="r" fsuid=1000 ouid=0

[  132.751313] audit: type=1400 audit(1598706924.030:75): apparmor="DENIED" operation="open" profile="snap.snap-store.ubuntu-software" name="/var/lib/snapd/hostfs/usr/share/icons/Yaru/icon-theme.cache" pid=3997 comm="pool-org.gnome." requested_mask="r" denied_mask="r" fsuid=1000 ouid=0

[  223.805844] sysrq: Trigger a crash

[  223.805853] Kernel panic - not syncing: sysrq triggered crash

[  223.805861] CPU: 3 PID: 4488 Comm: bash Kdump: loaded Tainted: G           OE     5.4.0-42-generic #46-Ubuntu

[  223.805865] Hardware name: Hewlett-Packard HP Pavilion dv4 Notebook PC/1836, BIOS F.22 09/05/2012

[  223.805868] Call Trace:

[  223.805885]  dump_stack+0x6d/0x9a

[  223.805895]  panic+0x101/0x2e3

[  223.805903]  sysrq_handle_crash+0x15/0x20

[  223.805908]  __handle_sysrq.cold+0x48/0x107

[  223.805914]  write_sysrq_trigger+0x28/0x40

[  223.805920]  proc_reg_write+0x43/0x70

[  223.805926]  __vfs_write+0x1b/0x40

[  223.805931]  vfs_write+0xb9/0x1a0

[  223.805937]  ksys_write+0x67/0xe0

[  223.805942]  __x64_sys_write+0x1a/0x20

[  223.805950]  do_syscall_64+0x57/0x190

[  223.805958]  entry_SYSCALL_64_after_hwframe+0x44/0xa9

[  223.805965] RIP: 0033:0x7f1d2cb70057

[  223.805971] Code: 64 89 02 48 c7 c0 ff ff ff ff eb bb 0f 1f 80 00 00 00 00 f3 0f 1e fa 64 8b 04 25 18 00 00 00 85 c0 75 10 b8 01 00 00 00 0f 05 <48> 3d 00 f0 ff ff 77 51 c3 48 83 ec 28 48 89 54 24 18 48 89 74 24

[  223.805976] RSP: 002b:00007ffc65c9e978 EFLAGS: 00000246 ORIG_RAX: 0000000000000001

[  223.805982] RAX: ffffffffffffffda RBX: 0000000000000002 RCX: 00007f1d2cb70057

[  223.805986] RDX: 0000000000000002 RSI: 0000558c871b6900 RDI: 0000000000000001

[  223.805989] RBP: 0000558c871b6900 R08: 000000000000000a R09: 0000000000000001

[  223.805993] R10: 0000558c851b2017 R11: 0000000000000246 R12: 0000000000000002

[  223.805997] R13: 00007f1d2cc4b6a0 R14: 00007f1d2cc4c4a0 R15: 00007f1d2cc4b8a0


for more complex bugs, the bt command is interesting.

bt normally shows the backtrace of the task which caused the system crash, but you can select other tasks and fetch their backtraces as well.

The output for bt is:

crash> bt

PID: 4488   TASK: ffff89dec9895d00  CPU: 3   COMMAND: "bash"

 #0 [ffffaaed81ee7c68] machine_kexec at ffffffffa3c700e3

 #1 [ffffaaed81ee7cc8] __crash_kexec at ffffffffa3d58cd2

 #2 [ffffaaed81ee7d98] panic at ffffffffa3ca1962

 #3 [ffffaaed81ee7e18] sysrq_handle_crash at ffffffffa4290d15

 #4 [ffffaaed81ee7e28] __handle_sysrq.cold at ffffffffa42916a8

 #5 [ffffaaed81ee7e60] write_sysrq_trigger at ffffffffa4291548

 #6 [ffffaaed81ee7e78] proc_reg_write at ffffffffa3f715a3

 #7 [ffffaaed81ee7e98] __vfs_write at ffffffffa3edab1b

 #8 [ffffaaed81ee7ea8] vfs_write at ffffffffa3edb829

 #9 [ffffaaed81ee7ee0] ksys_write at ffffffffa3edddb7

#10 [ffffaaed81ee7f20] __x64_sys_write at ffffffffa3edde4a

#11 [ffffaaed81ee7f30] do_syscall_64 at ffffffffa3c044c7

#12 [ffffaaed81ee7f50] entry_SYSCALL_64_after_hwframe at ffffffffa480008c

    RIP: 00007f1d2cb70057  RSP: 00007ffc65c9e978  RFLAGS: 00000246

    RAX: ffffffffffffffda  RBX: 0000000000000002  RCX: 00007f1d2cb70057

    RDX: 0000000000000002  RSI: 0000558c871b6900  RDI: 0000000000000001

    RBP: 0000558c871b6900   R8: 000000000000000a   R9: 0000000000000001

    R10: 0000558c851b2017  R11: 0000000000000246  R12: 0000000000000002

    R13: 00007f1d2cc4b6a0  R14: 00007f1d2cc4c4a0  R15: 00007f1d2cc4b8a0

    ORIG_RAX: 0000000000000001  CS: 0033  SS: 002b

crash> 


kdump on ubuntu 20.04/18.04 part 1

 kdump is a tool which captures crash dumps from the memory of a running crashed system. The architecture is slightly interesting, since when the production kernel crashes, another, separate kernel is booted via kexec, into a memory space reserved by the production kernel. The freshly booted separate kernel, also known as the crash kernel, then captures the state of the crashed system, and writes it to disk.


This all works because of kexec. kexec is a fastboot tool implemented in the kernel. It allows other kernels to be booted from an already running kernel, skipping the need to go through standard BIOS routines. This, coupled with the fact that the crash kernel is loaded into reserved space allocated by the production kernel, means that memory is intact and is not overwritten by a reboot. This is how reliability and integrity of crash dumps are assured.


Once the crash dump is written to disk, or even sent over the network to a remote host, the system reboots so uptime can be restored. The crash dump can then be analysed later on.


Configuring kdump

Kernel Configuration

If we read the kdump Documentation, kdump requires some kernel features to be configured and compiled into the kernel.


They are:


CONFIG_KEXEC=y

CONFIG_CRASH_DUMP=y

CONFIG_PROC_VMCORE=y

CONFIG_DEBUG_INFO=y

CONFIG_MAGIC_SYSRQ=y

CONFIG_RELOCATABLE=y

CONFIG_PHYSICAL_START=0x1000000

CONFIG_KEXEC enables the syscall required for kexec to function, and is necessary for being able to boot into the crash kernel.


CONFIG_CRASH_DUMP and CONFIG_PROC_VMCORE enables the crashed kernel to be dumped from memory, and exported to a ELF file.


CONFIG_DEBUG_INFO builds the kernel with debugging symbols, and produces a vmlinux file which can be used for analysis of crash dumps. The production kernel runs a kernel stripped of debugging symbols for performance, so it is very important to match packages of production kernels and debug kernels.


CONFIG_MAGIC_SYSRQ is necessary to be able to use SYSRQ features, such as flushing buffers on kernel panic, and to be able to trigger crashes manually.


CONFIG_RELOCATABLE is set since our kernel is relocatable in memory, so we must also set CONFIG_PHYSICAL_START as the deterministic address in which we can place the crash kernel in memory. Now, 0x1000000 is at 16mb in physical memory, and is the default set in Cosmic Cuttlefish’s kernel.


The nice thing is, all of these features are enabled by default on Ubuntu production kernels, so we don’t need to compile our own kernel today. You can verify that these features are enabled by looking at the config files in /boot:


root@user1-HP-Pavilion-dv4-Notebook-PC:/home/user1# grep -i crash  /boot/config-5.4.0-42-generic 

CONFIG_CRASH_DUMP=y

CONFIG_CRASH_CORE=y


Installing Packages

We can install all the required kdump packages with the command: 

sudo apt install linux-crashdump     

This will install crash, kdump-tools, kexec-tools, makedumpfile and itself.



Should kexec-tools handle reboots (sysvinit only)? answer YES


Should kdump-tools be enabled by default? asnwer YES


We should probably make sure we have all the necessary kernel packages around as well, such as headers and tools, so run:

$ sudo apt install linux-image-generic linux-headers-generic linux-tools-generic   


Setting up kdump-tools

We need to tell the kernel where the crash kernel will be loaded in memory, and how much space it has. This happens by appending a crashkernel=... to the kernel command line. This has been done for us when we installed linux-crashdump, and we need to reboot the system so that the changes actually take effect. So go ahead and restart.


After restarting, we can see run kdump-config show, to see that all is well:


root@user1-HP-Pavilion-dv4-Notebook-PC:/home/user1# kdump-config show

DUMP_MODE:        kdump

USE_KDUMP:        1

KDUMP_SYSCTL:     kernel.panic_on_oops=1

KDUMP_COREDIR:    /var/crash

crashkernel addr: 0x8a000000

   /var/lib/kdump/vmlinuz: symbolic link to /boot/vmlinuz-5.4.0-42-generic

kdump initrd: 

   /var/lib/kdump/initrd.img: symbolic link to /var/lib/kdump/initrd.img-5.4.0-42-generic

current state:    ready to kdump


kexec command:

  /sbin/kexec -p --command-line="BOOT_IMAGE=/boot/vmlinuz-5.4.0-42-generic root=UUID=eb00fc0a-fab7-42a7-a272-7ba7b07dd94d ro quiet splash vt.handoff=7 reset_devices systemd.unit=kdump-tools-dump.service nr_cpus=1 irqpoll nousb ata_piix.prefer_ms_hyperv=0" --initrd=/var/lib/kdump/initrd.img /var/lib/kdump/vmlinuz



  A few interesting things to note:


Core dumps will be stored in /var/crash

The crash kernel vmlinuz is located at /var/lib/kdump/vmlinuz

The crash kernel initial filesystem is located at /var/lib/kdump/initrd.img

To see the updated kernel command line, we can run cat /proc/cmdline:


root@user1-HP-Pavilion-dv4-Notebook-PC:/home/user1# cat /proc/cmdline

BOOT_IMAGE=/boot/vmlinuz-5.4.0-42-generic root=UUID=eb00fc0a-fab7-42a7-a272-7ba7b07dd94d ro quiet splash crashkernel=512M-:192M vt.handoff=7


$ cat /proc/sys/kernel/sysrq

176

 We will have to look at /etc/sysctl.d/10-magic-sysrq.conf to see what 176 means.


 $ sudo sysctl -w kernel.sysrq=1

Right. We can trigger a system crash by passing the ‘c’ character to /proc/sysrq-trigger. This has to be done as root:


$ sudo -s

# echo c > /proc/sysrq-trigger

mysql monitor - newrelic

https://blog.newrelic.com/engineering/how-to-monitor-mysql/

MySQL is an open source relational database system that, like Linux, started its history as a personal side project. Over its 25 years of history, MySQL has gained significant traction, and today a broad range of companies, such as Sony and Uber, use it to run their multi-petabyte mission-critical databases.

In a way, MySQL has been a victim of its own success. It’s easy enough to run that developers may take it for granted and assume it doesn’t need supervision. In reality, MySQL is a complex system with a delicate balance you must monitor closely. It exposes a lot of useful metrics you can’t afford to miss because they highlight where bottlenecks are, when it’s time to upgrade, and what queries you should optimize.

Like most relational databases, MySQL organizes data using databases (also called schemas) and tables. However, MySQL has a unique modular architecture that lets you choose the best low-level storage engine for the job. MySQL exposes its inner workings in all these levels through dozens of metrics.

MySQL is also extremely flexible. You can run it as a single instance, as a primary-secondary cluster, thank to replication, or in multi-master mode. And third-party solutions like Vitess allow you to create horizontally-scaled clusters.

Key MySQL Metrics to Monitor

Let’s start by reviewing some of the most important metrics to monitor in any MySQL instance. To view all available metrics, check out our MySQL integration docs (which we’ll walk through setting up below).

Uptime

It may sound self-evident, but many teams set alerts for server downtime while forgetting to monitor the MySQL process itself. When the database is down, you want to get notified immediately.

Connections

MySQL sets a hard limit on the number of simultaneous connections. When you reach it, new connections are blocked until someone disconnects.

MySQL allows 151 connections by default. Changing the limit is simple:

SET GLOBAL max_connections = 200;

Bear in mind that each connection needs at least 3MB, so always try to keep the number of connections as small as possible.

To determine the optimum number of connections to set, monitor three metrics:

  • net.maxUsedConnections: The maximum number of connections recorded since the database started. Use this value as a reference to set max_connections.
  • net.threadsConnected: The current number of active connections.
  • net.connectionErrorsMaxConnectionsPerSecond: The number of connections failed per second due to the max_connections limit being reached. If the value is higher than zero, you need to either raise the limit, set up connection pools for your applications, or consider installing a load balancer like ProxySQL.

Network issues and buggy clients can also affect MySQL connections. Watch net.abortedClientsPerSecond to detect applications not closing connections properly. A high rate usually indicates problems in the network.

Memory usage

Databases need a lot of memory to work well, so monitoring memory is vital to keep your MySQL in top shape.

First, set up monitoring for the server to ensure it has enough RAM:

  • memoryFreeByes
  • memoryUsedBytes
  • memoryTotalByes

Then, on the MySQL side, monitor these metrics:

  • db.innodb.bufferPoolPagesTotal: The number of pages in-memory holding data. You want this number to be as high as possible to reduce disk activity and increase performance.
  • db.innodb.bufferPoolReadsPerSecond: The number of pages not found in-memory that need to be retrieved from disk. If the value is more than 5-15% of db.innodb.bufferPoolPagesTotal, the database needs more memory. In that case, check the server RAM and increase the db.innodb_buffer_pool_size setting on MySQL.
  • db.innodb.logWaitsPerSecond: If this value is consistently high, it means that the log buffer is set too low. In that case, increase innodb_log_buffer_size until the problem goes away.

Storage speed

After memory, disk I/O speed is the most crucial factor for database performance. Even if the system has enough RAM to allocate the complete database, it’ll still need disk I/O to ensure transaction consistency.

The main database workload shapes disk activity. For Online Transaction Processing (OLTP) systems (e.g., systems used for online purchase processing), the following metrics should be smooth and steady. Peaks indicate possible bottlenecks and latency for your users. On the other hand, for Online Analytical Processing (OLAP) systems (e.g., systems used for budgeting and forecasting), uneven activity is a lot more common and should be expected.

To keep an eye on workload, monitor the following:

  • db.innodb.dataReadsPerSecond: The number of reads per second.
  • db.innodb.dataWritesPerSecond: The number of writes per second.
  • db.innodb.osLogWrittenBytesPerSecond: The transaction log throughput. This value is proportional to how much the data changes over time.

Query speed

Watch these metrics to monitor query speed and capture a baseline for your database:

  • query.questionsPerSecond: The number of queries sent by clients.
  • query.queriesPerSecond: The total number of queries per second (QPS), including administrative commands and stored procedures. It measures the raw capacity of the database.
  • query.maxExecutionTimeExceededPerSecond: The number of SELECT statements timed out per second. For OLTP workloads, you never want this value to exceed zero. If you find that your queries are timing out, optimize them.

Query optimization metrics

Query optimization is where you can make the most significant impact on MySQL performance.

To identify long-running queries, activate the MySQL slow query log:

SET GLOBAL slow_query_log = 1;
SET GLOBAL slow_query_log_file = '/var/log/mysql/mysql-slow.log';

Then set a reasonable query time to capture the worst-behaving queries on a first pass:

// 3 seconds threshold
SET GLOBAL long_query_time = 3;

As performance improves, you can reduce the query time and repeat the process.

Once the feature is active, monitor query.slowQueriesPerSecond, analyze the log, and use an EXPLAIN statement to find which queries do worse. Depending on the case, you may need to rewrite them, add or modify indexes, or restructure your tables.

Here are some additional metrics to monitor while optimizing queries.

Temporary Files and Tables

MySQL creates temporary files and tables on disk for operations such as GROUP BY, ORDER BY, or UNION that don’t fit in-memory. Since these can cause excessive disk I/O, keep a close watch on these metrics:

  • db.createdTmpDiskTablesPerSecond measures tables.
  • db.createdTmpFilesPerSecond measures temporary files.

While it’s not always possible to reduce these values to zero, you can minimize temporary disk activity by adjusting sort_buffer_size and join_buffer_size, and rewriting queries.

Locks

MySQL uses table- and row-level locks to ensure data consistency. Poorly written queries and some administrative tasks can lead to long-running locks that block other clients. The main metrics for lock activity are db.tablesLocksWaitedPerSecond for tables, and db.innodb.rowLockTimeAvg and db.innodb.rowLockWaitsPerSecond for rows.

Missing indexes

MySQL uses indexes for filtering, sorting, and joining tables. When queries and table structures don’t line up, MySQL is forced to scan the whole table. This situation uses up a lot of extra memory and causes heavy disk I/O.

Monitor these metrics for details:

  • db.selectFullJoinPerSecond and db.selectFullJoinRangePerSecond indicate whether your tables need additional indexes.
  • db.innodb.bufferPoolReadAheadRndPerSecond helps detect inefficient table-level reads.

Monitoring MySQL with New Relic

Our MySQL integration uses the New Relic Infrastructure agent to collect and send performance metrics from your MySQL database to our platform.  You can see  your database server’s health and analyze metric data so that you can easily find the source of any problems

The integration is compatible with MySQL version 5.6 or higher.

In the following example, we’ll show you how to set up Infrastructure Monitoring for an  Ubuntu server running MySQL. If you have a different host OS, check the agent documentation for alternative instructions.

Note: You can also monitor MySQL as a service running in Kubernetes or ECS.

Install the agent and integration on an Ubuntu server

  1. From New Relic One, navigate to your account drop-down (in the top-right corner) and select Add more data.
  2. Select your operating system (in this case Ubuntu), and follow the prompts to get your license key and select your Ubuntu version.
  3. To deploy the Infrastructure agent and the MySQL integration, run the following commands on your server:
    • Import Infrastructure agent GPG Key.
      curl -s https://download.newrelic.com/infrastructure_agent/gpg/newrelic-infra.gpg | sudo apt-key add -
    • Add the New Relic repository (view all distributions here).
      printf "deb [arch=amd64] https://download.newrelic.com/infrastructure_agent/linux/apt bionic main" | sudo tee -a /etc/apt/sources.list.d/newrelic-infra.list
    • Install the infrastructure agent (newrelic-infra) and MySQL integration (nri-mysql).
      sudo apt-get update && sudo apt-get install -y newrelic-infra nri-mysql

Configure the MySQL integration

  1. Add a monitoring user in MySQL.
    mysql -e "CREATE USER 'newrelic'@'localhost' IDENTIFIED BY 'MONITOR_USER_PASSWORD';"
    mysql -e "GRANT REPLICATION CLIENT ON *.* TO 'newrelic'@'localhost';"
  2. Configure the MySQL integration.
    cd /etc/newrelic-infra/integrations.d
    sudo cp mysql-config.yml.sample mysql-config.yml
    sudo nano mysql-config.yml
  3. Fill in the password.hostname:
    hostname: localhost
    port: 3306
    username: newrelic
    password: MONITOR_USER_PASSWORD
  4. Set remote_monitoring to true.
  5. Capture extended_metrics and extended_innodb_metrics.
    extended_metrics: 1
    extended_innodb_metrics: 1
  6. If you have MyISAM tables, also set extended_myisam_metrics:
    extended_myisam_metrics: 1
  7. Restart the infrastructure agent to complete the setup.systemctl restart newrelic-infra

A full list of configuration options is available in our MySQL integration documentation.