20141029

mysql administration notes

MySQL server on debian administration notes .



Install on debian
debian-sys-maint user
Passwordless administration commands or SQL statements
Configuration files and MySQL system variables
mysqladmin
Using the standard client for an elementary database exploration.
Binary Backups
mysqlhotcopy
mysqldump --Logical Backups.
Master-Slave Replication.
mysqlcheck.



Now, with the debian MySQL server packet installation
# apt-get install mysql-server
you get the MySQL server version 5.5 along with its prerequisites, basic MySQL tools like the standard MySQL client and the Perl DBI, and some other stuff like mailx.
heirloom-mailx libaio1 libdbd-mysql-perl libdbi-perl libhtml-template-perl
libmysqlclient18 mysql-client-5.5 mysql-common mysql-server-5.5 mysql-server-core-5.5




The debian-sys-maint user.

The debian package adds the debian-sys-maint MySQL user that can do pretty much everything if logging in locally.
mysql> show grants for 'debian-sys-maint'@'localhost';
+----------------------------------------------------------------------------------------------------------------------------------------------------+
| Grants for debian-sys-maint@localhost                                                                                                              |
+----------------------------------------------------------------------------------------------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'debian-sys-maint'@'localhost' IDENTIFIED BY PASSWORD '*0123456789ABCDEF12346789082F1970A47EDCBA' WITH GRANT OPTION |
+----------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> select Host,Super_priv,Create_priv,Grant_priv,Drop_priv from mysql.user where user='debian-sys-maint';
+-----------+------------+-------------+------------+-----------+
| Host      | Super_priv | Create_priv | Grant_priv | Drop_priv |
+-----------+------------+-------------+------------+-----------+
| localhost | Y          | Y           | Y          | Y         |
+-----------+------------+-------------+------------+-----------+
1 row in set (0.01 sec)



The debian-sys-maint user has a "random" password stored at /etc/mysql/debian.cnf.
# ls -l /etc/mysql/debian.cnf 
-rw------- 1 root root 333 Oct 23 16:04 /etc/mysql/debian.cnf




Skip the Password Prompts.

The debian-sys-maint user is used by system scripts, but it is convenient for an administrator to use it in his commands and scripts.
# mysqladmin --defaults-file=/etc/mysql/debian.cnf create yo
# mysqladmin --defaults-file=/etc/mysql/debian.cnf drop yo
Dropping the database is potentially a very bad thing to do.
Any data stored in the database will be destroyed.

Do you really want to drop the 'yo' database [y/N] y
Database "yo" dropped


Another way to skip the password prompt when running a SQL command.
# mysql -u root -p"password" -e "command;"
As far as I know since at least version 5.1.41-3 and upwards commands like the above, do not reveal your password in the current processes snapshot (ps)
root     30510  0.0  0.1  40280  2696 pts/0    S+   07:41   0:00          \_ mysql -u root -px xxxxxx




Configuration files and MySQL system variables.

Default options are read from the following files in the given order: /etc/my.cnf /etc/mysql/my.cnf /usr/etc/my.cnf ~/.my.cnf

Within the MySQL configuration or option files we may define groups for which we want to set options. A Group name often matches a MySQL helper program name. An options group named "group" starts with [group] in the options or configuration files.

The debian debian-package puts the configuration files in /etc/mysql.

The database table and DB specific options files are stored in /var/lib/mysql

An easy way to display MySQL system variables and their values.
# mysqladmin --defaults-file=/etc/mysql/debian.cnf variables


A quick reference of the MySQL daemon options along with some MySQL system variables and their values.
# mysqld --h -v


MySQL has many logging options (look for log in the MySQL system variables).
General query log keeping is expensive and disabled by default. It may may be enabled permanently in the configuration file /etc/mysql/my.cnf
#general_log_file        = /var/log/mysql/mysql.log
#general_log             = 1


As of version 5.1, general log keeping may be enabled or disabled at runtime.
# mysql -u root -p"root_paswd"
mysql> show variables like 'general%';
+------------------+-------------------------------+
| Variable_name    | Value                         |
+------------------+-------------------------------+
| general_log      | OFF                           |
| general_log_file | /var/lib/mysql/anaxagoras.log |
+------------------+-------------------------------+
2 rows in set (0.00 sec)
mysql> SET GLOBAL general_log=1;
Query OK, 0 rows affected (0.00 sec)
mysql> show variables like 'general%';
+------------------+-------------------------------+
| Variable_name    | Value                         |
+------------------+-------------------------------+
| general_log      | ON                            |
| general_log_file | /var/lib/mysql/anaxagoras.log |
+------------------+-------------------------------+
2 rows in set (0.00 sec)
mysql> SET GLOBAL general_log=0;
Query OK, 0 rows affected (0.08 sec)
mysql> quit
Bye
# cat /var/lib/mysql/anaxagoras.log 
/usr/sbin/mysqld, Version: 5.5.40-0+wheezy1 ((Debian)). started with:
Tcp port: 3306  Unix socket: /var/run/mysqld/mysqld.sock
Time                 Id Command    Argument
141026 13:21:22    37 Query show variables like 'general%'
141026 13:24:35    37 Query SET GLOBAL general_log=0




