Thursday, November 8, 2012

Futex in Linux

Test Class for Shm

class Test
{
        public:
        int i_val[3];
        int64_t time;
        int seq;
};
 

Following is futex WAIT example using shm

include <linux/futex.h>
#include <sys/time.h>
#include <iostream>
#include <unistd.h>
#include <sys/syscall.h>

#include <Timer.h>
#include "ShmManager.h"
#include "Test.h"

//static long sys_futex(void *addr1, int op, int val1, struct timespec *timeout, void *addr2, int val3)
//{
//      return syscall(SYS_futex, addr1, op, val1, timeout, addr2, val3);
//}

using namespace std;
using namespace NS_COOL;


int main(int argc, char** argv)
{
        google::InitGoogleLogging(argv[0]);

        Timer timer;
        Test * test;
        ShmManager shm_man;
        shm_man.Add("FUTEX_SHM",4096 ,false);
        shm_man.AddType("FUTEX_SHM","FUTEX_SHM_TYPE", &test);
        cout<<"Shm created"<<endl;


        int index = atoi(argv[1]);
        cout<<"test "<<test->i_val[index]<<endl;
        test->i_val[index] = 1;
        cout<<"test "<<test->i_val[index]<<endl;

        int count = 0;
        int64_t tot = 0;
        //int64_t next_seq = 1;

        int min = 1000;
        int max = 0;
        int diff = 0;

while(true)
{
//       cout<<"Waiting.."<<endl;
        //int ret = syscall(SYS_futex ,&test->i_val,FUTEX_WAIT,1,NULL,NULL,0);
        syscall(SYS_futex ,&test->i_val[index],FUTEX_WAIT,1,NULL,NULL,0);
        int64_t time  = timer.ClockGetTime().GetTime();
        /*int l_Errno = errno;
        cout<<"l_Errno="<<l_Errno<<" seq="<<test->seq<<" Time="<<time - test->time<<endl;
        if (l_Errno == ETIMEDOUT)
                cout<<"ETIMEDOUT ret="<<ret<<endl;
        if (l_Errno == EWOULDBLOCK)
                cout<<"EWOULDBLOCK ret="<<ret<<endl;
        if (l_Errno == EINTR)
                cout<<"EINTR ret="<<ret<<endl;
       

        if(next_seq != test->seq)
        {
                cout<<"Seq Missing"<<endl;
                next_seq = test->seq + 1;      
        }
        else
                ++next_seq;
        */

        ++count;
        diff = time - test->time;
        tot += diff;
        if(min > diff)
                min = diff;

        if(max < diff)
                max = diff;

        if(count % 100 == 0)
                cout<<"Avg = "<<double(tot)/double(count)<<" min="<<min<<" max="<<max<<endl;
}
        return 0;
}

Following is futex WAKE example using shm

#include <linux/futex.h>
#include <sys/time.h>
#include <iostream>
#include <unistd.h>
#include <sys/syscall.h>

#include <Timer.h>
#include "ShmManager.h"
#include "Test.h"

//static long sys_futex(void *addr1, int op, int val1, struct timespec *timeout, void *addr2, int val3)
//{
//      return syscall(SYS_futex, addr1, op, val1, timeout, addr2, val3);
//}

using namespace std;
using namespace NS_COOL;


int main(int argc, char** argv)
{
        google::InitGoogleLogging(argv[0]);

        Timer timer;
        Test * test;
        ShmManager shm_man;
        shm_man.Add("FUTEX_SHM",1024 ,false);
        shm_man.AddType("FUTEX_SHM","FUTEX_SHM_TYPE", &test);
        cout<<"Shm created"<<endl;
        sleep (10);
        test->seq = 0;

        int count = 0;
        int64_t tot = 0;
while(true)
{
        ++test->seq;
        //cout<<"Waking.."<<endl;
        test->time = timer.ClockGetTime().GetTime();
        for(int i = 0 ; i < 3 ; ++i)
                syscall(SYS_futex ,&test->i_val[i],FUTEX_WAKE,1,NULL,NULL,0);
        /*int ret = syscall(SYS_futex ,&test->i_val,FUTEX_WAKE,5,NULL,NULL,0);
        cout<<"syscall time "<<timer.ClockGetTime().GetTime() - test->time<<endl;
        int l_Errno = errno;
        //cout<<"l_Errno="<<l_Errno<<endl;
        if (l_Errno == ETIMEDOUT)
                cout<<"ETIMEDOUT ret="<<ret<<endl;
        if (l_Errno == EWOULDBLOCK)
                cout<<"EWOULDBLOCK ret="<<ret<<endl;
        if (l_Errno == EINTR)
                cout<<"EINTR ret="<<ret<<endl;
        */
        ++count;
        tot += timer.ClockGetTime().GetTime() - test->time;
        if(count % 100 == 0)
                cout<<"Avg = "<<double(tot)/double(count)<<endl;

        usleep(5000);
}


        return 0;
}

