REDHAT CLUSTER part 2 - Setting up corosync , CMAN, and RGmanager centos 6.7

Disable SELinux on all nodes
setenforce 0

All nodes are under oracle virtual box:-
number of cluster nodes : 3
setup static ip for all 3 nodes and proper hostname
example
[root@c1 cluster]# cat /etc/hosts
127.0.0.1   localhost
192.168.0.55 c1.example.com c1
192.168.0.66 c2.example.com c2
192.168.0.77 c3.example.com c3

Setup proper gateway( setup similar config in other 2 nodes)
[root@c1]# cat /etc/sysconfig/network
NETWORKING=yes
HOSTNAME=c1.example.com
GATEWAY=192.168.0.235

[root@c1 ]# cat /etc/sysconfig/network-scripts/ifcfg-eth0
DEVICE=eth0
HWADDR=08:00:27:2E:24:80
TYPE=Ethernet
UUID=02e21921-20a5-4490-bf4a-052ab8cb6c11
ONBOOT=yes
NM_CONTROLLED=no
BOOTPROTO=none
IPADDR=192.168.0.55
NETMASK=255.255.255.0

NTP configuration: ON ALL 3 nodes. You must install and start the NTP time synchronization
service to maintain consistent time throughout the cluster:

[root@node-1 ~]# yum install ntp –y

Installation time is synchronized with official CentOS NTP
servers. If you want to change this, edit the NTP configuration file at /etc/
ntp.conf.
You must start the NTP service and make sure it starts at boot. In the
following screenshot, you can see the commands used:
[root@c1 ~]# service ntpd start
[root@c1 ~]# chkconfig ntpd on

Setting up corosync

setup iptables to allow cluster communication traffic among cluster nodes. You must add an iptables rule to allow UDP traffic on 5404 and 5405, and another rule to allow multicast traffic communication :

iptables -I INPUT -m state --state NEW -p udp -m multiport --dports 5404,5405 -j ACCEPT

iptables -I INPUT -m addrtype --dst-type MULTICAST -j ACCEPT

The default Corosync cluster communication ports are 5404 and
5405, and the UDP protocol is used. The ports are configured in the
/etc/corosync/corosync.conf configuration file. If you want
to change the default Corosync communication ports, make sure you
change iptables accordingly.

service iptables save

yum install corosync -y   #do it on all nodes

#generate corosync encryption key on any one node and transfer it to rest of nodes

#corosync-keygen
it might take long time so to speed up
dd if=/dev/random of=test123.log

Make backup of original file and rename on any one node.
[root@c1 ~]# cp /etc/corosync/corosync.conf.example /etc/corosync/corosync.conf
#vim corosync.conf

 Remove all commented-out lines—lines starting with #—and change the
secauth parameter to on.
 Change the bindnetaddr parameter to the current cluster node's IP address.



 * Remove all commented-out lines—lines starting with #—and change the
secauth parameter to on.
 * Change the bindnetaddr parameter to the current cluster node's IP address.
* Change the to_syslog parameter to no. We will use a separate log file, so there's no need to duplicate the information in syslog.

Now scp the corosync.conf to all rest of nodes

On all nodes
#service corosync start
#chkconfig corosync on

To check if members have joined
[root@c3 ~]# corosync-objctl  | grep member.*ip
runtime.totem.pg.mrp.srp.members.3.ip=r(0) ip(192.168.0.77)
runtime.totem.pg.mrp.srp.members.1.ip=r(0) ip(192.168.0.55)
runtime.totem.pg.mrp.srp.members.2.ip=r(0) ip(192.168.0.66)

You can stop corosync for some time on all nodes
#service corosync stop


Install CMAN on all nodes

yum install cman -y

Create cluster.conf file on any one node and copy to rest of nodes

cat /etc/cluster/cluster.conf

<?xml version="1.0"?>
<cluster config_version="3" name="hacluster">
    <logging debug="off"/>
    <clusternodes>
        <clusternode name="c1" nodeid="1"/>
        <clusternode name="c2" nodeid="2"/>
        <clusternode name="c3" nodeid="3"/>
    </clusternodes>
    <rm>
        <failoverdomains>
            <failoverdomain name="simple" nofailback="1" ordered="0" restricted="0">
                <failoverdomainnode name="c1"/>
                <failoverdomainnode name="c2"/>
                <failoverdomainnode name="c3"/>
            </failoverdomain>
        </failoverdomains>
    </rm>
</cluster>

The config_version parameter is the version of the CMAN
configuration file(it should be same on all nodes and should be increased by one+ when changed similar to serial number in bind zone configuration), and the name parameter is your preferred cluster name.
The debug parameter is set to off and should be turned on for debugging purposes.The clusternodes section is where the cluster nodes are configured. The clusternode parameter is defined by a name parameter, which is the FQDN or short node name, and the nodeid parameter, which is the ID of the cluster node.