mysqladmin and a few usage examples.
mysqladmin is an agent-client suitable for administering MySQL servers.


Check whether the server is alive.
# mysqladmin --defaults-file=/etc/mysql/debian.cnf ping
mysqld is alive



See status.
# mysqladmin --defaults-file=/etc/mysql/debian.cnf status
Uptime: 10189  Threads: 2  Questions: 172  Slow queries: 0  Opens: 171  Flush tables: 1  Open tables: 41  Queries per second avg: 0.016


To view an extended status try.
# mysqladmin --defaults-file=/etc/mysql/debian.cnf extended-status |less


List processes.
# mysqladmin --defaults-file=/etc/mysql/debian.cnf processlist
+----+------------------+-----------+----+---------+------+-------+------------------+
| Id | User             | Host      | db | Command | Time | State | Info             |
+----+------------------+-----------+----+---------+------+-------+------------------+
| 40 | root             | localhost |    | Sleep   | 1940 |       |                  |
| 47 | debian-sys-maint | localhost |    | Query   | 0    |       | show processlist |
+----+------------------+-----------+----+---------+------+-------+------------------+


Kill process with ID 40 and show processes (proc).
# mysqladmin --defaults-file=/etc/mysql/debian.cnf kill 40 proc
+----+------------------+-----------+----+---------+------+-------+------------------+
| Id | User             | Host      | db | Command | Time | State | Info             |
+----+------------------+-----------+----+---------+------+-------+------------------+
| 46 | debian-sys-maint | localhost |    | Query   | 0    |       | show processlist |
+----+------------------+-----------+----+---------+------+-------+------------------+


Reload the MySQL server mysql database grant tables.
# mysqladmin --defaults-file=/etc/mysql/debian.cnf reload
or
# mysqladmin -u root -p"root_passwd" flush-privileges


Clear MySQL status variables in a MySQL instance running on host 192.0.2.10
# mysqladmin -h 192.0.2.10 -u root -p"0210_root_passwsd" flush-status


Shutdown MySQL server.
# mysqladmin --defaults-file=/etc/mysql/debian.cnf ping
mysqld is alive
# mysqladmin --defaults-file=/etc/mysql/debian.cnf shutdown
# mysqladmin --defaults-file=/etc/mysql/debian.cnf ping 2>/dev/null
# echo $?
1


Start MySQL server.
# /etc/init.d/mysql start
[ ok ] Starting MySQL database server: mysqld ..
[info] Checking for tables which need an upgrade, are corrupt or were 
not closed cleanly..




Use the standard client in an elementary database exploration.

Log in to MySQL as the root using the standard mysql client.
# mysql -u root -p"root_passwd"


Show databases.
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| foodb              |
| mysql              |
| performance_schema |
+--------------------+
4 rows in set (0.00 sec)
The mysql , information_schema and performance_schema databases come with the MySQL server and they are used by the MySQL server in its operation. The mysql database holds information about users,servers,plugins,timezone,etc and the users may write to it (eg: this is how you add a MySQL user ). The information_schema (read-only to the users) stores information about all the other databases that MySQL maintains. The performance_schema database is used by the MySQL system to provide low level execution monitoring.

Use the foodb database.
mysql> use foodb;


Show all tables in the foodb database.
mysql> show tables;
+------------------+
| Tables_in_foodb  |
+------------------+
| exits            |
+------------------+
1 row in set (0.00 sec)


Describe the schema of the 'exits' table in the 'foodb' DB.
mysql> describe exits;
+------------+------------------+------+-----+---------+-------+
| Field      | Type             | Null | Key | Default | Extra |
+------------+------------------+------+-----+---------+-------+
| su         | int(10) unsigned | NO   | PRI | NULL    |       |
| first_test | datetime         | YES  |     | NULL    |       |
| last_test  | datetime         | YES  |     | NULL    |       |
+------------+------------------+------+-----+---------+-------+
3 rows in set (0.00 sec)


