Archive for the ‘ How tos ’ Category

Linux – top 10 memory consuming processes

*Show top 10 memory consuming processes in descending order –

[daniel@kauai demo]$  ps havx | awk ' { print $8 " " $10}' | sort -nr  |head  -10
2267936 /usr/libexec/qemu-kvm
841588 /usr/libexec/qemu-kvm
400336 /opt/google/chrome/chrome
316424 /opt/google/chrome/chrome
299740 /opt/google/chrome/chrome
45640 /usr/bin/python
43748 /usr/sbin/named-sdb
39516 /usr/bin/Xorg
31724 libvirtd
24080 /usr/libexec/mysqld


*Continuously show top 10 every one second – Use Ctrl+C to stop.

[daniel@kauai demo]$ while (true); do ps havx | awk ' { print $8 " " $10}' | sort -nr  |head  -10; echo "..... " ; sleep 1 ; done
2267936 /usr/libexec/qemu-kvm
841540 /usr/libexec/qemu-kvm
401500 /opt/google/chrome/chrome
316360 /opt/google/chrome/chrome
300060 /opt/google/chrome/chrome
45640 /usr/bin/python
43748 /usr/sbin/named-sdb
39516 /usr/bin/Xorg
31724 libvirtd
24080 /usr/libexec/mysqld

..... 
2267936 /usr/libexec/qemu-kvm
841540 /usr/libexec/qemu-kvm
401500 /opt/google/chrome/chrome
316360 /opt/google/chrome/chrome
300060 /opt/google/chrome/chrome
45640 /usr/bin/python
43748 /usr/sbin/named-sdb
39516 /usr/bin/Xorg
31724 libvirtd
24080 /usr/libexec/mysqld

..... 
2267936 /usr/libexec/qemu-kvm
841540 /usr/libexec/qemu-kvm
401516 /opt/google/chrome/chrome
316360 /opt/google/chrome/chrome
300060 /opt/google/chrome/chrome
45640 /usr/bin/python
43748 /usr/sbin/named-sdb
39516 /usr/bin/Xorg
31724 libvirtd
24080 /usr/libexec/mysqld

..... 
2267936 /usr/libexec/qemu-kvm
841540 /usr/libexec/qemu-kvm
401528 /opt/google/chrome/chrome
316360 /opt/google/chrome/chrome
300060 /opt/google/chrome/chrome
43748 /usr/sbin/named-sdb
39516 /usr/bin/Xorg
31724 libvirtd
24080 /usr/libexec/mysqld
21260 gnome-terminal

..... 
^C
[daniel@kauai demo]$ 

Linux – empty or truncate files with strange names such as white space etc.

In Linux, it is very common to expect the files in the system to follow certain naming conventions – such as no white space, usually only lower cases, alphanumeric with underscore or dashes. But in some cases, you will find files which don’t follow this convention – the files might have been copied from other OSes such as Microsoft Windows or MacOS. Here is a trick to empty these files without deleting them.

Use the “truncate” command to empty files with non-standard names.

Requirement – empty files with white space in file name. Keep the files, just reduce the size to 0.

# find . -type f -exec ls -l {} \;
-rw-rw-r-- 1 nagios nagios 0 Dec 21 11:21 ./app/\var\log\messages
-rw-rw-r-- 1 nagios nagios 1359 Dec 19 06:26 ./puppet/\var\log\syslog
-rw-rw-r-- 1 nagios nagios 8071 Dec 15 02:30 ./ftp/Microsoft-Windows-EventCollector\Operational

# find . -type f -exec truncate -s 0 {} \;

# find . -type f -exec ls -l {} \;
-rw-rw-r-- 1 nagios nagios 0 Dec 21 11:27 ./app/\var\log\messages
-rw-rw-r-- 1 nagios nagios 0 Dec 21 11:27 ./puppet/\var\log\syslog
-rw-rw-r-- 1 nagios nagios 0 Dec 21 11:27 ./ftp/Microsoft-Windows-EventCollector\Operational

With the command

find . -type f -exec truncate -s 0 {} \;

, we were able to list all files in current directory and empty them.

C programming Language – Code snippets

C Programming Language, 2nd Edition

Compiling and running the sample codes using gcc :