Once the CMAN service has been successfully started on all cluster nodes, check the CMAN node status using the cman_tool nodes command. All three cluster nodes should be listed with status as M. In the following screenshot, you can see the output of the cman_tool nodes command issued on the node-1 cluster node:

[root@c1 ~]# cman_tool nodes
Node  Sts   Inc   Joined               Name
   1   M    364   2015-08-26 10:53:04  c1
   2   M    372   2015-08-26 10:54:14  c2
   3   M    368   2015-08-26 10:53:18  c3

Let's take a look at each column in more detail:
•     Node: This column shows the node ID number.
•     Sts: This column shows the cluster node status, with M indicating that the
node is a joined cluster member and X indicating that the node is dead.
•     Inc: This column is for debugging purposes only. It is the incarnation number.
•     Joined: This column shows the time the cluster member joined the cluster.
•     Name: This column shows the cluster node name as defined in the cluster.conf file.

Check quorum status:-

[root@c1 ~]# cman_tool status
Version: 6.2.0
Config Version: 3
Cluster Name: hacluster
Cluster Id: 10117
Cluster Member: Yes
Cluster Generation: 372
Membership state: Cluster-Member
Nodes: 3
Expected votes: 3
Total votes: 3
Node votes: 1
Quorum: 2 
Active subsystems: 7
Flags:
Ports Bound: 0 
Node name: c1
Node ID: 1
Multicast addresses: 239.192.39.172
Node addresses: 192.168.0.55

Nodes: This line is where the number of your cluster nodes
should be listed

Expected votes: This line shows the number of expected votes
in the currently active configuration

Total votes: This line shows the number of total votes provided
by the CMAN configuration file

Node votes: This line shows the number of votes the current
node has

Quorum: This line shows the number of votes required to reach
Quorum

The finishing touch for the CMAN installation and configuration process is the start of a service called ricci. "The ricci service provides on-the-fly CMAN configuration file distribution."

setup password for ricci user and start ricci on all nodes-

passwd ricci
Password: ********


service ricci start
chkconfig ricci on


Setup RG Manager on all nodes:-

iptables -I INPUT -m state --state NEW -p tcp -m multiport --dports 11111,21064,41966,41967,41968,41969 -j ACCEPT

service iptables save
service iptables restart

yum install rgmanager -y

service rgmanager start
chkconfig rgmanager on

Check cluster status:-

#clustat

#Member status: This line provides information about the
Quorum status.
#Member Name: This column shows the cluster node name as
defined in the cluster.conf configuration file.
#ID: This column shows the node ID number.
#Status: This column provides information about the node's
status. The output of the clustat command must list all
the cluster nodes as online, confirming that installation and
configuration of the cluster stack software on CentOS 6 were
successful and that you did a great job at it.


Edit cluster.conf file on any one node(you may need to manually create/copypaste same file on node which is offline) , make sure to increment configversion="" after making changes:-

[root@c1 ~]# cat /etc/cluster/cluster.conf
<?xml version="1.0"?>
<cluster config_version="3" name="hacluster">
    <logging debug="off"/>
    <clusternodes>
        <clusternode name="c1" nodeid="1"/>
        <clusternode name="c2" nodeid="2"/>
        <clusternode name="c3" nodeid="3"/>
    </clusternodes>
    <rm>
        <failoverdomains>
            <failoverdomain name="simple" nofailback="1" ordered="0" restricted="0">
                <failoverdomainnode name="c1"/>
                <failoverdomainnode name="c2"/>
                <failoverdomainnode name="c3"/>
            </failoverdomain>
        </failoverdomains>
    </rm>
</cluster>

To validate

[root@c1 ~]# ccs_config_validate
Configuration validates

Once it is found valid, you can propagate to other nodes

# cman_tool version -r

Note that, if a specific cluster node is not online, the configuration file will have to be transferred manually and the cluster stack software will have to be restarted to catch up once it comes back online.

You can confirm that the configuration file was successfully
distributed by issuing the ccs_config_dump command on any of
the other cluster nodes and comparing the XML output.

[root@c3 ~]# ccs_config_dump
<?xml version="1.0"?>
<cluster config_version="3" name="hacluster">
    <logging debug="off"/>
    <clusternodes>
        <clusternode name="c1" nodeid="1"/>
        <clusternode name="c2" nodeid="2"/>
        <clusternode name="c3" nodeid="3"/>
    </clusternodes>
    <rm>
        <failoverdomains>
            <failoverdomain name="simple" nofailback="1" ordered="0" restricted="0">
                <failoverdomainnode name="c1"/>
                <failoverdomainnode name="c2"/>
                <failoverdomainnode name="c3"/>
            </failoverdomain>
        </failoverdomains>
    </rm>
    <cman nodename="c3" cluster_id="10117"/>
</cluster>








































x11 forwarding in ubuntu 14.04 LTS