Find out the number of rows in the table exits.
mysql> SELECT COUNT(*) FROM exits;
+----------+
| COUNT(*) |
+----------+
|   260472 |
+----------+
1 row in set (0.00 sec)



exit
mysql> quit
Bye
#




Binary Database Backup.
If a database contains only MyISAM tables (*.frm,*.MYD,or *.MYI) and the db.opt file you may simply copy it.

Lock tables before copying.
# mysql --defaults-file=/etc/mysql/debian.cnf -e "LOCK TABLES foodb.exits READ;"


The database tables are in /usr/lib/mysql. To copy.
# cp -rp /var/lib/mysql/foodb /bak/mysql/foodb


Unlock tables after copying.
# mysql --defaults-file=/etc/mysql/debian.cnf -e "UNLOCK TABLES;"


To restore the foodb to the same or another MySQL server
copy it to /var/lib/mysql.
# cp -rp  /bak/mysql/foodb /var/lib/mysql/foodb
If you are copying to another MySQL server and you are missing or you do not want to mess with the old /var/lib/mysql/mysql you may want to create a user for the foodb.
mysql> grant all on foodb.* to foodbuser;
mysql> set password for foodbuser = password('foodbuser_passwd');


When I did copy the foodb DB directory to another MySQL server everything worked fine, the origin MySQL server was version 5.1.41-3, and the destination MySQL was version 5.5.40-0.



mysqlhotcopy

A more robust way for doing binary backups of MyISAM tables is mysqlhotcopy --a Perl script that comes with the standard MySQL distribution.
Eg: to copy foodb to another MySQL server using mysqlhotcopy.
dest# mkdir /var/lib/mysql/foodb
orig#mysqlhotcopy --method='scp' --user=root --password=mysqlrootpasswd foodb root@192.0.2.26:/var/lib/mysql


mysqldump --Logical Backups

Good for all storage engines. Logical Backups are text files that contain SQL statements used to restore schemata and data.

Dump backup of foodb in a file.
orig# mysqldump -u root -p"root_passwd" foodb > foodb.sql


Restore the foodb to another MySQL server.
dest# mysqladmin --defaults-file=/etc/mysql/debian.cnf create foodb
dest# mysql --defaults-file=/etc/mysql/debian.cnf foodb < foodb.sql




Master-Slave Replication

Prepare Master ( anaxagoras ) and Slave ( democritus ) MySQL servers.
Enable binary logging, set a server ID number and listen on all interfaces.

Master --host anaxagoras
add in /etc/mysql/my.cnf -configuration group mysqld
[mysqld]
server-id               = 11
log_bin                 = /var/log/mysql/mysql-bin.log
bind-address            = 0.0.0.0
innodb_flush_log_at_trx_commit=1
sync_binlog             = 1  
binlog_do_db            = foodb


Restart MySQL
anaxagoras# service mysql restart


Punch Firewall holes.

Slave --host democritus
Add in /etc/mysql/my.cnf -configuration group mysqld
[mysqld]
server-id               = 12
log_bin                 = /var/log/mysql/mysql-bin.log
binlog_do_db            = foodb

Restart MySQL
democritus# service mysql restart 


Create a user for replication on the master.
anaxagoras# mysql -u root -p"root_passwd"
mysql> CREATE USER 'repuser'@'192.0.2.0/255.255.255.128';
mysql> SET PASSWORD FOR 'repuser'@'192.0.2.0/255.255.255.128' = password('repuser_password');
mysql> GRANT REPLICATION SLAVE ON *.* TO 'repuser'@'192.0.2.0/255.255.255.128';
mysql> FLUSH PRIVILEGES;


Obtain master's binary log coordinates.
mysql> USE foodb
mysql> FLUSH TABLES WITH READ LOCK;
Query OK, 0 rows affected (0.17 sec)

mysql> SHOW MASTER STATUS;
+------------------+----------+--------------+------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000003 |      107 | foodb        |                  |
+------------------+----------+--------------+------------------+
1 row in set (0.00 sec)



Copy the database with mysqldump , mysqlhotcopy , a cold copy, or something else.

Cold Super Copy.
Copy raw data files to the slave MySQL.
If you are using any InnoDB tables, shutdown MySQL
anaxagoras# mysqladmin --defaults-file=/etc/mysql/debian.cnf shutdown 
anaxagoras# rsync -avz -e ssh /var/lib/mysql/ root@democritus:/var/lib/mysql
anaxagoras# scp /etc/mysql/debian.cnf root@democritus:/etc/mysql/


Remove master' s lock.
mysql> UNLOCK TABLES;


