MySQL multi-master replication

http://scale-out-blog.blogspot.com/2012/04/if-you-must-deploy-multi-master.html

Multi-master replication means that applications update the same tables on different masters, and the changes replicate automatically between those masters.  Remote sites mean that the masters are separated by a wide area network (WAN), which implies high average network latency of 100ms or more.  WAN network latency is also characterized by a long tail, ranging from seconds due to congestion to hours or even days if a ship runs over the wrong undersea cable.


1. Use the Right Replication Technology and Configure It Properly

The best overall tool for MySQL multi-master replication between sites is Tungsten.  The main reason for this assertion is that Tungsten uses a flexible, asynchronous, point-to-point, master/slave replication model that handles a wide variety of topologies such as star replication or all-to-all.  Even so, you have to configure Tungsten properly.  The following topology is currently my favorite:

  • All-to-all topology.  Each master replicates directly to every other master.  This handles prolonged network outages or replication failures well, because one or more masters can drop out without breaking  replication between the remaining masters or requiring reconfiguration.  When the broken master(s) return, replication just resumes on all sides.  All-to-all does not work well if you have a large number of masters.  
  • Updates are not logged on slaves.  This keeps master binlogs simple, which is helpful for debugging, and eliminates the possibility of loops.  It also requires some extra configuration if the masters have their own slaves, as would be the case in a Tungsten Enterprise cluster. 
There are many ways to set up multi-master replication replication, and the right choice varies according to the number of masters, whether you have local clustering, or other considerations.  Giuseppe Maxia has described many topologies, for example here, and the Tungsten Cookbook has even more details.

One approach you should approach with special caution is MySQL circular replication.  In topologies of three or more nodes, circular replication results in broken systems if one of the masters fails.  Also, you should be wary of any kind of synchronous multi-master replication across sites that are separated by more than 50 kilometers (i.e. 1-2ms latency).  Synchronous replication makes a siren-like promise of consistency but the price you pay is slow performance under normal conditions and broken replication when WAN links go down.

2. Use Row-Based Replication to Avoid Data Drift

Replication depends on deterministic updates--a transaction that changes 10 rows on the original master should change exactly the same rows when it executes against a replica.  Unfortunately many SQL statements that are deterministic in master/slave replication are non-deterministic in multi-master topologies.  Consider the following example, which gives a 10% raise to employees in department #35.

   UPDATE emp SET salary = salary * 1.1 WHERE dep_id = 35;

If all masters add employees, then the number of employees who actually get the raise will vary depending on whether such additions have replicated to all masters.  Your servers will very likely become inconsistent with statement replication.  The fix is to enable row-based replication using binlog-format=row in my.cnf.  Row replication transfers the exact row updates from each master to the others and eliminates ambiguity.

3. Prevent Key Collisions on INSERTs

For applications that use auto-increment keys, MySQL offers a useful trick to ensure that such keys do not  collide between masters using the auto-increment-increment and auto-increment-offset parameters in my.cnf.  The following example ensures that auto-increment keys start at 1 and increment by 4 to give values like 1, 5, 9, etc. on this server.

server-id=1
auto-increment-offset = 1

auto-increment-increment = 4
This works so long as your applications use auto-increment keys faithfully.  However, any table that either does not have a primary key or where the key is not an auto-increment field is suspect.  You need to hunt them down and ensure the application generates a proper key that does not collide across masters, for example using UUIDs or by putting the server ID into the key.   Here is a query on the MySQL information schema to help locate tables that do not have an auto-increment primary key. 
SELECT t.table_schema, t.table_name 
  FROM information_schema.tables t 
    WHERE NOT EXISTS 
      (SELECT * FROM information_schema.columns c
       WHERE t.table_schema = c.table_schema  
         AND t.table_name = c.table_name
         AND c.column_key = 'PRI'
         AND c.extra = 'auto_increment')

4. Beware of Semantic Conflicts in Applications

Neither Tungsten nor MySQL native replication can resolve conflicts, though we are starting to design this capability for Tungsten.  You need to avoid them in your applications.  Here are a few tips as you go about this.
First, avoid obvious conflicts.  These include inserting data with the same keys on different masters (described above), updating rows in two places at once, or deleting rows that are updated elsewhere.  Any of these can cause errors that will break replication or cause your masters to become out of sync.  The good news is that many of these problems are not hard to detect and eliminate using properly formatted transactions.  The bad news is that these are the easy conflicts.  There are others that are much harder to address.  
For example, accounting systems need to generate unbroken sequences of numbers for invoices.  A common approach is to use a table that holds the next invoice number and increment it in the same transaction that creates a new invoice.  Another accounting example is reports that need to read the value of accounts consistently, for example at monthly close.  Neither example works off-the-shelf in a multi-master system with asynchronous replication, as they both require some form of synchronization to ensure global consistency across masters.  These and other such cases may force substantial application changes.  Some applications simply do not work with multi-master topologies for this reason. 

5. Remove Triggers or Make Them Harmless
Triggers are a bane of replication.  They conflict with row replication if they run by accident on the slave.  They can also create strange conflicts due to weird behavior/bugs (like this) or other problems like needing definer accounts present.  MySQL native replication turns triggers off on slaves when using row replication, which is a very nice feature that prevents a lot of problems.  
Tungsten on the other hand cannot suppress slave-side triggers.  You must instead alter each trigger to add an IF statement that prevents the trigger from running on the slave.  The technique is described in the Tungsten Cookbook.  It is actually quite flexible and has some advantages for cleaning up data because you can also suppress trigger execution on the master.  
You should regard all triggers with suspicion when moving to multi-master.  If you cannot eliminate triggers, at least find them, look at them carefully to ensure they do not generate conflicts, and test them very thoroughly before deployment.  Here's a query to help you hunt them down: 
SELECT trigger_schema, trigger_name 
  FROM information_schema.triggers;