How to Bind a Process to CPU in Linux

Linux Setting processor affinity for a certain task or process

When you are using SMP (Symmetric MultiProcessing) you might want to override the kernel's process scheduling and bind a certain process to a specific CPU(s).

But what is CPU affinity?

CPU affinity is nothing but a scheduler property that "bonds" a process to a given set of CPUs on the SMP system. The Linux scheduler will honor the given CPU affinity and the process will not run on any other CPUs. Note that the Linux scheduler also supports natural CPU affinity:
The scheduler attempts to keep processes on the same CPU as long as practical for performance reasons. Therefore, forcing a specific CPU affinity is useful only in certain applications. For example, application such as Oracle (ERP apps) use # of cpus per instance licensed. You can bound Oracle to specific CPU to avoid license problem. This is a really useful on large server having 4 or 8 CPUS

Setting processor affinity for a certain task or process using taskset command

taskset is used to set or retrieve the CPU affinity of a running process given its PID or to launch a new COMMAND with a given CPU affinity. However taskset is not installed by default. You need to install schedutils (Linux scheduler utilities) package.

Install schedutils

Debian Linux:
# apt-get install schedutils

Red Hat Enterprise Linux:
# up2date schedutils

OR
# rpm -ivh schedutils*

Under latest version of Debian / Ubuntu Linux taskset is installed by default using util-linux package.
The CPU affinity is represented as a bitmask, with the lowest order bit corresponding to the first logical CPU and the highest order bit corresponding to the last logical CPU. For example:
  • 0x00000001 is processor #0 (1st processor)
  • 0x00000003 is processors #0 and #1
  • 0x00000004 is processors #2 (3rd processor)
To set the processor affinity of process 13545 to processor #0 (1st processor) type following command:
# taskset 0x00000001 -p 13545

If you find a bitmask hard to use, then you can specify a numerical list of processors instead of a bitmask using -c flag:
# taskset -c 1 -p 13545
# taskset -c 3,4 -p 13545

Where,
  • -p : Operate on an existing PID and not launch a new task (default is to launch a new task)

Wednesday, November 7, 2012

DBUS

D-Bus is an inter-process communication (IPC) open-source system for software applications to communicate with one another. Heavily influenced by KDE 2–3's DCOP system, D-Bus has replaced DCOP in the KDE 4 release. An implementation of D-Bus supports most POSIX operating systems, and a port for Windows exists. It is used by Qt 4 and GNOME. In GNOME it has gradually replaced most parts of the earlier Bonobo mechanism.
Red Hat operates as the primary developer of D-Bus as part of the freedesktop.org project.

 Example

#define DBUS_API_SUBJECT_TO_CHANGE
#include <dbus/dbus.h>
#include <stdbool.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

/**
 * Connect to the DBUS bus and send a broadcast signal
 */
void sendsignal(char* sigvalue)
{
   DBusMessage* msg;
   DBusMessageIter args;
   DBusConnection* conn;
   DBusError err;
   int ret;
   dbus_uint32_t serial = 0;

   printf("Sending signal with value %s\n", sigvalue);

   // initialise the error value
   dbus_error_init(&err);

   // connect to the DBUS system bus, and check for errors
   conn = dbus_bus_get(DBUS_BUS_SYSTEM, &err);
   if (dbus_error_is_set(&err)) {
      fprintf(stderr, "Connection Error (%s)\n", err.message);
      dbus_error_free(&err);
   }
   if (NULL == conn) {
      exit(1);
   }

   // register our name on the bus, and check for errors
   ret = dbus_bus_request_name(conn, "test.signal.source", DBUS_NAME_FLAG_REPLACE_EXISTING , &err);
   if (dbus_error_is_set(&err)) {
      fprintf(stderr, "Name Error (%s)\n", err.message);
      dbus_error_free(&err);
   }
   if (DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER != ret) {
      exit(1);
   }

   // create a signal & check for errors
   msg = dbus_message_new_signal("/test/signal/Object", // object name of the signal
                                 "test.signal.Type", // interface name of the signal
                                 "Test"); // name of the signal
   if (NULL == msg)
   {
      fprintf(stderr, "Message Null\n");
      exit(1);
   }

   // append arguments onto signal
   dbus_message_iter_init_append(msg, &args);
   if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &sigvalue)) {
      fprintf(stderr, "Out Of Memory!\n");
      exit(1);
   }

   // send the message and flush the connection
   if (!dbus_connection_send(conn, msg, &serial)) {
      fprintf(stderr, "Out Of Memory!\n");
      exit(1);
   }
   dbus_connection_flush(conn);
  
   printf("Signal Sent\n");
  
   // free the message and close the connection
   dbus_message_unref(msg);
   dbus_connection_close(conn);
}