Configure the slave MySQL server and start the replication.
democritus# mysql -u root -p"root_passwd"
mysql> CHANGE MASTER TO MASTER_HOST='anaxagoras', MASTER_USER='repuser', MASTER_PASSWORD='repuser_password', MASTER_LOG_FILE='mysql-bin.000003', MASTER_LOG_POS=107;
mysql> START SLAVE;



See the status in the slave MySQL server.
mysql> SHOW SLAVE STATUS\G




mysqlcheck --A MySQL tables maintance program.

Check all tables in all databases.
# mysqlcheck --defaults-file=/etc/mysql/debian.cnf -A


Analyze tables in database foodb.
# mysqlcheck --defaults-file=/etc/mysql/debian.cnf --analyze foodb


Optimize tables in database foodb.
# mysqlcheck --defaults-file=/etc/mysql/debian.cnf -0 foodb


Repair tables in foodb. Make backups of the tables before 'repairing' them.
# mysqlcheck --defaults-file=/etc/mysql/debian.cnf --debug-info --auto-repair foodb




MySQL administration notes



20141021

DELETE tun interfaces

A quick note on killing a bug in a previous recipe and deleting protocol 41 tunnel interfaces in linux.

datun is an interface used as one of the edges in a 6in4 tunnel set with
ip tunnel add datun mode sit remote 192.0.2.49 local 198.51.100.50 ttl 64 
ip link set datun up


seen as
# ifconfig datun
datun Link encap:IPv6-in-IPv4 


and taken down with
# ip link set datun down
at the 6in4 tunnels to the IPv6 Internet how-to, even in places we needed to delete the tunnel instead of putting it down, causing all kinds of errors and confusion.

To delete a tunnel interface.
ip tunnel del datun


Instead of "restarting" the 6in4 tunnel it may be better to destroy it and set it again.
# ip tunnel del datun
# /etc/network/if-up.d/ipv6-tunnel.sh




delete tun interface

20141020

tripwire notes

Yet another tripwire ( as in the open source file integrity checker for Unix Systems ) how-to for debian , like tripwire ... but, hopefully, easier to follow.

Assuming you trust your repositories, your distribution, etc
# apt-get install tripwire
and then click the no, no, and OK buttons.

Ideally, the tripwire binaries and the tripwire database are stored in a read only medium that can be mounted as read-write for updates. I would use an SD card or some other medium that I can set "mechanically" to read-only. Some administrators put the binaries and the DB in an NFS.I think that putting the binaries and the DB in an NFS would increase the attack surface. If you are not in the mood or do not have the resources to take the extra steps to secure further the integrity of the tripwire binaries and the tripwire DB at least save copies of the files and their cryptographically secure checksums in other hosts.

In debian the tripwire binaries are statically linked and located in /usr/sbin and the DB is located in /var/lib/tripwire.
# sha256sum /usr/sbin/tripwire |tee ~/twsums
0e4791bb58dfc4095dba902621b72111d61bf1838d77aff4ae00d3c7432d5739  /usr/sbin/tripwire
# sha256sum /usr/sbin/tw* |tee -a ~/twsums
bc01ac66aa421d2e5324983150bea573b2e2d3ee004293501b0dcc4ce1560898  /usr/sbin/twadmin
e1b097eaf28f3ec54114cba7cc82a1ab4122a9fb82590422d9820711c884e5e9  /usr/sbin/twprint
# sha256sum /usr/sbin/siggen |tee -a ~/twsums 
e5e72b264f9b4fa86aa88e0f893b6031457e30b510f28bcb31ea1296b38566bd  /usr/sbin/siggen


Tripwire uses $HOSTNAME a lot in the configuration and policy files. Make sure that you are happy with hostname, if not change the hostname before continuing the tripwire configuration.

Create a site key.
# cd /etc/tripwire/
# twadmin --generate-keys --site-keyfile site.key
# chmod 400 site.key
The site key is used to secure the integrity of the tripwire configuration files.

Create a local key.
# twadmin --generate-keys --local-keyfile `hostname`-local.key
# chmod 400 *cal.key
The local key is used to protect the integrity of the local tripwire database.

Create and sign tw.cfg --the tripwire configuration file.
# stor twcfg.txt
# vi twcfg.txt 
# twadmin --create-cfgfile --cfgfile tw.cfg --site-keyfile site.key twcfg.txt
Please enter your site passphrase: 
Wrote configuration file: /etc/tripwire/tw.cfg


Create and sign tw.pol --the tripwire policy file.
# stor twpol.txt
# vi twpol.txt
# twadmin --create-polfile --cfgfile tw.cfg --site-keyfile site.key twpol.txt
Please enter your site passphrase: 
Wrote policy file: /etc/tripwire/tw.pol


