Perşembe, Ekim 09, 2014

Bash Stuff


Postgresql komutlarını tek transaction içerisinde çalıştırma

psql \
    -X \
    -U myuser \
    -h myhost \
    -f /path/to/sql/file.sql \
    --echo-all \
    --single-transaction \
    --set AUTOCOMMIT=off \
    --set ON_ERROR_STOP=on \
    mydatabase

sql den gelen sonucu iterate etme

#!/bin/bash

set -e
set -u

PSQL=/usr/bin/psql

DB_USER=myuser
DB_HOST=myhost
DB_NAME=mydb

$PSQL \
    -X \
    -h $DB_HOST \
    -U $DB_USER \
    -c "select username, password, first_name, last_name from users" \
    --single-transaction \
    --set AUTOCOMMIT=off \
    --set ON_ERROR_STOP=on \
    --no-align \
    -t \
    --field-separator ' ' \
    --quiet \
    -d $DB_NAME \
| while read username password first_name last_name ; do
    echo "USER: $username $password $first_name $last_name"
done


Shell Tricks


Dosya içerisinde geçen tüm todo ları bulun

find . -name '*.java' -exec grep -i -H -n "todo" {} \;

Pazar, Eylül 07, 2014

.bashrc


alias memrss='while read command percent rss; do if [[ "${command}" != "COMMAND" ]]; then rss="$(bc <<< "scale=2;${rss}/1024")"; fi; printf "%-26s%-8s%s\n" "${command}" "${percent}" "${rss}"; done < <(ps -A --sort -rss -o comm,pmem,rss | head -n 11)'

Perşembe, Ağustos 28, 2014

Çoklu ping atma


aralık berlirterek

#!/bin/bashfor i in 192.168.0.{1..10}do ping -c 1 -t 1 "$i" >/dev/null 2>&1 && echo "Ping Status of $i : Success" || echo "Ping Status of $i : Failed"done

dosyadan okuyarak

while read hostnamedoping -c 1 -t 1 "$hostname" > /dev/null 2>&1 && echo "Ping Status of $hostname : Success" || echo "Ping Status of $hostname : Failed" done < host.txt

Çarşamba, Temmuz 23, 2014

Rabbit - Error: mnesia_unexpectedly_running


You need to copy the cookie from the node you trying to connect

  1. Let us use an example with 2 nodes: rabbit@node1 and rabbit@node2
  2. Go to rabbit@node1 and copy the cookie from cat /var/lib/rabbitmq/.erlang.cookie
  3. Go to rabbit@node2 remove the current cookie and paste the new one.


Execute the following commands on the same node


/usr/sbin/rabbitmqctl stop_app
/usr/sbin/rabbitmqctl reset
/usr/sbin/rabbitmqctl cluster rabbit@node1


Pazar, Temmuz 13, 2014

Centos 7 iptables.service failed to load: No such file or directory

iptables servisini çalıştırırken veya restart ederken bu hatayı alıyorsanız


# service iptables restart
Redirecting to /bin/systemctl start  iptables.service
Failed to issue method call: Unit iptables.service failed to load: No such file or directory.

bunun anlamı iptables-service paketi yüklü değil demektir.

# yum install iptables-services

Perşembe, Haziran 19, 2014

Create a yum Repository from the RHEL 6 DVD

Create a dvd.repo text file in /etc/yum.repos.d/ with the following content:

[dvd]
#mediaid=xxxxxxxxxx.xxxxxx
name=DVD for RHEL6
baseurl=file:///media/dvd/Server
enabled=1
gpgcheck=0

Cuma, Haziran 13, 2014

How to install Redis stable on Centos 6.5


wget http://download.redis.io/redis-stable.tar.gz 
tar xvzf redis-stable.tar.gz
 cd redis-stable
make
make install
cd utils
sh install_server.sh

How To Install PostgreSQL 9.3 on CentOS 6.5

Update your system

[root@centos]# yum update
 
Install tools needed for DB 

[root@centos]# yum install git wget 
[root@centos]# yum groupinstall "Development tools" 
 
Then finish PostgreSQL installation