gcc sample.c -o sample
./sample

Chapter 2 – Types, Operators and Expressions

1.Convert to lower case.

#include<stdio.h>

int main(int argc, char *argv[])

{

  while(*argv[1])
   {
     if(*argv[1] >='A' && *argv[1] <='Z') { putchar(*argv[1] + 'a' -'A'); *++argv[1]; }
     else
      {putchar(*argv[1]); *++argv[1]; }
   }

printf("\n");
return 0;
}

2. Get bits


#include<stdio.h>

unsigned getbits(unsigned x,int p, int n);

int main()

{
   int x=16;
   printf("%d\n",getbits(x,4,3));

return 0;
}

unsigned getbits(unsigned x, int p, int n)
 {
   return ( x >> (p+1-n)) & ~(~0 << n);
 }

3. Count one bits


#include<stdio.h>

int bitcount(unsigned x);
int main()

{
  unsigned short x=38;

  printf("%d has %d 1 bits\n",x,bitcount(x));
  return 0;
}

int bitcount(unsigned x)
 {
   int b;
   for(b=0; x!=0; x>>=1)
    if (x&1) b++;
  return b;
}

4. Remove character from string



#include<stdio.h>

int main(int argc, char *argv[])

{


if (argc !=3)  { printf("usage: del string char\n"); return -1;}

while(*argv[1])

{
   if(*argv[1] != *argv[2]) { putchar(*argv[1]); *++argv[1]; }
   else
   { *++argv[1]; continue; }
}
printf("\n");
return 0;

}

5. Convert x to binary


#include<stdio.h>
#define  LEN 16
int main()

{
  int x=112,counter=0;
  int binary[LEN]={0};
  while(x)
   {
     binary[counter]=x%2; x/=2; counter++;
   }
while(counter>=0) { printf("%d",binary[counter]); counter--; }
printf("\n");
return 0;
}

6. Convert char to integer

#include<stdio.h>

#define NUM 1

int main(int argc, char *argv[])

{
 int counter=1,n=0;

 if(argc!=2) { printf("usage: atoi arglist\n"); return -1;}

 while(*argv[NUM])
   {
      if(*argv[NUM]>='0' && *argv[NUM]<='9') { n=10*n+(*argv[NUM]-'0'); *++argv[NUM]; }
      else
       { *++argv[NUM]; continue; }
   }
 printf("number=%d\n",n);
 return 0;

 }

Reference –

https://www.amazon.com/Programming-Language-2nd-Brian-Kernighan/dp/0131103628#reader_0131103628

Linux – fast file search

Linux – fast file system search with locate and updatedb

Typically

find

command is the most commonly used search utility in Linux. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence.

There is an alternative and fast way of searching for files and directories in Linux though and that is the

locate

command, and it goes hand in had with the

updatedb

utility which keeps an indexed database of the files in your system. The locate tools simply reads the database created by updatedb.

Installation –

sudo apt-get -y install mlocate           [Debian/Ubuntu]
sudo yum -y install mlocate               [CentOS/Redhat]

updatedb is usually has a daily cron job to update the default database(‘/var/lib/mlocate/mlocate.db’). To manually update the database, you can manually run the ‘updatedb’ command first. That will take a while depending on the number of files you have on your system, the last time updatedb ran or other file related changes.

First time – update the default database, run any of the below command depending on your requirements. Most likely, the first and/or third command is what you need.

updatedb
updatedb -U /some/path      # if interested in indexing specific directory that you will search frequently.
updatedb -v                 # verbose mode

Time to search
locate command is the utility to search for entries in a mlocate database.

Some examples –

locate cron         # any file or directory with cron in its name
locate -i cron      # case insensitive
locate -c cron      # only print number of found entries
locate -r 'cron$'   # regex - only files or directories with names ending in cron.
locate -r '/usr/.*ipaddress.*whl$'   # regex for eg. /usr/share/python-wheels/ipaddress-0.0.0-py2.py3-none-any.whl

locate can also print the statistics on count of files, directories, size used by updatedb default directory.

root@cloudclient:/tmp# locate -S
Database /var/lib/mlocate/mlocate.db:
	28,339 directories
	185,661 files
	11,616,040 bytes in file names
	4,481,938 bytes used to store database

