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