[root@centos]# rpm -Uvh http://yum.postgresql.org/9.3/redhat/rhel-6-x86_64/pgdg-centos93-9.3-1.noarch.rpm
[root@centos]# yum install postgresql93-server postgresql93-contrib postgresql93-devel 
[root@centos]# service postgresql-9.3 initdb 
[root@centos]# chkconfig postgresql-9.3 on
 

Çarşamba, Haziran 04, 2014

elementary os(ubuntu 12.04) üzerine postgresql 9.3 kurulumu

$ echo "deb http://apt.postgresql.org/pub/repos/apt/ precise-pgdg main" > /etc/apt/sources.list.d/pgdg.list
$ wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -
$ sudo apt-get update
$ sudo apt-get install postgresql-9.3 postgresql-contrib-9.3


eğer bu tarz bi hata alırsanız

The following packages have ummet dependencies:
  postgresql-9.3 :  Depends: postgresql-client-9.3 but is not going to be installed
                    Depends: postgresql-common (>=1.4.2)...
  ...

postgresql-common u güncelleyip tekrar deneyin

$ sudo apt-get install postgresql-common=151.pgdg12.4+1
$ sudo apt-get install postgresql-9.3 postgresql-contrib-9.3

postgresql-common alternatifleri için

sudo apt-cache policy postgresql-common

elementary os(ubuntu 12.04) üzerine postgresql 9.3 kurulumu

Perşembe, Şubat 27, 2014

linux find komutu



boyutu 1 byte den küçük olanları sil

find . -size -1b -exec rm -rf {} \;

tarihi bugünden eski planları sil
find . -daystart -type f -mtime 1 -exec rm -f {} \;

Pazartesi, Şubat 24, 2014

Postgresql get running queries and kill a long running query


SELECT datname,procpid,current_query FROM pg_stat_activity;

template1=# SELECT datname,procpid,current_query FROM pg_stat_activity;
  datname  | procpid |                                   current_query                                  
-----------+---------+-----------------------------------------------------------------------------------
 pguser    |   22438 | in transaction
 template1 |   24692 | SELECT datname,procpid,current_query FROM pg_stat_activity;
(2 rows)

SELECT pg_cancel_backend(pid of the postgres process); 

deleting all pending tasks in celery

From the docs:
$ celeryctl purge
or
from celery.task.control import discard_all
discard_all()

Çarşamba, Şubat 19, 2014

django obj reference for processing in Inline

class RoomInline(admin.TabularInline):

    model = Room

    def formfield_for_foreignkey(self, db_field, request=None, **kwargs):

        field = super(RoomInline, self).formfield_for_foreignkey(db_field, request, **kwargs)

        if db_field.name == 'inside_room':
            if request._obj_ is not None:
                field.queryset = field.queryset.filter(building__exact = request._obj_)  
            else:
                field.queryset = field.queryset.none()

        return field



class BuildingAdmin(admin.ModelAdmin):

    inlines = (RoomInline,)

    def get_form(self, request, obj=None, **kwargs):
        # just save obj reference for future processing in Inline
        request._obj_ = obj
        return super(BuildingAdmin, self).get_form(request, obj, **kwargs)

Salı, Ocak 28, 2014

rename lots of redis keys with regex



önce

error-testtask_2405406e-98d4-45a0-874f-46131843520b

redis-cli keys "error-*" |awk '{print "redis-cli RENAME " $1 " " substr($0,7)}'|sh

sonra

testtask_2405406e-98d4-45a0-874f-46131843520b

Pazar, Ocak 05, 2014

Failover With KeepAlived

Network Scenario:
  1. LB1 Server: 192.168.10.111 ( eth1 )
  2. LB2 Server: 192.168.10.112 ( eth1 )
  3. Virtual IP: 192.168.10.121
Install Keepalived

Keepalived is available in centos base repository. Install it using yum command line tool.
# yum install keepalived
Keepalived configuration File: /etc/keepalived/keepalived.conf

Configure Keepalived on LB1.

Edit Keepalived configuration file on LB1 and add following configuration.
vrrp_instance VI_1 {
    interface eth1 state MASTER
    virtual_router_id 10
    priority 101 # 101 on master, 100 on backup
    virtual_ipaddress {
        192.168.10.121
    }
}
Configure Keepalived on LB2.