On server
======================
apt-get install xauth

/etc/ssh/ssh_config    #ssh client system-wide configuration file


Host *

ForwardX11 yes
ForwardX11Trusted yes


/etc/ssh/sshd_config     #daemon configuration

X11Forwarding yes
X11DisplayOffset 10


At client
==============
ssh -X user1@192.168.0.135

echo $DISPLAY
localhost:19.0



If it says anything other than localhost, it's quite possible you are not configured properly. If it says nothing, go down to the Configuring the SSH Server line.
To perform an actual test of the graphics, run xclock. A small clock should appear on your desktop if it works.
#to run firefox browser

#firefox -no-remote

REDHAT CLUSTER series part 1 introduction

There are two common types of computer clusters:

1) Load balancing computer clusters (loadbalancers, multiple web and database servers)
2) High-availability computer clusters (eg..Redhat cluster stack-  corosync,heartbeat,pacemaker  etc)

Category 2 ) High-availability computer clusters strive to minimize the downtime of the service
provided and not so much to improve the overall performance of the service.
active/active
active/passive
N + 1  =The N over 1 configuration
implies the presence of N cluster members in an active/active configuration with one cluster member in backup or hot standby. The standby cluster member is ready to take over any of the failed cluster node responsibilities at
any given time.

The cluster software stack must provide two significant features:
1)cluster communication : uses tcp or udp broadcast/multicast
2)cluster resource management: Cluster resource management starts, stops, and manages applications in the cluster in general. It relies on the cluster communication layer to get the information it requires about cluster members and their status, and takes cluster resource
actions based on that

Cluster resource manager components: -



TOTEM provides cluster group communication. TOTEM provides
cluster messaging and membership services. The cluster messaging service is the communication process among cluster members. This communication process is called a
heartbeat and the formation cluster members adopt is called a ring.


TOTEM uses the broadcast method to send messages
to all recipients simultaneously.  
TOTEM protocol introduces a special token, passed among the cluster members. Only the cluster member that possesses this TOKEN can broadcast messages to other cluster members. Virtual Synchrony concept was extended to allow continued operation with a so-called temporary transitional cluster configuration with reduced membership in case of cluster member failures
The Membership Protocol detects cluster member failures and rebuilds the cluster configuration, leaving out failed cluster members. A new passing token is also generated

Another very important process managed by the cluster communication layer is
called Quorum. Quorum is the minimum number of cluster member votes required to perform a cluster operation Some cluster communication software solutions support
an additional quorum disk that counts as an additional so-called tie-breaker vote.
The quorum disk is very useful and also required in an even-node cluster configuration. In a two-node cluster, only two votes are available from the cluster nodes, which means that, in the event of a cluster failure, the operational cluster node does not have quorum majority and
can't make decisions. The quorum disk is a shared storage disk to which all the cluster
members have access. All the cluster members use the quorum disk for heartbeat
communication and store cluster configuration data in it. Based on the activity on the quorum disk, cluster members can run their cluster communication via the quorum
disk, and the quorum disk can also count as a vote in the quorum process. The quorum
disk is a must in an even-node cluster configuration.

SPLIT Brain is a condition in the cluster where the cluster is split into two sides, each side thinking
that the other side is dead or inactive. In this situation, each side proceeds to take
over the resources as if the other side no longer exists. To prevent such scenarios,
an additional mechanism called FENCING  is used. Before any of the split sides of the
cluster takes over the resources, the fencing mechanism fences the other side by
issuing a configured action of reboot or power-off on the cluster nodes, thus making
sure that the cluster nodes on the other side are really dead. Once successful fencing
is confirmed, the operational side can safely start the resources without any data
corruption or disruption. types of fencing: resource-level fencing and node-level fencing. Resource-level fencing is the way the cluster disables a specific or problematic node to access a specific resource. This is usually used on shared storage resources, where a
problematic node is denied access to certain shared storage. More commonly used
is node-level fencing. Node-level fencing is a way to make sure a node does not run
any resources at all.

               
CentOS 6 and CentOS 7. The only difference between the two versions is the cluster resource
manager software used. This means that both solutions will use the same cluster communication software, called Corosync. Corosync provides cluster communication features and
capabilities. Corosync provides TOTEM with virtual synchrony, Quorum.
Since cluster resource manager software must run on top of Corosync, this is where
the road splits into two. There are two cluster resource manager software options
to use—either RGManager or Pacemaker . Generally, Pacemaker has more features
than RGManager. RGManager also requires the CMAN software as the middle layer
between it and Corosync. CMAN is the communication layer between Corosync and
RGManager, also providing some additional functionality. It is an interesting fact
that the official Red Hat Cluster software suite in RHEL 6 version includes Corosync,
CMAN, and RGManager; in RHEL 7, however, this was changed to Corosync and
Pacemaker.