Customizing updatedb
updatedb can be customized to output the search database to a different file than the default db, in addition to this we can change the directory to index other than the default root tree. We can then tell locate to use the custom db.

In the below example, I am indexing the files under home directory in /tmp/home.db database, and then run locate to use this custom DB. As you can see the number of files and directories is way lower and thus the search much faster although since it has to scan specific directory.

$ updatedb -U ~ -o /tmp/home.db
$ locate -d /tmp/home.db cron
$ locate -d /tmp/home.db -S
Database /tmp/home.db:
	3,530 directories
	29,943 files
	2,635,675 bytes in file names
	762,621 bytes used to store database

References –

https://linux.die.net/man/8/updatedb

https://linux.die.net/man/1/locate

Infoblox dns api

Infoblox dns management – using the REST api with Python

Infoblox provides a product to manage your DNS, DHCP and IPAM through a single management interface. In this short article, I will walk you through automating some of the day to day operations work in managing DNS using Infoblox REST API. The REST based api tool can be also used to manage DHCP and IPAM.

The Infoblox WAPI is the REST interface we will interact with. In a highly available DNS setup, the WAPI requests go to the HA Grid Master IP or hostname. The requests typically have arguments and body. A great resource that helped me get started is a github repo of Infoblox Api python modules.

Clone the Infoblox Python modules repo to get started –

cd /tmp
git clone https://github.com/Infoblox-Development/Infoblox-API-Python.git

The class initialization of infoblox api (infoblox.py ) holds certain parameters, including ones used for authentication. Set this values according to your environment.

        """ Class initialization method
        :param iba_ipaddr: IBA IP address of management interface
        :param iba_user: IBA user name
        :param iba_password: IBA user password
        :param iba_wapi_version: IBA WAPI version (example: 1.0)
        :param iba_dns_view: IBA default view
        :param iba_network_view: IBA default network view
        :param iba_verify_ssl: IBA SSL certificate validation (example: False)
        """

Once you have the right parameters, you can write scripts which utilize the infoblox.py module. Here is a simple python script to get A record record details, given an IP address and domain.

Make sure you work under the directory where you cloned the infoblox github repo –

Script path: /tmp/get_a_record.py
Usage example: python /tmp/get_a_record.py 192.168.100.2  mail-gateway.example.net

Script to pull A record details of a DNS zone –

#!/usr/bin/env python

import infoblox
import sys
import requests
import json
import socket

def Usage():
    print "{0} {1} {2}".format(sys.argv[0], 'IP-ADDRESS','FQDN')
    sys.exit(1)

if len(sys.argv)<3:
    Usage()

myip=sys.argv[1]
myfqdn=sys.argv[2].lower()
try:
    socket.inet_aton(myip)
except:
    print "Not valid IP."
    sys.exit(1)

# Create a session
ibx_server='grid-master.example.net'
ibx_username='dns-admin'
ibx_password='admin-secret'
ibx_version='1.6'
ibx_dns_view='default'
ibx_net_view='default'

ibx=infoblox.Infoblox(ibx_server, ibx_username, ibx_password, ibx_version, ibx_dns_view, ibx_net_view, iba_verify_ssl=False)

# Get address details
payload='{"ipv4addr": '  + json.JSONEncoder().encode(myip) + ',' + '"name": ' + json.JSONEncoder().encode(myfqdn) + '}'
my_url='https://' + ibx.iba_host + '/wapi/v' + ibx.iba_wapi_version + '/record:a'
r = requests.get(url=my_url, auth=(ibx.iba_user, ibx.iba_password), verify=ibx.iba_verify_ssl, data=payload)
data = r.json()
print data

You can also use the existing class methods defined in the infoblox module. In the below example, I am using the ‘create_cname_record’ method to create an Alias.

ibx=infoblox.Infoblox(ibx_server, ibx_username, ibx_password, ibx_version, ibx_dns_view, ibx_net_view, iba_verify_ssl=False)
canonical='www.example.net'
name='web-server1.example.net'
ibx.create_cname_record(canonical, name)

If you can’t find the particular method in the infoblox module, it should’t be difficult to write one. Follow the api reference documentation on the structure of the WAPI Api calls.