/**
 * Call a method on a remote object
 */
void query(char* param)
{
   DBusMessage* msg;
   DBusMessageIter args;
   DBusConnection* conn;
   DBusError err;
   DBusPendingCall* pending;
   int ret;
   bool stat;
   dbus_uint32_t level;

   printf("Calling remote method with %s\n", param);

   // initialiset the errors
   dbus_error_init(&err);

   // connect to the system bus and check for errors
   conn = dbus_bus_get(DBUS_BUS_SYSTEM, &err);
   if (dbus_error_is_set(&err)) {
      fprintf(stderr, "Connection Error (%s)\n", err.message);
      dbus_error_free(&err);
   }
   if (NULL == conn) {
      exit(1);
   }

   // request our name on the bus
   ret = dbus_bus_request_name(conn, "test.method.caller", DBUS_NAME_FLAG_REPLACE_EXISTING , &err);
   if (dbus_error_is_set(&err)) {
      fprintf(stderr, "Name Error (%s)\n", err.message);
      dbus_error_free(&err);
   }
   if (DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER != ret) {
      exit(1);
   }

   // create a new method call and check for errors
   msg = dbus_message_new_method_call("test.method.server", // target for the method call
                                      "/test/method/Object", // object to call on
                                      "test.method.Type", // interface to call on
                                      "Method"); // method name
   if (NULL == msg) {
      fprintf(stderr, "Message Null\n");
      exit(1);
   }

   // append arguments
   dbus_message_iter_init_append(msg, &args);
   if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &param)) {
      fprintf(stderr, "Out Of Memory!\n");
      exit(1);
   }
  
   // send message and get a handle for a reply
   if (!dbus_connection_send_with_reply (conn, msg, &pending, -1)) { // -1 is default timeout
      fprintf(stderr, "Out Of Memory!\n");
      exit(1);
   }
   if (NULL == pending) {
      fprintf(stderr, "Pending Call Null\n");
      exit(1);
   }
   dbus_connection_flush(conn);
  
   printf("Request Sent\n");
  
   // free message
   dbus_message_unref(msg);
  
   // block until we recieve a reply
   dbus_pending_call_block(pending);

   // get the reply message
   msg = dbus_pending_call_steal_reply(pending);
   if (NULL == msg) {
      fprintf(stderr, "Reply Null\n");
      exit(1);
   }
   // free the pending message handle
   dbus_pending_call_unref(pending);

   // read the parameters
   if (!dbus_message_iter_init(msg, &args))
      fprintf(stderr, "Message has no arguments!\n");
   else if (DBUS_TYPE_BOOLEAN != dbus_message_iter_get_arg_type(&args))
      fprintf(stderr, "Argument is not boolean!\n");
   else
      dbus_message_iter_get_basic(&args, &stat);

   if (!dbus_message_iter_next(&args))
      fprintf(stderr, "Message has too few arguments!\n");
   else if (DBUS_TYPE_UINT32 != dbus_message_iter_get_arg_type(&args))
      fprintf(stderr, "Argument is not int!\n");
   else
      dbus_message_iter_get_basic(&args, &level);

   printf("Got Reply: %d, %d\n", stat, level);
  
   // free reply and close connection
   dbus_message_unref(msg);  
   dbus_connection_close(conn);
}