https://alteeve.ca/w/Clustering
Configuration
how to calculate quorum?, the formula is:
quorum=peep(expected votes/2 + 1)
peep () function means allways round down
So if for example you hace a cluster formed by 3 nodes:
quorum=peep( 3 / 2 + 1)
quorum=peep( 1'5 + 1)
quorum=peep(2'5)
quorum=2
7 nodes..
quorum=peep (7 /2 +1 )
quorum=peep ( 3'5 +1 )
quorum=4
With cman_tool we can change the number of expected votes, lets say that we have and emergency and need to get a cluster quorate we can change the expected votes.
For example in a 3 node cluster we need to get a cluster working with only 1 node:
[root@centos ~]# clustat
Cluster Status for newcluster @ Thu Jul 18 17:21:33 2013
Member Status: Quorate
[root@centos ~]# cman_tool status
Version: 6.2.0
Config Version: 5
Cluster Name: newcluster
Cluster Id: 43508
Cluster Member: Yes
Cluster Generation: 60
Membership state: Cluster-Member
Nodes: 3
Expected votes: 3
Total votes: 3
Node votes: 1
Quorum: 2
Active subsystems: 8
Flags:
Ports Bound: 0 177
Node name: centosclu
Node ID: 1
Multicast addresses: 239.192.169.158
Node addresses: 1.1.1.2
[root@centos ~]# ccs_tool lsnode
Cluster name: newcluster, config_version: 6
Nodename Votes Nodeid Fencetype
centosclu 1 1
centos2clu 1 2
centos3clu 1 3
So lets say we loose centos2clu and centos3clu, and we need to start the cluster only with centosclu node:
we stop 1 node
[root@centos ~]# cman_tool status
Nodes: 2
Expected votes: 3
Total votes: 2
Node votes: 1
Quorum: 2
we stop 2 nodes:
[root@centos ~]#
Message from syslogd@centos at Jul 18 17:25:19 ...
rgmanager[2847]: #1: Quorum Dissolved
[root@centos ~]# cman_tool status
Membership state: Cluster-Member
Nodes: 1
Expected votes: 3
Total votes: 1
Node votes: 1
Quorum: 2 Activity blocked
[root@centos ~]# clustat
Service states unavailable: Operation requires quorum
Cluster Status for newcluster @ Thu Jul 18 17:26:22 2013
Member Status: Inquorate
So if we wan't to force the cluster to work with only one node we can change the expected votes:
[root@centos ~]# cman_tool expected -e 1
[root@centos ~]# clustat
Cluster Status for newcluster @ Thu Jul 18 17:27:37 2013
Member Status: Quorate
[ root@centos ~]# cman_tool status
Nodes: 1
Expected votes: 1
T otal votes: 1
Node votes: 1
Quorum: 1
Once we recover the nodes we need to leave the expected votes back to normal otherwise we can have serious problems with data integrity.
If we wan't to modify how many votes a node adds to a cluster we have several ways, for example manually editing the cluster.conf file:
root@centos cluster]# cat /etc/cluster/cluster.conf
<?xml version="1.0"?>
We can get info on all the parameters of the cluster.conf file from this html file:
/usr/share/doc/cman-3.0.12.1/cluster_conf.html
Once we modify the file we need to increment by one the config_version="7" number, and then distribute and activate the file using for example cman_tool:
[root@centos cluster]# cman_tool version -r
You have not authenticated to the ricci daemon on centos3clu
Password:
You have not authenticated to the ricci daemon on centos2clu
Password:
You have not authenticated to the ricci daemon on centosclu
Password:
[root@centos cluster]# ccs_tool lsnode
Cluster name: newcluster, config_version: 7
Nodename Votes Nodeid Fencetype
centosclu 2 1
centos2clu 1 2
centos3clu 1 3
[root@centos cluster]# cman_tool status
Version: 6.2.0
Membership state: Cluster-Member
Nodes: 3
Expected votes: 3
Total votes: 4
Node votes: 2
Quorum: 3
we can also modify expected votes to 4, so it all looks how it does:
[root@centos cluster]# cman_tool expected -e 4
[root@centos cluster]# cman_tool status
Nodes: 3
Expected votes: 4
Total votes: 4
Node votes: 2
Quorum: 3
Active subsystems: 8
Flags:
Ports Bound: 0 177
Node name: centosclu
Node ID: 1
Multicast addresses: 239.192.169.158
Node addresses: 1.1.1.2
Another exercise, we are going to give centos node 3 votes so even if we loose centos2 and centos3, we still have qourom tu run with centos.
We modify the file /etc/cluster/cluster.conf like before, and distribute it to all nodes, using ccs this time:
[root@centos4 ~]# ccs -h centos --sync --activate
We can check we have the new version working with 3 votes for node1:
[root@centos3 cluster]# cman_tool status
Version: 6.2.0
Config Version: 10
Cluster Name: newcluster
Cluster Id: 43508
Cluster Member: Yes
Cluster Generation: 192
Membership state: Cluster-Member
Nodes: 3
Expected votes: 4
Total votes: 5
Node votes: 1
Quorum: 3
No we take down centos2 and centos3
[liquid@liquid-ibm:~]$ virsh destroy centos2 (07-18 11:27)
Domain centos2 destroyed
[liquid@liquid-ibm:~]$ virsh destroy centos3 (07-18 18:07)
Domain centos3 destroyed
On centos logs we can see:
Jul 18 18:08:00 centos rgmanager[2267]: State change: centos2clu DOWN
Jul 18 18:08:00 centos fenced[1866]: fencing node centos3clu
Jul 18 18:08:00 centos rgmanager[2267]: State change: centos3clu DOWN
[root@centos ~]# clustat
Cluster Status for newcluster @ Thu Jul 18 18:10:03 2013
Member Status: Quorate
Member Name ID Status
------ ---- ---- ------
centosclu 1 Online, Local
centos2clu 2 Offline
centos3clu 3 Offline
[root@centos ~]# cman_tool status
Version: 6.2.0
Config Version: 10
Cluster Name: newcluster
Cluster Id: 43508
Cluster Member: Yes
Cluster Generation: 196
Membership state: Cluster-Member
Nodes: 1
Expected votes: 4
Total votes: 3
Node votes: 3
Quorum: 3
- See more at: http://www.hpuxtips.es/?q=content/part5quorum-my-study-notes-red-hat-certificate-expertise-clustering-and-storage-management#sthash.sacx9AAD.dpuf

tcp wrappers hosts.deny and hosts.allow

  1. TCP Wrapper is a host-based networking ACL system, used to filter network access to Internet Protocol servers on (Unix-like) operating systems such as Linux or BSD. It allows host or subnetwork IP addresses, names and/or ident query replies, to be used as tokens on which to filter for access control purposes.
TCP wrapper based access List Rules can be included in the two files
/etc/hosts.allow and
/etc/hosts.deny .
Work precedence:
  1. /etc/hosts.allow-
    1. if allow will not check 2
    2. if not found then go to 2
  2. /etc/hosts.deny .
    1. if not found allow access.
Points to remember
  • You can have only one rule per service in hosts.allow and hosts.deny file.
  • Any changes to hosts.allow and hosts.deny file takes immediate effect.
  • The last line in the files hosts.allow and hosts.deny must be a new line character. Or else the rule will fail.
Rule Syntax
The syntax for both hosts.allow and hosts.deny file takes the following form:
daemon : client [:option1:option2:…]
Examples
Allow SSH
for xyz.com and
deny access to all the others.
sshd : .xyz.com
… and in the hosts.deny file I include the rule:
sshd : ALL
Denys FTP access to all in abc.com domain  and hosts in the 192.168.1.0 network.
#FILE: /etc/hosts.deny
vsftpd : 192.168.1. , .abc.com
Beautification
#FILE: /etc/hosts.deny
vsftpd : 192.168.1. , .abc.co.in : spawn /bin/echo  `/bin/date` access denied >> /var/log/vsftpd.log : deny
In the above rule, spawn logs a message to the vsftpd log file each time the rule matches. deny is optional if you are including this rule in the hosts.deny file.
For example, you can use spawn option to send mail to the admin when ever a deny rule is matched.
Wildcards
You can use wildcards in the client section of the rule to broadly classify a set of hosts. These are the valid wildcards that can be used.
  • ALL – Matches everything
  • LOCAL – Matches any host that does not contain a dot (.) like localhost.
  • KNOWN – Matches any host where the hostname and host addresses are known or where the user is known.
  • UNKNOWN – Matches any host where the hostname or host address are unknown or where the user is unknown.
  • PARANOID – Matches any host where the hostname does not match the host address.
Patterns
ALL : 123.12.
Matches all the hosts in the 123.12.0.0 network. Note the dot (.) in the end of the rule.
ALL : 192.168.0.1/255.255.255.0
IP address/Netmask can be used in the rule.
sshd : /etc/sshd.deny
If the client list begins with a slash (/), it is treated as a filename. In the above rule, TCP wrappers looks up the file sshd.deny for all SSH connections.
sshd : ALL EXCEPT 192.168.0.15
will allow ssh connection for only the machine with the IP address 192.168.0.15 and block all other connections.
You can use the options allow or deny to allow or restrict on a per client basis in either of the files hosts.allow and hosts.deny
in.telnetd : 192.168.5.5 : deny
in.telnetd : 192.168.5.6 : allow
Shell Commands
As mentioned above, you can couple the rules to certain shell commands by using the following two options.
spawn – This option launches a shell command as a child process. For example, look at the following rule:
sshd : 192.168.5.5 : spawn /bin/echo `/bin/date` from %h >> /var/log/ssh.log : deny
Each time the rule is satisfied, the current date and the clients hostname %h is appended to the ssh.log file.
twist – This is an option which replaces the request with the specified command. For example, if you want to send to the client trying to connect using ssh to your machine, that they are prohibited from accessing SSH, you can use this option.
sshd : client1.xyz.com : twist /bin/echo “You are prohibited from accessing this service!!” : deny
When using spawn and twist, you can use a set of expressions. They are as follows :
%a — The client’s IP address.
%A — The server’s IP address.
%c — Supplies a variety of client information, such as the username and hostname, or the username and IP address.
%d — The daemon process name.
%h — The client’s hostname (or IP address, if the hostname is unavailable).
%H — The server’s hostname (or IP address, if the hostname is unavailable).
%n — The client’s hostname. If unavailable, unknown is printed. If the client’s hostname and host address do not match, paranoid is printed.
%N — The server’s hostname. If unavailable, unknown is printed. If the server’s hostname and host address do not match, paranoid is printed.
%p — The daemon process ID.
%s — Various types of server information, such as the daemon process and the host or IP address of the server.
%u — The client’s username. If unavailable, unknown is printed.

awstats for apache webserver

https://hottiehunter.com/awstats/awstats.pl?config=hottiehunter.com
Ubuntu 14.04, awstat version=7.2

#apt-get install awstats libgeo-ipfree-perl libnet-ip-perl
#a2enmod cgi 
 
 cp /etc/awstats/awstats.conf /etc/awstats/awstats.hottiehunter.com.conf
 
LogFile="/var/log/apache2/access.log"
LogFormat=1
 
SiteDomain="example.com"
#HostAliases="localhost 127.0.0.1 example.com"  #lesser is better for performance
 HostAliases="www.hottiehunter.com"
DirCgi="/awstats"
 
LoadPlugin="tooltips"
LoadPlugin="graphgooglechartapi"
LoadPlugin="geoipfree"
 
SkipDNSLookupFor="REGEX[^192\.168\.]"
 
AllowFullYearView=3 


Manually running update
========================

/usr/lib/cgi-bin/awstats.pl -config=hottiehunter.com -update
 
 

Automatic Stat Updates

To maintain the stats on a regular basis you will need a cron job to run the awstats update script. Change the user who will be running the script from www-data to root. There area bunch of permission errors when run as www-data.
The cron job below will run every 10 minutes, adjust the time to your needs.

*/10 * * * * root /usr/lib/cgi-bin/awstats.pl -config=hottiehunter.com -update > /dev/null
 
Configure Apache2 for awstats

vim /etc/apache2/sites-available/awstats.conf
 #for user password authentication to view stats
<Directory /usr/lib/cgi-bin/>
 AuthName "Enter Your User Name and Password"
  AuthType Basic
  AuthUserFile /etc/apache2/auth_users
  Require valid-user
</Directory> 
#alias configuration
Alias /awstatsclasses "/usr/share/awstats/lib/"
Alias /awstats-icon/ "/usr/share/awstats/icon/"
Alias /awstatscss "/usr/share/doc/awstats/examples/css"
ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
ScriptAlias /awstats/ /usr/lib/cgi-bin/
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch

if you receive some warnings with command :
apache2ctl -t 

grep search in /etc/apache2 with "alias and scriptalias as keywords"
for example
grep -i -R "ScriptAlias" /etc/apache2/*   #find duplicatoins and remove accordingly
Currently my config looks like:
 
Alias /awstatsclasses "/usr/share/awstats/lib/"
Alias /awstats-icon/ "/usr/share/awstats/icon/"
Alias /awstatscss "/usr/share/doc/awstats/examples/css"
#ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/    #this is commented due to duplicaton
ScriptAlias /awstats/ /usr/lib/cgi-bin/
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch 


Stop Unauthorised Users

As the above setup stands anyone, that is the world and his dog can now see your web serrver stats. Probably not a good idea or something you want. We can let Awstats protect itself with the rather well named parameter AllowAccessFromWebToFollowingIPAddresses or as it is also simple to restrict access by forcing the user to enter a password or simple only allow IP addresses on your local LAN not from external IPs.
To allow awstats to protect itself edit the config file and add a list of IP addresses or ranges see the comment above the option of the syntax.
sudo nano /etc/awstats/awstats.example.com.conf
 
AllowAccessFromWebToFollowingIPAddresses="127.0.0.1 192.168.2.0-192.168.2.255" 
 

Access via a User Name and Password

To create a new user file and add the username “richard” to the file /etc/apache2/auth_users

To append other users do not use the -c flag.

htpasswd -c /etc/apache2/auth_users richard
 
#configuration is already on top for awstats.conf file for user/pass authentication

#service apache2 restart
 

Logging Data From Old logs

If you want to log the data in old log files rotated out of the way you can do that using a command line similar to the below. This may take some time depending on the number and size of your log files and the files need to be run in chronological order. If you ran the manual update above you will need to delete the database. Anyway, it was worth while as that is generally very quick and you can see some data being displayed. Also, it is worth moving the cron file for awstats to stop that from running.
The database files are where ever you pointed the option DirData to, it defaults to /var/lib/awstats. The second command mv the awstats cron job out of the way.

sudo rm /var/lib/awstats/*
 
sudo mv /etc/cron.d/awstats /root
 
Now we can run the log import or update from the command line. My Apache
 logs are compressed and called access.log,  access.log.1 or 
access.log.n.gz. Giving the following command line to import them all. 
Depending on the size and number of files this may put a heavy load on 
the server, so i also run the command through nice.

Note: the command should all be on one line.
 
sudo nice /usr/lib/cgi-bin/awstats.pl -update -config="example.com" -LogFile="/usr/share/awstats/tools/logresolvemerge.pl /var/log/apache2/access.log* |"
 

Remember to put the cron file back again.
sudo mv /root/awstats  /etc/cron.d
 
1) The URL should be
http://example.com/awstats/awstats.pl?config=example.com
2) Unless the CGI module is enabled, the perl script will be offered for download instead of being executed.
An additional step was required on my Ubuntu 14.04 system:
a2enmod cgi
 
Additional resource:
http://computers.in4mnation.com/install-and-secure-awstats-ubuntu-apache2/#set_up_cron_to_update_awstats
http://blogging.dragon.org.uk/installing-awstats-on-ubuntu-14-04-lts/




Nginx brief introduction

why exactly is nginx so much faster than the typical Apache setup of the prefork MPM and mod_php? The technical explanation is that nginx is a non-blocking event based architecture while Apache is a blocking process based architecture. To simplify it heavily the theory is like this:

Apache "Prefork Processes":

    Receive PHP request, send it to a process.
    Process receives the request and pass it to PHP.
    Receive an image request, see process is busy.
    Process finishes PHP request, returns output.
    Process gets image requests and returns the image.

While the process is handling the request it is not capable of serving another request, this means the amount of requests you can do simultaneously is directly proportional to the amount of processes you have running.
Apache + PHP setup has the PHP binary embedded directly into the Apache processes. This means Apache can talk to PHP incredibly fast and without much overhead, but it also means that the Apache process is going to be 25-50MB in size. Not just for requests for PHP requests, but also for all static file requests. This is because the processes keep PHP embedded at all times due to cost of spawning new processes. This effectively means you will be limited by the amount of memory you have as you can only run a small amount of processes and a lot of image requests can quickly make you hit your maximum amount of processes.

Nginx "Event Based Processing:"

    Receive request, trigger events in a process.
    The process handles all the events and returns the output


Nginx
Nginx, on the other hand, requires the use of PHP-FPM if you want to run a PHP application. It
doesn’t have a module to load in PHP like Apache can. I always use Nginx, as it does everything I
need with a simpler configuration, and better overall performance.

Process Management
PHP-FPM’s master process creates child processes to handle all PHP requests. Processes are
expensive to create and manage. How we treat them is important.
PHP-FPM is an implementation of FastCGI, which uses “persistent processes”. Rather than killing
and re-creating a process on each request, FPM will re-use processes.
This is much more efficient than Apache’s mod_php, which requires Apache to create and destroy a
process on every request.

nginx –s stop Stops the daemon immediately (using the TERM signal)
nginx –s quit Stops the daemon gracefully (using the QUIT signal)
nginx –s reopen Reopens the log files
nginx –s reload Reloads the configuration

part 5 apache MOD REWRITE

url rewrite with mod_rewrite.so  engine#
 
feature:
1)changes url or underlying request based on condition
2)based on perl regex
  important characters are
  . = matches a  single character
  * = matches zero or more of previous character
  + = matches one or more
  ? = optional match
  [] = character class  i,e '/prod[123]*'
  [^] = character class negation
  () = groups character for assignation to backreference , eg '/(prod|products)'
3) ability to parse:
  HTTP headers
  Server VARs - %{HTTP_HOST}
  enviromental VARs i,e IE
 
 http://hostname/URI
 HTTP= scheme
 host=hostname
 urlpath = /.. = basic rewrites operate here

  •        <Directory>
  •        .htaccess
      
      
RewirteRule - basic requirement - Takes 3 argument
usage: 'RewriteRule Pattern(URL-Path) Substitution [flag[s]]
Note: URL-Path matches after HOST and before Query String
eg http://site2.example.com/prod/index.php?pid=1&user=current

Note: substitution can be:
    a) File system path(mod_alias):
    RewriteRule ^/docs /usr/local/share/apache2/docs
    Note: The above uses 'mod_rewrite' as mod_alias
   
    b)web path:
    RewirteRule ^/docs$ /documents
    note: '/documents' exists beneath the DocumentRoot
   
    c)absolute URL: 'RewirteRule ^/docs$ http://www.testing.com/docs [R]'
    rewrites users browser URL to reflect new absolute URL
   
    Redirect
    No Change: '-'
    RewriteRule \.(jpg|png) - [E=image:1]  =>this enable VAR for later usage
Note Flags are optional can be multiple [f1,f2,f3...] and include common option
[NC] = case insensitive
[E=Var:Value] - setting of enviroment VAR -useful in logs,other rewrite rule, CGI
[F] = Returns 403 to client forbidding access to resource
[G] = Returns 410 to client resource is no longer available
[R] = returns redirect 300-399 to client

note: consult mod_rewrite docs for more flags

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

ensure module is loaded

ln -s . /etc/apache2/mods-available/rewrite.loaded

vim 000-default.conf
<virtualhost>
..
#request for example.com/index.html is sent to example.com/index2.html
RewriteEngine on   #enables processing
RewriteRule ^/index.html$ /index2.html #fetches new content but does not Redirect BROWSER (eg. example.com/index.html will serve content from index2.html but BROWSER url bar is not changed )
RewriteRule ^/index.html$ /index2.html [R] #fetches new content ALSO Redirect bROWSER #url is changed in browser
RewriteRule ^/docs$ http://testing.com/docs [R]


</virtualhost>


#mod rewrite - rewrite condition
 

features:

 stackability of logic
 rules are implicitly ANDed: use [OR] to enable ORing
 one or more tests may be performed on current request
 Supports backreferences using: %N - %1..%9
 Usage 'RewriteCond TestString CondPattern (RegEx) [OR, ornext, NC,NV
   teststring:
      RewriteRule
     
Task:
omit localhost (127.0.x.y) from apache logs
 a)  RewriteCond %{REMOTE_ADDR} ^127\.0\.
 b)  RewriteRule .* - [E=localnolog] => Defines VAR to indicate request from localhost
 c)  'CustomLog /var/log/apache/access.log combined env=!localnolog'



 Force SSL for url path '/login$'

 'RewriteCond %{REQUEST_URI} ^/login'
 'RewriteCond ${SERVER_PORT} !443'
 'RewriteRule .* https://%{HTTP_HOST}/login'
OR
 RewriteCond %{REQUEST_URI} ^(/login.*)
RewriteCond %{SERVER_PORT} !443
RewriteRule .* https://%{HTTP_HOST}/login.html

Force ssl for all
RewriteCond %{SERVER_PORT} !443
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI

RewriteEngine on
RewriteCond %{HTTP_HOST} ^lokeshworhandicraft.com.np [NC,OR]
RewriteCond %{HTTP_HOST} ^www.lokeshworhandicraft.com.np [NC]
RewriteCond %{REQUEST_URI} !^/public/
RewriteRule ^(.*)$ /public/$1 [L]

 

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}





Back reference

##mod rewrite##
Backreferences

feature
 #tokenize portion of URL for reuse
 #token range form $1 .. $9
 #uses '()' to create token
 #per server and per directory (.htaccess | <Directory>)
 Note: normally placed at site-wide or virtualHost layer
 Note: normally used to match: URL-Path

 task:
 rewrite index.html -> /new/index.html
 ------------------------------------------
 RewriteRule ^/(index.html)$ /new/$1  #equivalent to redirect[Match]
 RewriteRule ^/(index.html)$ /new/$1 [R] #equivalent to Redirect[Match] - Force redirect


 Rewrite 'localhost/docs*' -> 'http://www.facebook.com/docs*
 a. RewriteRule ^(/docs.*)$ http://linuxorg.com$1 - Redirects: '/docs* to remote server










part 4 apache conditional handling

conditional handling features:

A) make decisions based on current conditions:
 1) modules available
 2) remote HOST
 3) browser type - useragent(http header request)

B) <IfDefine> parameter - directives to be processed at server startup
C) <IfModule> - directive to be processed based on module existence. Eg mod_ssl
D) <IfVersion> - directive processed based on version of apache
E) SetEnvIf[NoCase] -sets environmental VAR (variable) based on :
   HTTP Request Header : i,e User-Agent, Referer , Accept-Language
   Remote_(Addr|Host) server_addr, Request_(method|Protocol), Request_URI
   Predefined Environmental VARs using : SetEnvIf[NoCase]
  
Task:

 Explore <IfModule>

 apachectl -D DUMP_MODULES 
 or
 apache2ctl -M | grep -E "(static|shared)" | wc -l

 cd /etc/apache2 && grep -R -i 'ifmodule' *   --searches for ifmodule

 inside the <VirutalHost>
 <VirtualHost>
 ..
 SetEnvIf Referer "site1.linuxcbt.internal" site1_referrer
 CustomLog /var/log/apache2/site2.site1_referral.access.log combined env=site1_referrer
 </VirtualHost>