Edit Keepalived configuration file on LB2 and add following configuration.
vrrp_instance VI_1 {
    interface eth1 state BACKUP
    virtual_router_id 10
    priority 100 # 101 on master, 100 on backup
        virtual_ipaddress {
            192.168.10.121
        }
    }

1. Priority value will be higher on Master server, It doesn’t matter what you used in state. Ifyour state is MASTER but your priority is lower than the router with BACKUP, you will lose the MASTER state.
2. virtual_router_id should be same on both LB1 and LB2 servers.
3. By default single vrrp_instance support up to 20 virtual_ipaddress. In order to add more addresses you need to add more vrrp_instance
Start Keepalived

Start Keepalived service using following command and also configure to auto start on system boot.
# service keepalived start
# chkconfig keepalived on

Çarşamba, Ocak 01, 2014

PostgreSQL 9.1 Hot standby Kurulumu


kontrol makinesi : 192.168.2.5
master db : 192.168.101
slave db: 192.168.2.102

Bu yöntem ile yapılabilecekler.

  • Orjinal veritabanınızın bir kopyasına sahip olursunuz ve veri kaybınıönlemiş olursunuz.
  • Veritabanına gelen yükü dağıtabilirsiniz (Slave server üzerinde sadeceokuma amaçlı sorguları çalışıtrabilirsiniz )
  • Rapor amaçlı uzun süren sorguları slaver server üzerinde çalıştırarakperformans artışı sağlanabilir.

Bu yöntem ile neler yapılamaz
  • Sadece bir tabloyu, şemayı (schema) yada veritabanını kopyalayamazsınız.
  • Slave server orjinalin bire bir kopyası olmak zorundadır.
  • Birden fazla Master kopya olamaz.
  • PostgreSQL versiyonları farklı olamaz.

Kurulum

sudo apt-get install postgresql" 
yazarak postgresql in son sürümünü indirin.
Postgresql için kullanıcı adı ve şifrelerin ayarlanması için gereken terminal komutları
sudo -u postgres psql postgres
\password postgres
Master tarafında ki ayarlamalar
Master tarafında yapılan değişkilklikler. Master sunucu içerisinde ki ayar dosyalarındaki değişiklikleri yapın.
/etc/postgresql/9.1/main/postgresql.conf
listen_address = '*'
wal_level = hot_standby
max_wal_senders = 3

etc/postgresql/9.1/main/pg_hba.conf
host all all 192.168.2.5/32 md5
host replication all           192.168.2.102/32            trust

Veri klasörünün kopyalanması
öncelikle master veri tabanın da backup işlemini başlatın
pgadmin den veya psql den yazılabilir.
select pg_start_backup('backup');

Şimdi master sunucudaki postgresql in veri klasörünü, slave sunucudaki postgresql veri klasörüne kopyalamalısınız.
rsync -av 192.168.2.101:/var/lib/postgresql/9.1/main/ /var/lib/postgresql/9.1/main/
kopyalama işlemini yaptıktan sonra kopyalanan slave sunucudaki "postmaster.pid" dosyasını silin.
rm -rf /var/lib/postgresql/9.1/main/postmaster.pid 
veri klasörünün nerde olduğunu bulmak için pgadmin de aşağıdaki sql cümlesini yazıp çalıştırabilirsiniz.
show data_directory;
Son olarak master sunucudaki backup işlemini durdurmalısınız. Bunun için pgadmin de aşağıdakı sorguyu çalıştırın.
select pg_stop_backup();
Slave sunucu tarafında yapılan değişklikler

Slave sunucudaki postgresql veri klasörü içine "recovery.conf" adında bir dosya oluşturmalısınız.
Bu dosyaya aşağıdaki satırları yazın.

vi /var/lib/postgresql/9.1/recovery.conf

standby_mode='on'
primary_conninfo='host=192.168.2.101'
eğer salave sunucuda sorgu çalıştırmak istiyorsanız slave sunucuda aşağıdaki ayarı da yapın
/etc/postgresql/9.1/main/postgresql.conf

hot_standby = on

Son olarak yapmanız gereken slave sunucudaki postgresql servisini yeniden başlatmanız. Bunun için terminale aşağıdaki kodu yazın.
sudo /etc/init.d/postgresql restart