void reply_to_method_call(DBusMessage* msg, DBusConnection* conn)
{
   DBusMessage* reply;
   DBusMessageIter args;
   bool stat = true;
   dbus_uint32_t level = 21614;
   dbus_uint32_t serial = 0;
   char* param = "";

   // read the arguments
   if (!dbus_message_iter_init(msg, &args))
      fprintf(stderr, "Message has no arguments!\n");
   else if (DBUS_TYPE_STRING != dbus_message_iter_get_arg_type(&args))
      fprintf(stderr, "Argument is not string!\n");
   else
      dbus_message_iter_get_basic(&args, &param);

   printf("Method called with %s\n", param);

   // create a reply from the message
   reply = dbus_message_new_method_return(msg);

   // add the arguments to the reply
   dbus_message_iter_init_append(reply, &args);
   if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_BOOLEAN, &stat)) {
      fprintf(stderr, "Out Of Memory!\n");
      exit(1);
   }
   if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_UINT32, &level)) {
      fprintf(stderr, "Out Of Memory!\n");
      exit(1);
   }

   // send the reply && flush the connection
   if (!dbus_connection_send(conn, reply, &serial)) {
      fprintf(stderr, "Out Of Memory!\n");
      exit(1);
   }
   dbus_connection_flush(conn);

   // free the reply
   dbus_message_unref(reply);
}

/**
 * Server that exposes a method call and waits for it to be called
 */
void listen()
{
   DBusMessage* msg;
   DBusMessage* reply;
   DBusMessageIter args;
   DBusConnection* conn;
   DBusError err;
   int ret;
   char* param;

   printf("Listening for method calls\n");

   // initialise the error
   dbus_error_init(&err);
  
   // connect to the bus and check for errors
   conn = dbus_bus_get(DBUS_BUS_SYSTEM, &err);
   if (dbus_error_is_set(&err)) {
      fprintf(stderr, "Connection Error (%s)\n", err.message);
      dbus_error_free(&err);
   }
   if (NULL == conn) {
      fprintf(stderr, "Connection Null\n");
      exit(1);
   }
  
   // request our name on the bus and check for errors
   ret = dbus_bus_request_name(conn, "test.method.server", DBUS_NAME_FLAG_REPLACE_EXISTING , &err);
   if (dbus_error_is_set(&err)) {
      fprintf(stderr, "Name Error (%s)\n", err.message);
      dbus_error_free(&err);
   }
   if (DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER != ret) {
      fprintf(stderr, "Not Primary Owner (%d)\n", ret);
      exit(1);
   }

   // loop, testing for new messages
   while (true) {
      // non blocking read of the next available message
      dbus_connection_read_write(conn, 0);
      msg = dbus_connection_pop_message(conn);

      // loop again if we haven't got a message
      if (NULL == msg) {
         sleep(1);
         continue;
      }
     
      // check this is a method call for the right interface & method
      if (dbus_message_is_method_call(msg, "test.method.Type", "Method"))
         reply_to_method_call(msg, conn);

      // free the message
      dbus_message_unref(msg);
   }

   // close the connection
   dbus_connection_close(conn);
}

/**
 * Listens for signals on the bus
 */
void receive()
{
   DBusMessage* msg;
   DBusMessageIter args;
   DBusConnection* conn;
   DBusError err;
   int ret;
   char* sigvalue;

   printf("Listening for signals\n");

   // initialise the errors
   dbus_error_init(&err);
  
   // connect to the bus and check for errors
   conn = dbus_bus_get(DBUS_BUS_SYSTEM, &err);
   if (dbus_error_is_set(&err)) {
      fprintf(stderr, "Connection Error (%s)\n", err.message);
      dbus_error_free(&err);
   }
   if (NULL == conn) {
      exit(1);
   }
  
   // request our name on the bus and check for errors
   ret = dbus_bus_request_name(conn, "test.signal.sink", DBUS_NAME_FLAG_REPLACE_EXISTING , &err);
   if (dbus_error_is_set(&err)) {
      fprintf(stderr, "Name Error (%s)\n", err.message);
      dbus_error_free(&err);
   }
   if (DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER != ret) {
      exit(1);
   }

   // add a rule for which messages we want to see
   dbus_bus_add_match(conn, "type='signal',interface='test.signal.Type'", &err); // see signals from the given interface
   dbus_connection_flush(conn);
   if (dbus_error_is_set(&err)) {
      fprintf(stderr, "Match Error (%s)\n", err.message);
      exit(1);
   }
   printf("Match rule sent\n");

   // loop listening for signals being emmitted
   while (true) {

      // non blocking read of the next available message
      dbus_connection_read_write(conn, 0);
      msg = dbus_connection_pop_message(conn);

      // loop again if we haven't read a message
      if (NULL == msg) {
         sleep(1);
         continue;
      }

      // check if the message is a signal from the correct interface and with the correct name
      if (dbus_message_is_signal(msg, "test.signal.Type", "Test")) {
        
         // read the parameters
         if (!dbus_message_iter_init(msg, &args))
            fprintf(stderr, "Message Has No Parameters\n");
         else if (DBUS_TYPE_STRING != dbus_message_iter_get_arg_type(&args))
            fprintf(stderr, "Argument is not string!\n");
         else
            dbus_message_iter_get_basic(&args, &sigvalue);
        
         printf("Got Signal with value %s\n", sigvalue);
      }

      // free the message
      dbus_message_unref(msg);
   }
   // close the connection
   dbus_connection_close(conn);
}