6. Have a Plan for Sorting Out Mixed Up Data

Master/slave replication has its discontents, but at least sorting out messed up replicas is simple: re-provision from another slave or the master.  No so with multi-master topologies--you can easily get into a situation where all masters have transactions you need to preserve and the only way to sort things out is to track down differences and update masters directly.   Here are some thoughts on how to do this.
  1. Ensure you have tools to detect inconsistencies.  Tungsten has built-in consistency checking with the 'trepctl check' command.  You can also use the Percona Toolkit pt-table-checksum to find differences.  Be forewarned that neither of these works especially well on large tables and may give false results if more than one master is active when you run them.  
  2. Consider relaxing foreign key constraints.  I love foreign keys because they keep data in sync.  However, they can also create problems for fixing messed up data, because the constraints may break replication or make it difficult to go table-by-table when synchronizing across masters.  There is an argument for being a little more relaxed in multi-master settings. 
  3. Switch masters off if possible.  Fixing problems is a lot easier if you can quiesce applications on all but one master.  
  4. Know how to fix data.  Being handy with SQL is very helpful for fixing up problems.  I find SELECT INTO OUTFILE and LOAD DATA INFILE quite handy for moving changes between masters.  Don't forget SET SESSION LOG_FILE_BIN=0 to keep changes from being logged and breaking replication elsewhere.  There are also various synchronization tools like pt-table-sync, but I do not know enough about them to make recommendations.  
At this point it's probably worth mentioning commercial support.  Unless you are a replication guru, it is very comforting to have somebody to call when you are dealing with messed up masters.  Even better, expert advice early on can help you avoid problems in the first place.

(Disclaimer:  My company sells support for Tungsten so I'm not unbiased.  That said, commercial outfits really earn their keep on problems like this.)

7. Test Everything

Cutting corners on testing for multi-master can really hurt.  This article has described a lot of things to look for, so put together a test plan and check for them.  Here are a few tips on procedure:
  1. Set up a realistic pre-prod test with production data snapshots.  
  2. Have a way to reset your test environment quickly from a single master, so you can get back to a consistent state to restart testing. 
  3. Run tests on all masters, not just one.  You never know if things are properly configured everywhere until you try. 
  4. Check data consistency after tests.  Quiesce your applications and run a consistency check to compare tables across masters. 
It is tempting to take shortcuts or slack off, so you'll need to find ways to improve your motivation.  If it helps, picture yourself explaining to the people you work for why your DBMS servers have conflicting data with broken replication, and the problem is getting worse because you cannot take applications offline to fix things.  It is a lot easier to ask for more time to test.  An even better approach is to hire great QA people and give them time to do the job right.

Summary

Before moving to a multi-master replication topology you should ask yourself whether the trouble is justified.  You can get many of the benefits of multi-master with system-of-record architectures with a lot less heartburn.  That said, an increasing number of applications do require full multi-master across multiple sites.  If you operate one of them, I hope this article is helpful in getting you deployed or improving what you already have.

Tungsten does a pretty good job of multi-master replication already, but I am optimistic we can make it much better.  There is a wealth of obvious features around conflict resolution, data repair, and up-front detection of problems that will make life better for Tungsten users and reduce our support load.  Plus I believe we can make it easier for developers to write applications that run on multi-master DBMS topologies.  You will see more about how we do this in future articles on this blog.




increase inodes in linux ext4 file system

inode

= data structure containing information about files.
= the inode number is an integer unique to the volume
= inodes point to blocks that make up a file and also contain the metadata of the file.

Warning: once the number is increased you can never reduce it
as new files are created, the file system consumes the additional disk space required to hold the inodes for the
additional files, there is no way for the storage system to release that disk space.

If you are keeping huge number of small files in your disks, this may one day cause running out of available inodes because of which even though you might have sufficient disk space, file system cannot create new files. Lets see how it works in my 1GB disk partition.

The parameter “-i” allows us to play with the number of inodes we can have in a partition. It is called “bytes-per-inode”. The bigger it is less number of inodes you will have. I have set a relatively big size “163840″ bytes per inode and the result is I have 6768 inodes. What this means indeed is I can’t create more than 6768 file.

In order to increase the number of inodes, format the partition again and specify the size.

#mkfs.ext3 -i 163840 /dev/sdb1

In order to check,use the command:
#df -i


The -i options specifies the size of the inode, not how many there are.
The -N option sets the number inodes

snapshots share inodes with live system files so snapshots shoud be deleted if present to free inodes

pcregrep

pcregrep 'April'  /var/log/messages

pcregrep 'April\s+(29|30|22)'  /var/log/messages

April + one or more spaces +29 or 30 or 22

pcregrep 'April\s+(29|30|22)'  /var/log/messages

setup KVM on centos 6 / 7


KVM requires a linux kernel module to support full virtualization. The linux module consists of three files:
1) kvm.ko,
2) kvm_intel.ko (for Intel processors),
3) kvm_amd.ko (for AMD processors).
the 2.6.20 kernel version (and higher) includes these kernel modules as part of the mainline kernel.

To disable SELinux on CentOS:
$ sudo -e /etc/selinux/config

SELINUX=permissive


modprobe is command used to add / remove module from linux kernel (check)
modprobe -l | grep kvm

kernel/arch/x86/kvm/kvm.ko
kernel/arch/x86/kvm/kvm-intel.ko
kernel/arch/x86/kvm/kvm-amd.ko

if kvm modules are properly loaded you will see following two sets of modules
lsmod | grep kvm