Note – in some cases, you have to make multiple api calls to perform certain tasks. One example is updating the TTL for a DNS entry. On the first call, you need to get the host reference id and on second call update the TTL. The below example shows a simple python script to update the TTL (in seconds) for an existing FQDN entry.

Usage example - python update_ttl.py mail-gateway.example.net 600

update_ttl.py script –

#!/usr/bin/env python

import infoblox
import sys
import json
import requests

def Usage():
    print "{0} {1} {2}".format(sys.argv[0], 'ExistingFQDN', 'TTL')
    sys.exit(1)

if len(sys.argv)<3:
    Usage()

oldname=sys.argv[1].lower()
newttl=int(sys.argv[2])

# Create a session
ibx_server='grid-master.example.net'
ibx_username='dns-admin'
ibx_password='admin-secret'
ibx_version='1.6'
ibx_dns_view='default'
ibx_net_view='default'
ibx=infoblox.Infoblox(ibx_server, ibx_username, ibx_password, ibx_version, ibx_dns_view, ibx_net_view, iba_verify_ssl=False)
# Validate oldname exists
ibxhost=ibx.get_host(oldname)
if ibxhost['name'] != oldname:
    print oldname + " does not exist."
    sys.exit(1)
# update data
host_ref=ibxhost['_ref']
payload=json.dumps({'ttl':newttl})
my_url = 'https://' + ibx.iba_host + '/wapi/v' + ibx.iba_wapi_version + '/' + host_ref
r = requests.put(url=my_url, auth=(ibx.iba_user, ibx.iba_password), verify=ibx.iba_verify_ssl, data=payload)
if r.ok:
    print("TTL updated successfully.")
else:
    print("Error - {}".format(r.content))

References –

Products page – https://www.infoblox.com/products/dns/

Rest API documentation – https://www.infoblox.com/wp-content/uploads/infoblox-deployment-infoblox-rest-api.pdf

HA GRID MASTER – https://docs.infoblox.com/display/NAG8/Chapter+5+Deploying+a+Grid#Chapter5DeployingaGrid-bookmark587

Ansible : rolling upgrades or updates.

Making a change to live servers in production is something which has to be done with extreme care and planning. Several deployment types such as blue/green, canary, rolling update are in use today to minimize user impact. Ansible can be used to orchestrate a zero-downtime rolling change to a service.

A typical upgrade of an application, such as patching, might go like this –

  1. disable monitoring alerts for a node
  2. disable or pull out from load balancer
  3. make changes to server
  4. Reboot node
  5. wait for node to be UP and do sanity check
  6. put node back to load balancer
  7. turn on monitoring of node

Rinse and repeat.

Ansible would be a great choice in orchestrating above steps. Let us start with an inventory of web servers, a load balancer and a monitoring node with nagios –

[webservers]
web1.example.net
web2.example.net
web3.example.net
web4.example.net
web5.example.net

[balancer]
haproxy.example.net

[monitoring]
nagios.example.net

The web servers are running apache2, and we will patch apache and the kernel. For the patch to take effect, the servers need to be recycled. We will perform the patching one node at a time, wait for the node to be healthy and go to the next. The first portion of our playbook would be something like this –

---
- hosts: webservers
  serial: 1

  pre_tasks:
  - name: Stop apache service
    service: name=httpd state=stopped

  tasks:
  - name: update apache
    yum: name=httpd state=latest
  - name: Update Kernel
    yum: name=kernel state=latest
  - name: Reboot server
    shell: /sbin/reboot -r +1

  post_tasks:
  - name: Wait for webserver to come up
    wait_for: host={{ inventory_hostname }} port=80 state=started delay=65 timeout=300
    delegate_to: 127.0.0.1

I haven’t included the playbook tasks for disabling/enabling monitoring as well as removing/adding node to the load balancer. The procedures might differ depending on what type of monitoring system or load balancer technology you are using. In addition to this, the sanity check show is a simple port 80 probing, in reality a much more sophisticated validation can be done.

References –

http://docs.ansible.com/ansible/latest/playbooks_delegation.html

http://docs.ansible.com/ansible/latest/guide_rolling_upgrade.html