int main(int argc, char** argv)
{
   if (2 > argc) {
      printf ("Syntax: dbus-example [send|receive|listen|query] [<param>]\n");
      return 1;
   }
   char* param = "no param";
   if (3 >= argc && NULL != argv[2]) param = argv[2];
   if (0 == strcmp(argv[1], "send"))
      sendsignal(param);
   else if (0 == strcmp(argv[1], "receive"))
      receive();
   else if (0 == strcmp(argv[1], "listen"))
      listen();
   else if (0 == strcmp(argv[1], "query"))
      query(param);
   else {
      printf ("Syntax: dbus-example [send|receive|listen|query] [<param>]\n");
      return 1;
   }
   return 0;
}





If you get following Error


Listening for method calls
Name Error (Connection ":1.48" is not allowed to own the service "test.method.server" due to security policies in the configuration file)
Not Primary Owner (-1)





How to solve.

i have gone thru the "/etc/dbus-1/system.conf" and found these lines
<!-- Config files are placed here that among other things, punch
holes in the above policy for specific services. -->
<includedir>system.d</includedir>

<!-- This is included last so local configuration can override what's
in this standard file -->
<include ignore_missing="yes">system-local.conf</include>

::remove this line from config file
<include ignore_missing="yes">system-local.conf</include>



Then create
/etc/dbus-1/system.d/system-local.conf

<!-- This configuration file specifies the required security policies
     for Bluetooth core daemon to work. -->

<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN"
 "http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<busconfig>

  <!-- ../system.conf have denied everything, so we just punch some holes -->

<policy context="default">
<!-- Deny everything then punch holes -->
<allow send_interface="*"/>
<allow receive_interface="*"/>
<allow own="*"/>
<!-- But allow all users to connect -->
<allow user="*"/>
<!-- Allow anyone to talk to the message bus -->
<!-- FIXME I think currently these allow rules are always implicit
even if they aren't in here -->
<allow send_destination="org.freedesktop.DBus"/>
<allow receive_sender="org.freedesktop.DBus"/>
<!-- valid replies are always allowed -->
<allow send_requested_reply="true"/>
<allow receive_requested_reply="true"/>
</policy>

</busconfig>


Now should not receive above error :-D

 

Thursday, September 20, 2012

IP Forwarding in Linux

How to forward connection from one interface to another under linux

 

 Basicly you need to figure an external IP address on the "outside" interface and add iptables rule:

 

#Flush all iptable chains and start afresh
sudo iptables -F

 

 iptables -t nat -A PREROUTING -p tcp -d X.X.X.X --dport 8080 -j DNAT --to Y.Y.Y.Y:8080

 

 

X.X.X.X is the external address while Y.Y.Y.Y is the internal one running webserver. In that scenario you also have to make sure you are allowing the traffic in the forward chain:
iptables -A FORWARD -p tcp -d Y.Y.Y.Y --dport 8080 -j ACCEPT
Your box has to have forwarding enabled for this:
sysctl net.ipv4.ip_forward=1 
or
echo 1 > /proc/sys/net/ipv4/ip_forward 

Thursday, August 30, 2012

YUM Install

If you have problem with yum install.  [Trying other mirror.]
yum clean all
rm -f /var/lib/rpm/__db*
rpm --rebuilddb
yum -y install yumex
Doesn't matter if you use yum -y install yumex or yum install yumex -y.
       

Wednesday, August 1, 2012

PGP File Encryption

How to generate a key
 $ gpg --gen-key


How to check installed keys

$gpg --list-keys

How to delete installed keys