kvm_intel              54285  0
kvm                   333172  1 kvm_intel

OR

kvm_amd     35678
kvm         333172  kvm_amd

Load modules and its dependent modules if not loaded with modprobe command:
modprobe  kvm

yum groupinstall "Virtualization Tools" "Virtualization Platform"
yum install python-virtinst

OR

yum install kvm qemu-kvm python-virtinst libvirt libvirt-python virt-manager libguestfs-tools

yum install policycoreutils-python   //for selinux commands like semanage

yum install virt-viewer  //for viewing vms during install

//at client side install vnc with #yum install vnc -y

#chkconfig libvirtd on
The libvirtd program is the server side daemon component of the libvirt virtualization management system.
#service libvirtd start

check service status with:
service libvirtd status
or
virsh -c qemu:///system list

Sample setup

                     +-------------+
                     | CentOS/RHEL |             |-----|
     -->ISP router---+ Box Host w/ +--- eth0 -->-+ br0 +  Private IP
                     | KVM         |             |     |
                     +-------------+--- eth1 -->-+ br1 | Public IP
                                                 |-----|
                                                    |
                                                vm1-+---vm2----vm3---vm4
*** NOTE: each VMs will have two interface i.e. Private and Public *****

Where,
    eth0 - KVM servers' LAN interface.
    eth1 - KVM servers' WAN/Internet interface.
    br0 - KVM servers' bridge interface to give VM direct access to all the resources on the LAN.
    br1 - KVM servers' bridge interface to give VM direct access to all the resources on the WAN/Internet. Users can ssh into VMs or you can host HTTPD/SMTPD using this interface.
    obsd-vm1 (vm1) - OpenBSD VM name.
    rhel-vm1 (vm2) - RHEL VM name.

Install and configure a network bridge

All VMs will only have network access to host and other VMs on same physical server via private network. You need to crate a network bridge so that the VMs can access your LAN and possible the Internet/WAN from outside. Type the following yum command to install bridge-utils package:
# yum install bridge-utils

Setup a default gateway

Edit /etc/sysconfig/network as follows
# cat /etc/sysconfig/network
NETWORKING=yes
HOSTNAME=kvm-42.cyberciti.biz
## I am routing internet traffic via br1 ##
GATEWAYDEV=br1

Configure bridging

Update /etc/sysconfig/network-scripts/ifcfg-eth0 (private) as follows:
# cat /etc/sysconfig/network-scripts/ifcfg-eth0
DEVICE=eth0
ONBOOT=yes
HWADDR=00:30:48:C6:0A:D8
BRIDGE=br0

Update /etc/sysconfig/network-scripts/ifcfg-eth1 (public) as follows:
# cat /etc/sysconfig/network-scripts/ifcfg-eth1
DEVICE=eth1
ONBOOT=yes
HWADDR=00:30:48:C6:0A:D9
BRIDGE=br1

Create/edit the /etc/sysconfig/network-scripts/ifcfg-br0 file to setup private/lan ip address for br0:
# cat /etc/sysconfig/network-scripts/ifcfg-br0
DEVICE=br0
TYPE=Bridge
BOOTPROTO=static
ONBOOT=yes
## setup LAN/VLAN ips as per your needs ##
IPADDR=10.10.29.66
NETMASK=255.255.255.192
DELAY=0


Create/edit the /etc/sysconfig/network-scripts/ifcfg-br1 file to setup public/wan/internet ip address for br1:
# cat /etc/sysconfig/network-scripts/ifcfg-br1
DEVICE=br1
TYPE=Bridge
BOOTPROTO=static
ONBOOT=yes
## setup INTERNET ips as per your needs ##
IPADDR=74.ww.xx.yy
NETMASK=255.255.255.248
GATEWAY=74.ww.xx.yy
DELAY=0


I need to route all lan traffic (subnet 10.0.0.0/8) via 10.10.29.65 gateway. Create/edit file /etc/sysconfig/network-scripts/route-br0 as follows:
# cat /etc/sysconfig/network-scripts/route-br0
10.0.0.0/8 via 10.10.29.65

#check the selinux context for newly created network config files(check the other files)
ls -lz /etc/sysconfig/network-scripts/route-br0

-rw-r--r--. root root system_u:object_r:net_conf_t:s0  route-br0

Warning: Restarting network service over the ssh session may result into total loss of the connectivity to the server. So make sure br0 and br1 configuration including routing set correctly.

cd /var/lib/libvirt/    #checkout selinux context
[root@v1 libvirt]# ls -lZ
drwx--x--x. root root system_u:object_r:virt_content_t:s0 boot
drwxr-xr-x. root root system_u:object_r:virt_var_lib_t:s0 dnsmasq
drwx--x--x. root root system_u:object_r:virt_var_lib_t:s0 filesystems
drwxr-xr-x. root root system_u:object_r:virt_image_t:s0 images
drwx------. root root system_u:object_r:virt_var_lib_t:s0 lxc
drwx------. root root system_u:object_r:virt_var_lib_t:s0 network
drwxr-x---. qemu qemu system_u:object_r:qemu_var_run_t:s0 qemu

[root@v1 libvirt]# ls -lZ boot/     #we have our centos 6.4 iso inside boot
-rw-r--r--. qemu qemu system_u:object_r:virt_content_t:s0 CentOS-6.4-x86_64-minimal.iso

Use below for restoring default SELinux contexts
# restorecon -Rv /etc/sysconfig/
If you are going to reboot the SELinux enabled server, make sure you type the following command:
# touch /.autorelabel
# reboot
####Now restart Network and verify br0/br1 settings
service network restart
brctl  show
ip address
ping youtube.com

###########CREATING VMS

cd /var/lib/libvirt/boot/
put your iso file there with proper selinux
do #chcon --reference  source   isofile