Make the policy and configuration files readable and writable only by the root user.
# chmod 600 *txt
# chmod 600 *cfg
# chmod 600 *pol


Initialize the tripwire database.
# tripwire --init
Please enter your local passphrase: 
Parsing policy file: /etc/tripwire/tw.pol
Generating the database...
*** Processing Unix File System ***
# ...
Wrote database file: /var/lib/tripwire/anaxagoras.twd
The database was successfully generated.


Test that tripwire can send email.
# tripwire --test --email example@example.net


Check integrity and produce report.
# tripwire --check


View report.
# twprint -m r --twrfile /var/lib/tripwire/report/hostname-latest.twr |less


It is highly unlikable that you are using all the files in the "Root config files" rulename in the debian default twpol.txt. Also you may want to adjust the "Devices & Kernel information" rulename since /proc (meaning recursive /proc/*) may be too much to track in normal servers.

Adjust the tripwire policy and initialize a new tripwire database.
# stor twpol.txt
# vi twpol.txt
# twadmin -m P -S site.key twpol.txt 
# tripwire --init


Check for integrity, create a report and OK changes if any.
Once the editor opens look for [x] and delete the x if you are not OK with that change.
# tripwire --check --interactive
Integrity check complete.
Please enter your local passphrase: 
Wrote database file: /var/lib/tripwire/anaxagoras.twd


You may enter an `interactive` mode from a report as well. eg:
# tripwire --update --twrfile /var/lib/tripwire/report/hostname-date-time.twr
and again look for [x] and delete the x if you are not OK with that change.

Email alerts.
To email an alert we need to add an emailto definition to at least one rulename.
So we need to update the tripwire policy. eg:
#
# Critical Libraries
#
(
  rulename = "Root file-system libraries",
  severity = $(SIG_HI),
  emailto = root,
  emailto = systembot@ares.ipduh.rox
)
{
        /lib                    -> $(SEC_BIN) ;
}

If /lib is changed an alert will be sent to root and systembot@ares.ipduh.rox.


Check integrity, produce report and email alerts.
# tripwire --check --email-report


The debian package sets a cronjob that creates reports and emails alerts daily.
#!/bin/sh -e

tripwire=/usr/sbin/tripwire

[ -x $tripwire ] || exit 0

umask 027

$tripwire --check --quiet --email-report


View the tripwire database.
# twprint -m d --print-dbfile |less


View tripwire information for a file eg:/var/test
# twprint -m d --print-dbfile /lib/test


The system used in this how-to.
ii  tripwire                           2.4.2.2-2                     amd64        file and directory integrity checker
# cat /etc/issue /etc/debian_version 
Debian GNU/Linux 7 \n \l

7.6





Links:
The Design and Implementation of Tripwire: A File System Integrity Checker





Tripwire how-to

20141018

apache disable SSLv3

Notes on disabling SSLv3 in apache.

Test if SSLv3 is available.
$ openssl s_client -connect ipduh.com:443 -ssl3


In Debian SSLv2 is disabled by default but SSLv3 is available.

# grep SSLProtocol /etc/apache2/mods-available/ssl.conf
SSLProtocol all -SSLv2


To disable SSLv3 add '-SSLv3' in /etc/apache2/mods-available/ssl.conf
# vi /etc/apache2/mods-available/ssl.conf


If you are using SSL Virtual Hosts you may need to add
SSLProtocol All -SSLv2 -SSLv3
in each VirtualHost definition.

Restart Apache
# /etc/init.d/apache2 restart


Test again if SSLv3 is disabled.
$ openssl s_client -connect ipduh.com:443 -ssl3
CONNECTED(00000003)
140330958718632:error:14094410:SSL routines:SSL3_READ_BYTES:sslv3 alert handshake failure:s3_pkt.c:1258:SSL alert number 40
140330958718632:error:1409E0E5:SSL routines:SSL3_WRITE_BYTES:ssl handshake failure:s3_pkt.c:596:




apache disable SSLv3

20141017

libguestfs notes

Libguestfs basics.

Install.
# apt-get install libguestfs-tools 
# apt-get install guestfish



guestfish

The libguestfs Filesystem Interactive SHell.

An example: explore, read and write to disk image file within the libguestfs VM.
# guestfish --rw -a /home/vm/anaxagoras.qcow2
> run
 100% ⟦▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓⟧ 00:00
> list-filesystems
/dev/vda1: ext4
/dev/vda2: unknown
/dev/vda5: swap
> mount /dev/vda1 /


Add a file to the disk image file system.
> touch /etc/guestfish_play
> edit /etc/guestfish_play
> quit
#



virt-cat

Display files in a virtual machine.

eg:
# virsh list
 Id    Name                           State
----------------------------------------------------
 9     anaxagoras                     running

# virt-cat anaxagoras /etc/issue
Debian GNU/Linux 7 \n \l
# virt-cat anaxagoras /etc/hostname
anaxagoras




guestmount

Mount a guest filesystem on the host using FUSE and libguestfs

Install
# apt-get install guestmount


Mount rw a filesystem contained in a disk image file.
# mkdir /mnt/anax
# guestmount -a /home/vm/anaxagoras.qcow2 -m /dev/vda1 --rw /mnt/anax/


# cat /mnt/anax/etc/guestfish_play
hi
# echo "hi kosme" > /mnt/anax/etc/guestfish_play
# mv /mnt/anax/etc/guestfish_play /mnt/anax/etc/guestmount_play
# umount /mnt/anax


guestmount is and looks traditionally-scriptable. However, guestfish is as or more scriptable. Also, libguestfs has cute C , Perl and Python APIs.


virt-df

List free space on virtual filesystems.
# virt-df anaxagoras
Filesystem                           1K-blocks       Used  Available  Use%
anaxagoras:/dev/sda1                  19751804     840608   17907832    5%



virt-filesystems

List filesystems, partitions, block devices, LVM in a virtual machine or a disk image file.

eg:
# virt-filesystems --long --parts --blkdevs -a /home/vm/anaxagoras.qcow2 -h
Name       Type       MBR  Size  Parent
/dev/sda1  partition  83   19G   /dev/sda
/dev/sda2  partition  05   1.0K  /dev/sda
/dev/sda5  partition  82   880M  /dev/sda
/dev/sda   device     -    20G   -



or

# virt-filesystems --long -h --all -a anaxagoras.qcow2 
Name       Type        VFS      Label  MBR  Size  Parent
/dev/sda1  filesystem  ext4     -      -    19G   -
/dev/sda2  filesystem  unknown  -      -    1.0K  -
/dev/sda5  filesystem  swap     -      -    880M  -
/dev/sda1  partition   -        -      83   19G   /dev/sda
/dev/sda2  partition   -        -      05   1.0K  /dev/sda
/dev/sda5  partition   -        -      82   880M  /dev/sda
/dev/sda   device      -        -      -    20G   -



virt-list-filesystems

List filesystems in a virtual machine or disk image.

eg:
# virt-list-filesystems anaxagoras.qcow2 
/dev/sda1
# virt-list-filesystems anaxagoras
/dev/sda1






virt-resize

Resize a virtual disk image file.

Eg: Expand the 20GB anaxagoras qcow2 disk image file to a 30GB qcow2 disk image file.
# truncate -r anaxagoras.qcow2 anaxagoras30G.qcow2
# truncate -s +10G anaxagoras30G.qcow2
# virt-resize --expand /dev/sda1 anaxagoras.qcow2 anaxagoras30G.qcow2 
Examining anaxagoras.qcow2 ...
**********

Summary of changes:

/dev/sda1: This partition will be resized from 19.1G to 29.1G.  The 
    filesystem ext4 on /dev/sda1 will be expanded using the 'resize2fs' 
    method.

/dev/sda2: This partition will be left alone.

**********
Setting up initial partition table on anaxagoras30G.qcow2 ...
Copying /dev/sda1 ...
 100% ⟦▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓⟧ 00:00
Copying /dev/sda2 ...
 100% ⟦▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓⟧ 00:00
Expanding /dev/sda1 using the 'resize2fs' method ...

Resize operation completed with no errors.  Before deleting the old 
disk, carefully check that the resized disk boots and works correctly.

Test resized image.
# cd /etc/libvirt/qemu/
# stor anaxagoras.xml
# virsh
virsh # edit anaxagoras
virsh # define anaxagoras.xml
virsh # start anaxagoras
virsh # quit
# ssh anaxagoras
root@anaxagoras:~# df -h
Filesystem                                              Size  Used Avail Use% Mounted on
rootfs                                                   29G  822M   27G   3% /
udev                                                     10M     0   10M   0% /dev
tmpfs                                                   202M  172K  202M   1% /run
/dev/disk/by-uuid/8ca4bd34-120c-45ff-bd0b-86d8de552d10   29G  822M   27G   3% /
tmpfs                                                   5.0M     0  5.0M   0% /run/lock
tmpfs                                                   579M     0  579M   0% /run/shm


More virt-.* tools.
virt-alignment-scan    virt-filesystems       virt-ls                virt-tar-in
virt-cat               virt-format            virt-make-fs           virt-tar-out
virt-clone             virt-host-validate     virt-pki-validate      virt-viewer
virt-convert           virt-image             virt-rescue            virt-win-reg
virt-copy-in           virt-inspector         virt-resize            virt-xml-validate
virt-copy-out          virt-install           virt-sparsify          
virt-df                virt-list-filesystems  virt-sysprep           
virt-edit              virt-list-partitions   virt-tar               


The system used.
# cat /etc/debian_version /etc/issue
7.6
Debian GNU/Linux 7 \n \l





libguestfs basics

20141014

mount qcow disk image files

Notes on mounting qcow disk image files.
Use this method to mount qcow2 disk image files you trust.

Load the network block device -- nbd -- module with partition support.
# modprobe nbd max_part=8


See - list nbd devices.
# ls /dev/nbd*
/dev/nbd0  /dev/nbd10  /dev/nbd12  /dev/nbd14  /dev/nbd2  /dev/nbd4  /dev/nbd6 /dev/nbd8
/dev/nbd1  /dev/nbd11  /dev/nbd13  /dev/nbd15  /dev/nbd3  /dev/nbd5  /dev/nbd7 /dev/nbd9


Make sure that the qcow2 disk image is not used by a virtual machine.

Connect a qcow2 disk image to the Qemu Disk Block Device Server.
# qemu-nbd -c /dev/nbd0 /home/vm/anaxagoras.qcow2


List nbd0* devices
# ls /dev/nbd0*
/dev/nbd0  /dev/nbd0p1 /dev/nbd0p2  /dev/nbd0p5


Mount partitions.
# mkdir /mnt/imgs
# mount /dev/nbd0p1 /mnt/imgs/


Check mounted partition.
# ls /mnt/imgs/
bin   dev  home        lib    lost+found  mnt  proc  run   selinux  sys  usr  vmlinuz
boot  etc  initrd.img  lib64  media   opt  root  sbin  srv     tmp  var


Unmount and Clean up.
# umount /dev/nbd0p1
# mount |grep nbd
#


Disconnect from the Qemu Disk Block Device Server.
# qemu-nbd -d /dev/nbd0
# ls /dev/nbd0*
/dev/nbd0


Unload nbd.
# modprobe -r nbd


The system used.
# cat /etc/debian_version /etc/issue
7.6
Debian GNU/Linux 7 \n \l

# uname -r
3.2.0-4-amd64




Mount qcow2 files in the host



20141013

debian on debian KVM II

An attempt to simplify an older debian on debian KVM how-to.

The system.
# cat /etc/debian_version /etc/issue
7.6
Debian GNU/Linux 7 \n \l

# uname -r
3.2.0-4-amd64
# grep "model\ name" /proc/cpuinfo -m1
model name : Intel(R) Core(TM) i5-4590 CPU @ 3.30GHz
# egrep "vmx|svm" /proc/cpuinfo -c
4


Install qemu-kvm, libvirt-bin and virtinst
# apt-get update
# apt-get install qemu-kvm libvirt-bin virtinst


Create a bridge (containing) to the host's physical interface

Create a debian guest that uses a virtual interface attached to a bridge interface named b0.
# mkdir /home/vm
# virt-install --connect qemu:///system -n anaxagoras -r 2048 -vcpus=1 --disk path=/home/vm/anaxagoras.qcow2,size=20 -c /insigdato/OS.iso/debian-7.6.0-amd64-netinst.iso --vnc --noautoconsole --os-type linux --description anaxagoras --network=bridge:b0 --hvm


To console into the new KVM guest from another host
( assuming you are working on a remote host ).

Find out where the KVM guest VNC console socket is in the KVM host.
# netstat -putan|grep kvm
tcp        0      0 127.0.0.1:5900          0.0.0.0:*               LISTEN      7499/kvm        



Set up SSH socket forwarding in another host
$ ssh -lroot -L 5900:localhost:5900 192.0.2.29
where 192.0.2.29 is the KVM_host IP address.

and console into the forwarded socket.
$ vncviewer localhost
5900 is the default port. For ports above 5900 use port_number-5900 to find out the vncviewer `port`.



Install.





I don 't like vnet0, vnet1 etc and prefer better names for the virtual interfaces attached to the bridge b0. To give a more descriptive name to the virtual interface and possibly circumvent a few issues I had in previous versions of virtinst and libvirt.
# virsh
virsh # edit anaxagoras
add
<target dev='anaxagoras'/>
in <interface ...     --Naming, the second toughest problem in CS :)

Set the KVM guest to autostart.
virsh # autostart anaxagoras
Domain anaxagoras marked as autostarted


and start it.
virsh # start anaxagoras
Domain anaxagoras started


List running guests.
virsh # list 
 Id    Name                           State
----------------------------------------------------
 2     anaxagoras                     running

virsh # exit



Inspect the ethernet bridge.
# brctl show
bridge name bridge id         STP enabled interfaces
b0          8000.40167e6d6745 yes         anaxagoras
                                          eth0










bridged KVM guest how-to



20141012

bridging for kvm

A basic layer 2 bridging how-to for virtualization like KVM in debian.

Many times, in KVM hosts we need to bridge the host's physical network interface with the virtual network interfaces used by the KVM guests.

Install the bridge utilities
# apt-get install bridge-utils


List network interfaces
# ip a|grep ":\ "
1: lo:  mtu 16436 qdisc noqueue state UNKNOWN 
2: eth0:  mtu 1500 qdisc pfifo_fast state UP qlen 1000


Inspect the ethernet bridge(s)
# brctl show
bridge name bridge id  STP enabled interfaces
# 
None yet.

Create a bridge instance that you can access from an interface named b0.
# brctl addbr b0


Show bridge
# brctl show
bridge name bridge id  STP enabled interfaces
b0  8000.000000000000 no  


You may add the physical interface(s) to the bridge.
# brctl addif b0 eth0
However, do not try it if you are working on a remote host.
See below how to adjust the interfaces file instead.

Delete b0
# brctl delbr b0


Adjust /etc/network/interfaces to create a "persistent" bridge and restart networking.
# vi /etc/network/interfaces
# /etc/init.d/networking restart


An example /etc/network/interfaces file where the host has the IP address 192.0.2.29/25 and the interface to the bridge is called b0.
auto lo
iface lo inet loopback


auto eth0
iface eth0 inet manual

auto b0
iface b0 inet static
 address 192.0.2.29
 netmask 255.255.255.128
 network 192.0.2.0
 broadcast 192.0.2.127
 gateway 192.0.2.10
 dns-nameservers 192.0.2.4
 dns-search ipduh.rocks
        bridge_ports eth0
        bridge_stp on           #spanning tree 
        bridge_waitport 0       #no delay before a port becomes available
        bridge_fd 0             #no forwarding delay
        bridge_maxwait 0



Inspect bridge.
# brctl show
bridge name bridge id         STP enabled interfaces
b0          8000.40167e6d6745 yes         eth0


List network interfaces.
# ip a|grep ":\ "
1: lo:  mtu 16436 qdisc noqueue state UNKNOWN 
2: eth0:  mtu 1500 qdisc pfifo_fast master b0 state UP qlen 1000
4: b0:  mtu 1500 qdisc noqueue state UP 


Add a KVM host (anaxagoras) and inspect the bridge.
# brctl show
bridge name bridge id         STP enabled interfaces
b0          8000.40167e6d6745 yes         anaxagoras
                                          eth0



The system used.
# cat /etc/issue /etc/debian_version 
Debian GNU/Linux 7 \n \l

7.6
# uname -r
3.2.0-4-amd64







L2 bridging for KVM

20141009

directadmin mysql open files limit

directadmin mysql open_files_limit notes

The directadmin `root` mysql password is called da_admin and you may find its password at
# ls -l /usr/local/directadmin/conf/mysql.conf
-r-------- 1 diradmin diradmin 30 Nov  5  2013 /usr/local/directadmin/conf/mysql.conf
# cat /usr/local/directadmin/conf/mysql.conf


Log in to the mysql server
# mysql -u da_admin -p 
Enter password:


Find out current open files limit
mysql> show variables like 'open%';
+------------------+-------+
| Variable_name    | Value |
+------------------+-------+
| open_files_limit | 1024  |
+------------------+-------+
1 row in set (0.00 sec)

mysql> exit;
Bye


Set limit to 10240
# echo "open_files_limit = 10240" >> /etc/my.cnf


Restart the mysql daemon
# /etc/init.d/mysqld restart


Check new open_files_limit
# mysql -u da_admin -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 7
Server version: 5.5.9 MySQL Community Server (GPL)

Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> show variables like 'open%';
+------------------+-------+
| Variable_name    | Value |
+------------------+-------+
| open_files_limit | 10240 |
+------------------+-------+
1 row in set (0.00 sec)

mysql> exit
Bye
# 




directadmin mysql open_files_limit