first need to delete  secret key
$ gpg --delete-secret-key prasad@gmail.com

Then delete the key
$ gpg --delete-key prasad@gmail.com

How to import a secret key
$ gpg --import  public-key


When importing a public key onto another machine, you may have configure gpg to
trust the key.  Otherwise, when you use the key to do encryption, you may
see a prompt like this:

 It is NOT certain that the key belongs to the person named
 in the user ID.  If you *really* know what you are doing,
 you may answer the next question with yes.

 Use this key anyway? (y/N)

To trust the key, run:
 gpg --edit-key NAME

GPG will output some information, and show a line like:
 trust: undefined     validity: unknown

You will be at a console, and you have to type "trust":
 Command> trust
 Please decide how far you trust this user to correctly verify other users' keys
 (by looking at passports, checking fingerprints from different sources, etc.)

   1 = I don't know or won't say
   2 = I do NOT trust
   3 = I trust marginally
   4 = I trust fully
   5 = I trust ultimately
   m = back to the main menu

 Your decision? 5
 Do you really want to set this key to ultimate trust? (y/N) y


Encrypting and decrypting documents



$ gpg --output doc.gpg --encrypt --recipient blake@cyb.org doc

The --recipient option is used once for each recipient and takes an extra argument specifying the public key to which the document should be encrypted. The encrypted document can only be decrypted by someone with a private key that complements one of the recipients' public keys. In particular, you cannot decrypt a document encrypted by you unless you included your own public key in the recipient list.

To decrypt a message the option --decrypt is used. You need the private key to which the message was encrypted. Similar to the encryption process, the document to decrypt is input, and the decrypted result is output.

gpg --output doc --decrypt doc.gpg


You need a passphrase to unlock the secret key for
user: "Blake (Executioner) <blake@cyb.org>"
1024-bit ELG-E key, ID 5C8CBD41, created 1999-06-04 (main key ID 9E98BC16)

Enter passphrase: 


Read more here

Download PGP for window form here

Tuesday, July 31, 2012

Bond Multiple Network Interfaces (NIC)

To learn more information read this

Step #1: Create a Bond0 Configuration File

Red Hat Enterprise Linux (and its clone such as CentOS) stores network configuration in /etc/sysconfig/network-scripts/ directory. First, you need to create a bond0 config file as follows:
# vi /etc/sysconfig/network-scripts/ifcfg-bond0

Append the following linest:


DEVICE=bond0
IPADDR=192.168.1.20
NETWORK=192.168.1.0
NETMASK=255.255.255.0
USERCTL=no
BOOTPROTO=none
ONBOOT=yes
BONDING_OPTS="mode=1 miimon=100"



You need to replace IP address with your actual setup. Save and close the file.

Step #2: Modify eth0 and eth1 config files

Open both configuration using a text editor such as vi/vim, and make sure file read as follows for eth0 interface
# vi /etc/sysconfig/network-scripts/ifcfg-eth0

Modify/append directive as follows:
DEVICE=eth0
USERCTL=no
ONBOOT=yes
MASTER=bond0
SLAVE=yes
BOOTPROTO=none

Open eth1 configuration file using vi text editor, enter:
# vi /etc/sysconfig/network-scripts/ifcfg-eth1

Make sure file read as follows for eth1 interface:
DEVICE=eth1
USERCTL=no
ONBOOT=yes
MASTER=bond0
SLAVE=yes
BOOTPROTO=none

Save and close the file.

Step # 3: Load bond driver/module

Make sure bonding module is loaded when the channel-bonding interface (bond0) is brought up. You need to modify kernel modules configuration file:
# vi /etc/modprobe.conf

Append following two lines:
alias bond0 bonding


Save file and exit to shell prompt. You can learn more about all bounding options by clicking here).

Step # 4: Test configuration

First, load the bonding module, enter:
# modprobe bonding

Restart the networking service in order to bring up bond0 interface, enter:
# service network restart

Make sure everything is working. Type the following cat command to query the current status of Linux kernel bounding driver, enter:
# cat /proc/net/bonding/bond0

Sample outputs:

Bonding Mode: fault-tolerance (active-backup)
MII Status: up
MII Polling Interval (ms): 100
Up Delay (ms): 200
Down Delay (ms): 200
Slave Interface: eth0
MII Status: up
Link Failure Count: 0
Permanent HW addr: 00:0c:29:c6:be:59
Slave Interface: eth1
MII Status: up
Link Failure Count: 0
Permanent HW addr: 00:0c:29:c6:be:63
To kist all network interfaces, enter:
# ifconfig