virt-install -n vm201 --description "demoserver centos6.4 64bit"  --ram=512 --vcpus=1 --cpu host  --cdrom /var/lib/libvirt/boot/CentOS-6.4-x86_64-minimal.iso  --network bridge:br0,model=virtio --network bridge:br1,model=virtio --graphics vnc  --disk path=/var/lib/libvirt/images/vm201.img,bus=virtio,size=10 --hvm

go to your REAL HOST MACHINE if you are using putty:-
In boot option edit boot machine and add below it:---->>>>

console=ttyS0,115200

install .................
guest centos 6.5 machine gets rebooted
now, you are on main Host machine now(No putty)

virsh console vm201

####Now set  ip address
[root@localhost network-scripts]# cat ifcfg-eth0
DEVICE=eth0
HWADDR=52:54:00:D2:CB:F0
TYPE=Ethernet
UUID=309c7798-762f-424a-a84f-d74036039a7e
ONBOOT=YES
NM_CONTROLLED=yes
BOOTPROTO=static
IPADDR=10.10.10.100
NETMASK=255.255.255.0
GATEWAY=10.10.10.2

[root@localhost network-scripts]# cat ifcfg-eth1
DEVICE=eth1
HWADDR=52:54:00:8E:CE:8C
TYPE=Ethernet
UUID=986d56c6-1aee-4fbe-bbf9-e12b55be520e
ONBOOT=yes
NM_CONTROLLED=yes
BOOTPROTO=static
IPADDR=192.168.213.201
NETMASK=255.255.255.0
GATEWAY=192.168.213.2

#service network restart

You can access your GUEST vm with VNC

on your NON-kvm  linux laptop
do ssh portforwarding
ssh -L 5900:127.0.0.1:5900  root@KVM-Server-IP-Here
OR
ssh -L 5900:127.0.0.1:5900 -N -f -l root


hit tab and enter

console=ttyS0,115200

find largest file

for i in G M K; do du -ah | grep [0-9]$i | sort -nr -k 1; done | head -n 11

So the idea is very simple and works wonders. Here is what this does. The for loop goes thru the Gs first, then the Ms, then the Ks, It sorts them and the end result is they are all concattaned on the screen and sorted from biggest to smallest from G to M to K.
1. take list of numbers and grep out numbers that have “number and G” and sort that
2. Do step one but instead of G use M
3. Do step one but instead of G use K
4. Concatenate the results


http://ram.kossboss.com/linux-sort-cant-sort-human-readable-fixworkaround-sorting-human-reable/

find . -newer modsecurity.conf -exec rm -rf {} \;  
##deleting lates files newer than the file ‘modsecurity.conf’

network bandwidth analysis with iperf

yum install iperf

Before going ahead with the test, lets understand some networking concepts related to speed test.
Network Throughput
Transfer rate of data from one place to another with respect to time is called as throughput. Throughput is considered a quality measuring metric for hard disks,network etc. Its measured in Kbps(Kilo bits per second),Mbps(Mega bits per second),Gbps(Giga bits per second.)
TCP Window
TCP (Transmission Control Protocol), is a reliable transport layer protocol used for network communications. How TCP works, is beyond the scope of this article. TCP works on a reliable manner, by sending messages and waiting for acknowledgement from the receiver.
Whenever two machine's are communicating with each other, then each of them will inform the other, about the amount of bytes it is ready to receive at one time.
In other words, the maximum amount of data that a sender can send the other end, without an acknowledgement is called as Window Size. This TCP window size affects network throughput very badly sometimes. Lets take an example.
Suppose you want to send a 500MB of data from one machine to the other, with the tcp window size of 64KB.
Which means for sending the whole 500MB data, the sending machine has to wait 800 times for an acknowledgement from the receiver.
500MB / 64KB = 800
So you can clearly see that, if you increase the Window size a little bit to tune TCP, it can bring significant difference to the throughput achieved.
Suppose you have a windows machine and want to measure the speed between it and another Linux machine, then you need to make one as client, and another as the server. Lets see how.

route configuration

[root@support network-scripts]# cat route-eth0
# Static route for metadata service
169.254.169.254 via 0.0.0.0 dev eth0

[root@support network-scripts]# cat ifcfg-eth0
DEVICE=eth0
BOOTPROTO=dhcp
ONBOOT=yes
TYPE=Ethernet
USERCTL=yes
PEERDNS=yes
IPV6INIT=no
PERSISTENT_DHCLIENT=yes



nrpe dead but subsys locked

nrpe dead but subsys locked  error
service dead but subsys locked

check if the port used by nrpe is  already used by other processess like xinetd
netstat -tulnp | grep 5666
or
lsof -ni udp:5666
lsof -ni tcp:5666