Sample outputs:

bond0     Link encap:Ethernet  HWaddr 00:0C:29:C6:BE:59
 inet addr:192.168.1.20  Bcast:192.168.1.255  Mask:255.255.255.0
 inet6 addr: fe80::200:ff:fe00:0/64 Scope:Link
 UP BROADCAST RUNNING MASTER MULTICAST  MTU:1500  Metric:1
 RX packets:2804 errors:0 dropped:0 overruns:0 frame:0
 TX packets:1879 errors:0 dropped:0 overruns:0 carrier:0
 collisions:0 txqueuelen:0
 RX bytes:250825 (244.9 KiB)  TX bytes:244683 (238.9 KiB)
eth0      Link encap:Ethernet  HWaddr 00:0C:29:C6:BE:59
 inet addr:192.168.1.20  Bcast:192.168.1.255  Mask:255.255.255.0
 inet6 addr: fe80::20c:29ff:fec6:be59/64 Scope:Link
 UP BROADCAST RUNNING SLAVE MULTICAST  MTU:1500  Metric:1
 RX packets:2809 errors:0 dropped:0 overruns:0 frame:0
 TX packets:1390 errors:0 dropped:0 overruns:0 carrier:0
 collisions:0 txqueuelen:1000
 RX bytes:251161 (245.2 KiB)  TX bytes:180289 (176.0 KiB)
 Interrupt:11 Base address:0x1400
eth1      Link encap:Ethernet  HWaddr 00:0C:29:C6:BE:59
 inet addr:192.168.1.20  Bcast:192.168.1.255  Mask:255.255.255.0
 inet6 addr: fe80::20c:29ff:fec6:be59/64 Scope:Link
 UP BROADCAST RUNNING SLAVE MULTICAST  MTU:1500  Metric:1
 RX packets:4 errors:0 dropped:0 overruns:0 frame:0
 TX packets:502 errors:0 dropped:0 overruns:0 carrier:0
 collisions:0 txqueuelen:1000
 RX bytes:258 (258.0 b)  TX bytes:66516 (64.9 KiB)
 Interrupt:10 Base address:0x1480

Monday, July 23, 2012

Persistence Static Routing

Red Hat (RHEL) / CentOS / Fedora Linux Persistence Static Routing

 Red Hat (RHEL) / CentOS / Fedora Linux Persistence Static Routing

You need to open /etc/sysconfig/network-scripts/route-eth0 file to define static routes for eth0 interface:

# cat /etc/sysconfig/network-scripts/route-eth0

Sample Output:

GATEWAY0=192.168.1.254
NETMASK0=255.255.255.0
ADDRESS0=192.168.55.0
GATEWAY1=10.164.234.112
NETMASK1= 255.255.255.240
ADDRESS1=10.164.234.132

Verify new routing table:
# route -n

How to configure a static ip in Linux

This is a newbie question I get quite often.

Configuring your Linux machine to run on a static IP is easy. Tools like system-config-network and netconfig provide you simple GUIs to do this.

For today, I’ll show you how to do this from the command line instead.

Navigate to /etc/sysconfig/network-scripts/


[root@baboo]# cd /etc/sysconfig/network-scripts/

Every network interface will have it’s own interface script file. eth0,eth1,eth2 and so on. Vi the ifcfg-eth0 interface script file for interface eth0. Replace the contents of the ifcfg-eth0 file with the parameters below.

 [root@baboo]# vi ifcfg-eth0.

DEVICE=eth1
BOOTPROTO=none
HWADDR=A4:BA:DB:2C:4F:58
ONBOOT=yes
HOTPLUG=no
TYPE=Ethernet
USERCTL=no
IPV6INIT=no
PEERDNS=yes
NETMASK=255.255.255.0
IPADDR=10.65.10.106
GATEWAY=10.65.10.254

Restart your interface to apply the changes.


[root@baboo]#ifdown eth0
[root@baboo]#ifup eth0

For further reading Click here

Friday, July 6, 2012

How to find Server model

Following peace of command will show all the hardware deatail of your system.
Run as root..

#/usr/sbin/dmidecode

Tuesday, May 22, 2012

Wednesday, May 9, 2012

Linux SHM

/dev/shm is nothing but implementation of traditional shared memoryconcept. It is an efficient means of passing data between programs. One program will create a memory portion, which other processes (if permitted) can access. This will result into speeding up things on Linux.