This means the service was running at one time, but has crashed.
When you start a service, it creates a "lock" file to indicate that the service is running. This helps avoid multiple instances of the service. When you stop a service, this lock file is removed.
When a running service crashes, the lock file exists but the process no longer exists. Thus, the message.
Look at the two areas /var/run/*.pid and /var/lock/subsys/*. These are expected to agree with each other. That is, if the (emtpy file) lockfile /var/lock/subsys/crond exists, then the first line of the file /var/run/crond.pid is expected to contain the PID of the process running for this service. If no such process is running, then something is wrong. If a process is indeed running (as you see) but it is not that PID, then something is probably confused.



http://serverfault.com/questions/26276/what-does-service-name-dead-but-subsys-locked-mean

http://www.linuxquestions.org/questions/linux-networking-3/service-dead-but-subsys-locked-376488/

Create a New User and Grant Permissions in MySQL

create/delete users 
-------------------- 

CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';

DROP USER ‘demo’@‘localhost’;

Change passwords
-------------------
mysqladmin -u USER -p password NEWPASSWORD

mysqladmin -u marcelo -p oLdpa$$word 'NEwP@$$'
mysql> use mysql;

SET PASSWORD FOR 'user-name-here'@'hostname-name-here' = PASSWORD('new-password-here');
flush privileges;

GRANTING/REVOKE PRIVILEGES
--------------------------

GRANT ALL PRIVILEGES ON *.* TO 'newuser'@'localhost';

OR

GRANT ALL PRIVILEGES ON demoDB.* TO 'newuser'@'localhost';

GRANT SELECT,UPDATE,DELETE ON testDB.* TO 'demo-user'@'localhost';

REVOKE UPDATE ON testDB.* FROM 'demo-user'@'localhost';

GRANT ALL ON testDB.* TO 'demo-user'@'localhost';

FLUSH PRIVILEGES;
show grants for 'demo-user'@'localhost';


Privileges:-
= = = = = = 
ALL PRIVILEGES,CREATE,DROP,DELETE,INSERT,SELECT,UPDATE,GRANT OPTION

  • ALL PRIVILEGES- as we saw previously, this would allow a MySQL user all access to a designated database (or if no database is selected, across the system)
  • CREATE- allows them to create new tables or databases
  • DROP- allows them to them to delete tables or databases
  • DELETE- allows them to delete rows from tables
  • INSERT- allows them to insert rows into tables
  • SELECT- allows them to use the Select command to read through databases
  • UPDATE- allow them to update table rows
  • GRANT OPTION- allows them to grant or remove other users' privileges
To provide a specific user with a permission, you can use this framework:
 GRANT [type of permission] ON [database name].[table name] TO ‘[username]’@'localhost’;


The root login can be changed with the following command:
---------------------------------------------------------- 
rename user 'root'@'localhost' to 'newAdminUser'@'localhost';




setup and use GIT

signup / singn in  to github.com


yum install git

git config --global user.name "urgensherpa"
git config --global user.email  "urgen.sherpa@outlook.com"


create new repository in github <using webbrowser>
eg.  repo name is   test


#mkdir  /home/nepal/test
#cd /home/nepal/test
git init
git remote add origin https://github.com/urgensherpa/test.git
                                                                        ^               ^
            <username>/<reponame>

make some files in /home/nepal/test

git add  dbconnect.php     <update only 1 file>
git add .                   <update all/multiple current dir>
git commit  -m 'first commit'
git  push origin master
<enter your user name and password for github>

check in your github.com account to see changes

when you change your files

git add  .
git commit -m 'second commit'
git push origin master
<enter your user/password for github.com>

edit some file  eg.  function.php
git  add  .
git commit -m 'third commit'
git reset --soft HEAD^    #this will reset the commit but the change made in file function.php is as is


git reset --hard HEAD^  #it will reset + changes made is reverted back to last commit that is second commit

==============cloning=================
git clone https://github.com/urgensherpa/test.git

ls -l     #see the cloned repo in your local current dir
make changes in files
echo  "test abcd" >>  dbconnect.php
git add .
git commit -m "added new file"
git push origin master
<user/pass for github.com>

===================================
http://stackoverflow.com/questions/7106012/download-a-single-folder-or-directory-from-a-github-repo


Create a new repository on GitHub. To avoid errors, do not initialize the new repository with README, license, or gitignore files. You can add these files after your project has been pushed to GitHub.

  1. Open Terminal (for Mac users) or the command prompt (for Windows and Linux users).
  2. Change the current working directory to your local project.
  3. Initialize the local directory as a Git repository.
    git init
    
  4. Add the files in your new local repository. This stages them for the first commit.
    git add .
    # Adds the files in the local repository and stages them for commit. To unstage a file, use 'git reset HEAD YOUR-FILE'.
  1. Commit the files that you've staged in your local repository.
    git commit -m 'First commit'
    # Commits the tracked changes and prepares them to be pushed to a remote repository. To remove this commit and modify the file, use 'git reset --soft HEAD~1' and commit and add the file again.
  1. Copy remote repository URL fieldAt the top of your GitHub repository's Quick Setup page, click
  1. to copy the remote repository URL.
  2. In the Command prompt, add the URL for the remote repository where your local repository will be pushed.
    git remote add origin remote repository URL
    # Sets the new remote
    git remote -v
    # Verifies the new remote URL
    
  3. Push the changes in your local repository to GitHub.
    git push origin master
    # Pushes the changes in your local repository up to the remote repository you specified as the origin 
     
     
     
    git init
    git add .
    git commit -m "Initial commit"
    git remote add origin <project url>
    git push -f origin master 

cpulimit linux

apt-get install cpulimit
yum install cpulimit    <enable epel>

#Eg. . on centos 6.5   with cpulimit-0.1-1.20140722gitcabeb99.el6.x86_64.rpm

cpulimit -p 8645 -l 10    
#limits this process to 10 % of cpu

cpulimit -e /usr/local/bin/myprog -l 20
#limits the CPU usage of /usr/local/bin/myprog to 20%

X% of one CPU. So for example, if you set "-l 100" on a dual-core machine, you are limiting the usage to 50% of available CPU resource.

To find out PID of the process use any of the following:
# ps aux | less
# ps aux | grep firefox
# pgrep -u vivek php-cgi
# pgrep lighttpd



LVM PART 1 data restore after accidental removal of logical volume

 Data Restore after  accidental  remove/delete of logical volume                     
Preparing  testing enviroment :

After creating partition use below command

partx        /dev/sda
pvcreate     /dev/sda4   /dev/sda5
vgcreate  VG1    /dev/sda4 /dev/sda5
vgs                                                              #display vg's
lvcreate  -L  4G -n  lv001   VG1
lvscan         or           lvdisplay


mke2fs -t  ext4  -j  
/dev/volgroup001/lv001
Add more space to logical volume (here lv001 is increased from 4gb to 6gb)
lvresize -L 6GB /dev/volgroup001/lv001                     
After resizing
 resize2fs   /dev/volgroup001/lv001

Accidental removal of logical volume

#lvremove    /dev/volgroup001/lv001     
#ll /etc/lvm/archive   ##contains the arhive of lvm data
[root@demo1 ~]# ll /etc/lvm/archive/
total 44
-rw-------. 1 root root 1761 Oct  8 15:46 vg_demo1_00000-1563239603.vg
-rw-------. 1 root root 1135 Oct 20 18:34 volgroup001_00000-1225438891.vg
-rw-------. 1 root root 1135 Oct 20 18:36 volgroup001_00001-1361506140.vg
-rw-------. 1 root root 1731 Oct 21 19:56 volgroup001_00002-1489665094.vg
-rw-------. 1 root root 1731 Oct 22 18:46 volgroup001_00003-1149849750.vg
-rw-------. 1 root root 1733 Oct 23 10:46 volgroup001_00004-1224808495.vg
-rw-------. 1 root root 1741 Oct 23 10:46 volgroup001_00005-843600971.vg
-rw-------. 1 root root 1733 Oct 23 10:56 volgroup001_00006-965431690.vg
-rw-------. 1 root root 1734 Oct 23 13:24 volgroup001_00007-1544816747.vg
-rw-------. 1 root root 1130 Oct 23 13:29 volgroup001_00008-1538079247.vg
-rw-------. 1 root root 1552 Oct 23 18:02 volgroup001_00009-1668760531.vg

#vgcfgrestore --list  volgroup001                              

  File:        /etc/lvm/archive/volgroup001_00008-1538079247.vg
  VG name:        volgroup001
  Description:    Created *before* executing 'lvcreate -L 4G -n lv001 volgroup001'
  Backup Time:    Thu Oct 23 13:29:51 2014

  
  File:        /etc/lvm/archive/volgroup001_00009-1668760531.vg
  VG name:        volgroup001
  Description:    Created *before* executing 'lvresize -L 6GB /dev/volgroup001/lv001'
  Backup Time:    Thu Oct 23 18:02:56 2014

  
  File:        /etc/lvm/backup/volgroup001
  VG name:        volgroup001
  Description:    Created *after* executing 'lvresize -L 6GB /dev/volgroup001/lv001'
  Backup Time:    Thu Oct 23 18:02:56 2014

#######
read the description and backuptime and select the file eg. /etc/lvm/archive/volgroup001_00009-
1668760531.vg    
#######

######   NOW RESTORRING   ######

#vgcfgrestore   -f    /etc/lvm/archive/volgroup001_00009-1668760531.vg     volgroup001
#lvscan
#lvchange -ay /dev/volgroup001/lv001         ##lvchange= change attribute ,  -ay = activateall -yes
#lvscan




vgcfgrestore -f   /etc/lvm/backup/volgroup001


now mount the lvm again

=================================================================

parted
select /dev/sdb

or   parted /dev/sdb
mklabel msdos
mkpart primary 1  10GB                                #1MB to 10GB = approx. 10 GB partition is created

print  or p ##view partition table

Number  Start   End     Size    Type     File system  Flags
 1      1049kB  525MB   524MB   primary  ext4         boot
 2      525MB   21.5GB  20.9GB  primary               lvm



set   <partition-number>  lvm on
quit

partx /dev/sdb

pvcreate  /dev/sdb5 /dev/sdb6 /dev/sdb7

or

pvcreate /dev/sdb[567]

##extend volume group with name volgroup 001

vgextend  volgroup001 /dev/sdb5 /dev/sdb6 /dev/sdb7  

To expand rest of space in VG enter similar command like below:-

lvextend -l +100%FREE /dev/myvg/testlvm

icinga monitor mysql slave replication

icinga monitor msyql slave replication status

At SLAVE mysql server create a user with replication privileges
mysql> GRANT REPLICATION CLIENT on *.* TO 'nagios'@'%' IDENTIFIED BY '1LumbIni2$';
mysql> flush privileges;

 service mysql restart

At  ICINGA server
download nagios mysql slave monitoring script

wget  http://www.claudiokuenzler.com/nagios-plugins/check_mysql_slavestatus.sh
chown icinga.icinga check_mysql_slavestatus.sh; chmod +x check_mysql_slavestatus.sh;

  #./check_mysql_slavestatus.sh -H 198.50.176.187 -u nagios -p 1LumbIni2$ -P 3306
OK: Slave SQL running: Yes Slave IO running: Yes / master: 5.9.240.235 / slave is 0 seconds behind master | delay=0s

Define commands in commands.cfg
# 'check_mysql_slavestatus' command definition
define command{
command_name check_mysql_slavestatus
command_line $USER1$/check_mysql_slavestatus.sh -H $HOSTADDRESS$ -P $ARG1$ -u $ARG2$ -p $ARG3$
}

# 'check_mysql_slavestatus' command definition with delay check
define command{
command_name check_mysql_slavestatus
command_line $USER1$/check_mysql_slavestatus.sh -H $HOSTADDRESS$ -P $ARG1$ -u $ARG2$ -p $ARG3$ -w $ARG4$ -c $ARG5$
}

Now create service for checking

define service{
use generic-service ; Name of service template to use
host_name gskhanalslave
service_description MySQL Replication Status
check_command check_mysql_slavestatus!3306!nagios!1LumbIni2$
}


inotify inodes

What are inodes?

In a nutshell, inodes are the data structure Linux servers use to store information about a file. inodes are set to a specific number on your server. When you write files to the server, you are using an inode for each file. When your inodes reach their limit, you will get Disk Space errors and other strange behaviors with your site.

How do I view my servers inodes?

Below is the Linux command for finding the inodes for your server. This command is ran through shell.
df -i
Get to know inotify
Inotify is a Linux kernel feature that monitors file systems and immediately alerts an attentive application to relevant events, such as a delete, read, write, and even an unmount operation. 
http://www.infoq.com/articles/inotify-linux-file-system-event-monitoring
Inotify is a file change notification system in the Linux kernel, available since version 2.6.13. 
grep INOTIFY_USER /boot/config-$(uname -r)
CONFIG_INOTIFY_USER=y
# pwd
/proc/sys/fs/inotify
root@web01 [/proc/sys/fs/inotify]# ls
./  ../  max_queued_events  max_user_instances  max_user_watches 
#bydefault value in max_user_watches is = 8192 
#echo 65535 > /proc/sys/fs/inotify/max_user_watches
# cat /proc/sys/fs/inotify/max_user_watches          
65536 
To make the change permanent, edit the file /etc/sysctl.conf and add this line to the end of the file:
fs.inotify.max_user_watches=65535
If this server is a VPS and it is running in a OpenVZ container then you are NOT allowed to modify any kernel parameter of that container. and you will get below error
root@vps01 [/proc/sys/fs/inotify]# sysctl -w fs.inotify.max_user_watches=65535 error: permission denied on key 'fs.inotify.max_user_watches'
change it from host

user and group quota SWAP fstab file and parted command part 2

parted
select /dev/sdb
mklabel msdos
mkpart primary 1  10GB       # here partition starts from 1  that's  1 MB
quit

mkfs.ext4 -j  /dev/sdb1
OR
mke2fs -t ext4 -j /dev/sdb1

-j = journaling is an option as provided for transaction oriented processing of writes to disk in event of posssible corruption introduced by abrupt power outages

usermod -a -G admins  urgen
mount -o remount,rw /

use blkid to ascertain UUID of recently created partion for /etc/fstab
#blkid
UUID="9b317d2e-f873-4f1e-a12c-0a57e54c5657" /projectx ext4 defaults 0  0


when mounted roughly about 2% is used to manage journaling the file system

= = = = = = = = = =USER QUOTA = = = = = = =
yum install quota*
vim  fstab

uuid="sdklfjdskljf"  /home ext4 defaults,usrquota,grpquota 0  0

mount  -o  remount,rw   /drive
  quotacheck -cug   /drive/
  quotacheck -mcug  /home  ##this will create q.check db and generate disk usage table
                                            ##use -m option to overwrite the need of single user mode
  quotaon /drive
edquota urgen
Disk quotas for user urgen (uid 501):
  Filesystem                blocks       soft        hard             inodes     soft     hard
  /dev/sdb1                 90        2000000    2097000          4        0        0
                          [used block] <-- [around 2GB]-->
  repquota -a

Note:quotacheck should be run in SINGLE user mode when system reboots
quotacheck should be run in SINGLE user mode when system reboots
use:
m = dont remount filesystem read-only
a = (all)check all filesystems
g = check group files
u = check user files
c = create new quota files
quotacheck -mcug  /home  ##this will create quota check db and generate disk usage table

quotacheck -avug   #checks quotas
quotacheck -mavug   #force check quota or update quota data

edquota username

quota username
repquota  /drive  #report quota for all user

 = = = =  = = = =  = = = = = GROUP QUOTA = = = = = = = = = = = = = =
#quotaon /drive
[root@demo1 drive]# edquota -g urgen

Disk quotas for group urgen (gid 501):
  Filesystem                   blocks       soft       hard     inodes     soft     hard
  /dev/sdb1                     11000      10000      11000          6        5        0

Make sure of the group owner ship of filecreated
-------------------------------------------------

# quota -g urgen     ##check quota usage for group urgen



Do not attempt to resize a partition on a device that is in use.
Before resizing a partition, boot into rescue mode (or unmount any partitions on the device and turn off any swap space on the device).
Start parted, where /dev/sda is the device on which to resize the partition:
parted /dev/sda       
View the current partition table to determine the minor number of the partition to resize as well as the start and end points for the partition:
print
To resize the partition, use the resize command followed by the minor number for the partition, the starting place in megabytes, and the end place in megabytes. For example:
resize 3 1024 2048

= = = = = = = = =SWAP Space = = = = = = = = =
TRY TO MAKE SWAP PARTITIN ON A DEDICATED PARTITION OR DRIVE
check Swap with  top | free -m | swapon -s
 [root@monitor1 ~]# parted /dev/sdb
GNU Parted 2.1
Using /dev/sdb
Welcome to GNU Parted! Type 'help' to view a list of commands.
(parted) p                                                              
Model: VMware, VMware Virtual S (scsi)
Disk /dev/sdb: 21.5GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos

Number  Start   End     Size    Type     File system  Flags
 1      1049kB  10.2GB  10.2GB  primary  ext4
(parted) help mkpart                                                                                    #displays help for mkpart
(parted) mkpart  primary   linux-swap  10.2GB   11.2GB                          ##add 1 GB swap
(parted)print
Number  Start   End     Size    Type     File system  Flags
 1      1049kB  10.2GB  10.2GB  primary  ext4
 2      10.2GB  11.2GB  959MB   primary
# we might not see filesystem type here in parted ,we check with fdisk -l /dev/sdb command

# mkswap /dev/sdb2
vim /etc/fstab
UUID=05bb80f0-2c4e-46d8-98bf-2f7d8cbf8a8f none swap defaults 0 0
swapon -s   ##check your current unchanged swap
swapon -a   ## reload fstab with changed swap

swapoff -a  ##disables swap

++++++++++SWAP File+++++++++++++++++
dd  if=/dev/zero  of=/swapdir/swapfile3GB   bs=1024   count=3145728
mkswap   /swapdir/swapfile3GB
vim /etc/fstab
/swapdir /swapfile3GB  none swap defaults 0 0
OR
/swapdir /swapfile3GB  none swap sw 0 0

swapon -a



user and group quota fstab file part 1

UUID="2c6180d9-8ecd-41bb-a3b7-7be2c9e29395"  /drive  ext4 defaults,usrquota,grpquota 0 0

first  column=device
2nd column= mount point
3rd = type of FS
4th = mount options,

auto and noauto  =  With the auto option,"auto is default"[auto cause FS to mount at boot noauto the opposite]
user and nouser = user means allow norrmaluser to mount FS ,"no user is default"nouser disable normal user to mount.
exec and noexec= exec is default, exec allow execute binaries on that partition and noexec dont allow,
ro and rw = rw is default

sync and async=async is default,    in "sync"when you, for example, copy a file to the floppy, the changes are physically

written to the floppy at the same time you issue the copy command.
in "async" the changes may be physically written to it long time after issuing the command.

defaults Uses the default options that are rw, suid, dev, exec, auto, nouser, and async.

5th and 6th columns: Dump and fsck options

5th is dump option. Dump checks it and uses the number to decide if a file system should be backed up. If it's zero,
dump will ignore that file system. If you take a look at the example fstab, you'll notice that the 5th column is zero in

most cases.

The 6th column is a fsck option. fsck looks at the number in the 6th column to determine in which order the file systems

should be checked. If it's zero, fsck won't check the file system. 

change screen resolution ubuntu vmware

Run: xrandr
this will display available resolutions. Then you can perform the following:

xrandr -s 1024x768

Multiple SSL Certificate install on apache2 server [Ubuntu 12.04]



Multiple SSL Certificate install on apache2 server  [Ubuntu 12.04]
Enable SSL on your webserver
sudo a2enmod ssl
Follow up by restarting Apache.
sudo service apache2 restart
Copy your SSL certificate and key to any location
Eg. Here we copied to /etc/apache2/ssl  
Make sure permission of those files are 400 or 600 [root only read/write]
In   sites/sites-available/<your domains>

vim btlg.com.au
<VirtualHost *:80>
ServerName btlg.com.au 
ServerAlias 
www.btlg.com.au
DocumentRoot /home/bootleg/public_html
</VirtualHost>
<VirtualHost *:443>
ServerName btlg.com.au
ServerAlias 
www.btlg.com.au
DocumentRoot /home/bootleg/public_html
SSLEngine on
SSLCertificateFile /etc/apache2/ssl/btlg/281027f6c6f445.crt
SSLCertificateKeyFile /etc/apache2/ssl/btlg/www_btlg_com_au.key 
SSLCertificateChainFile /etc/apache2/ssl/btlg/sf_bundle-g2-g1.crt
</VirtualHost>

vim example.com.au
<VirtualHost *:80>
ServerName btlg.com.au 
ServerAlias
example.com.au
DocumentRoot /home/example.com/public_html
</VirtualHost>
<VirtualHost *:443>
ServerName
example.com.au
ServerAlias www.example.com.au
DocumentRoot /home/example.com/public_html
SSLEngine on
SSLCertificateFile /etc/apache2/ssl/example/281027f6c6f445.crt
SSLCertificateKeyFile /etc/apache2/ssl/example/www_example_com_au.key 
SSLCertificateChainFile /etc/apache2/ssl/btlg/sf_bundle-g2-g1.crt
</VirtualHost>


Restart apache2 and browse to your domain with http or https
#######################################


On Ubuntu 14.04.1 x64 bit
Enable ssl

a2enmod ssl

Generate certificates  for site  example.com
----------------------------------------------------
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/apache2/ssl/example.com/apache.key -out /etc/apache2/ssl/example.com/apache.crt

**generate certificates for site example.org**
-------------------------------------------------------------
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/apache2/ssl/example.org/apache.key -out /etc/apache2/ssl/example.org/apache.crt
##Virtual Host Configuration <note:  the vhost file should have .conf extension###

root@server1:/etc/apache2/sites-available# vim  example.com.conf
<VirtualHost *:80>
        ServerAdmin webmaster@localhost
        ServerName example.org
        DocumentRoot /var/www/html/example.org

</VirtualHost>


<IfModule mod_ssl.c>
<VirtualHost *:443>

        ServerAdmin webmaster@localhost
        ServerName example.org
        DocumentRoot /var/www/html/example.org

        #   SSL Engine Switch:
        #   Enable/Disable SSL for this virtual host.
        SSLEngine on

        SSLCertificateFile /etc/apache2/ssl/example.org/apache.crt
        SSLCertificateKeyFile /etc/apache2/ssl/example.org/apache.key
</VirtualHost>

</IfModule>

#Configure ports

#cat /etc/apache2/ports.conf

NameVirtualHost *:80
NameVirtualHost *:443
Listen 80

<IfModule ssl_module>
        Listen 443
</IfModule>

<IfModule mod_gnutls.c>
        Listen 443
</IfModule>

#Enable sites#
  a2ensite example.com
  a2ensite example.org

Step Four — Activate the SSL Virtual Host

Now that we have configured our SSL-enabled virtual host, we need to enable it.
We can do this by typing:
sudo a2ensite default-ssl.conf
We then need to restart Apache to load our new virtual host file:
sudo service apache2 restart