For example, if you have 8GB RAM then remount /dev/shm as follows:
# mount -o remount,size=8G /dev/shm

More about SHM

Monday, February 6, 2012

Network Time Protocol

The Network Time Protocol is defined in RFC1305 and allows the transfer and maintenance of time functions over distributed network systems. One of the most widely used NTP servers is ntpd (ntp.isc.org), which also provides Simple NTP (RFC2030) and is a common package of most Linux distributions. The NTP server figures out how much the system clock drifts and smoothly corrects it with delicate accuracy, as opposed to large adjustments once every few hours

How to sync time with another server.

How to check NTP server port accessible

Default udp port is 123
nc -zu <ip> <udpport>

OR

# nmap -p [port] -sU -P0 [host name | ip address]
# nmap -p 123 -sU -P0 example.com

Errors

ntpdate no server suitable for synchronization found

 

I was configuring one of head node of our cluster server to synchronise from our time server in our organisation, and in turn the head node becomes a NTP Server for the compute nodes that on a private IP addresses. As I was configuring the compute nodes and encounter "ntpdate[4933]: no server suitable for synchronization found"

I configured the ntp servers and ntp clients according to Setting up NTP Server for Local Network. And yet the error remain unresolved. Finally, I came across a solution

  1. Open /etc/ntp/step-tickers and replace with the name of your local NTP Server
  2. Open /etc/ntp/ntpservers and replace with the name of your local NTP Server
  3. Restart your ntp services. You should eradicate the problem
 More information; link1 link2

Sunday, January 29, 2012

SVN

How to checkout code from deep server

1. Make tunnel to deep server
ssh -L 4444:deepserver.dyndns.org:2222 10.65.1.75 -N

2. Add tunnel svn config file
open ~/.subversion/config and add
sshtunnel = ssh -qp 4444 under tunnels

3. Checkout code
svn co svn+sshtunnel://localhost/srv/svn/repositories/TradingSystem

http://tomorrowisfriday.wordpress.com/2007/11/28/tunneling-subversion-for-the-svnssh-protocol/

Monday, January 9, 2012

SSH

What Is SSH?

There are a couple of ways that you can access a shell (command line) remotely on most Linux/Unix systems. One of the older ways is to use the telnet program, which is available on most network capable operating systems. Accessing a shell account through the telnet method though poses a danger in that everything that you send or receive over that telnet session is visible in plain text on your local network, and the local network of the machine you are connecting to. So anyone who can "sniff" the connection in-between can see your username, password, email that you read, and commands that you run. For these reasons you need a more sophisticated program than telnet to connect to a remote host.



http://support.suso.com/supki/SSH_Tutorial_for_Linux

Monday, January 2, 2012

GCC

Build GCC 4.5

http://openwall.info/wiki/internal/gcc-local-build

Linux user configurations

Newtork Configuration
# system-config-network
# /etc/init.d/network restart


Start samba ...
$system-config-samba

Status samba
#/sbin/service smb status

Restart Samba
#/sbin/service smb restart

Add user (auto)
#/usr/sbin/useradd auto

Check user info of and user
#id auto

Add group
#/usr/sbin/groupadd auto

Add user to a group
#/usr/sbin/usermod -G groupname username

Give permition of directories
#chown -R username.groupname directory

Create VPN

How to Add new VPN account

log in to router using "ssh"

# en

# conf t //entering to configuration mode

# username priv password

Ex: username user1 priv 7 password userpwd // priv 7 for moderate privileges
Ex: username user1 priv 15 password userpwd // priv 15 for admin privileges

# end //exit from configuration mode

# exit //exit from router

To delete an existing VPN account


Use same syntax for creating account with "no" the beginning.
Ex: no username user1 priv 7 password userpwd

CISCO Switch

Useful commands to check configurations

  • sh run //show run
  • sh ip int br //show ip interface briefly
  • sh int br //to check duplex mode

How to bounce a cisco switch


  • Log in to the switch using "telnet".
  • Go to enable mode using "en".
  • Bounce switch using "reload".
How to bounce a interface in cisco switch

  • Log in to the switch using "telnet".
  • Go to enable mode using "en".
  • Go to configuration mode "conf t".
  • Then select particular interface "interface Gi2/0/46" .
  • Then "shutdown" and "no shutdown"
  • Exit from configuration mode using "exit".