[linux] vim diff

Vim editor 에서 아래와 같이 vimdiff 로 alias가 걸려있음

Vimdiff A B 로 하면 둘을 비교해서 다른부분은 볼드체로 표시됨. 꿀~

컨트롤 WW 로 이동 가능염

그냥 VIM 에서는 :sp (split) 로 쪼갤수잇음.
Vim a.txt
:sp b.txt 입력

https://kldp.org/node/984

vimdiff 사용법
리눅스에서 두 파일을 비교하는 명령어인 vimdiff의 간단한 사용법을 말씀 드리겠습니다.
기본적으로 vimdiff는 vim에서 화면을 분할하고, 두 파일을 열었을 상태와 같다고 보시면 됩니다.
추가적으로 좋은 점은 서로 다른 부분을 표시해주는 부분이죠.
두 파일을 비교하고, 병합하는데 사용할 수 있습니다.
우선 분할된 창에서 다른 창으로 이동하는 명령은 Ctrl + w + w입니다.
차이점이 있는 부분으로 이동하는 명령은 ] + c 와 [ + c 입니다.
] + c는 현재 위치에서 아래쪽으로 탐색하며,
[ + c는 현재 위치에서 위쪽으로 탐색을 진행합니다.
수정을 원하는 부분을 찾았으면 복사를 해야겠지요.
d + o는 현재 위치에 반대쪽 창의 내용을 복사해 옵니다.
d + p는 현재 위치의 내용을 반대쪽 창에 복사합니다.
vimdiff는 동일한 부분은 생략하여 보여줍니다.
이를 펼치기 위해서는 z + o 또는 z + space를 누르면 됩니다.
반대로 접기 위해서는 z + c를 누르면 됩니다.
마지막으로, 한쪽 창의 내용을 편집하다보면 차이점을 나타내는 표시가 없어질 경우가 있습니다.
이때 :diffupdate를 누르시면 다시 비교하여, 차이점을 표시해 줍니다.

[linux] trickle 대역폭 제한

주로 ftp, rsync를 이용하여 데이터가 이동하는데 이런 프로그램의 대역폭을 trickle 프로그램으로

조절이 가능하다.

설치

root@smileserv-desktop:~# apt-get install trickle

패키지 목록을 읽는 중입니다완료

의존성 트리를 만드는 중입니다       

상태 정보를 읽는 중입니다완료

다음 패키지가 자동으로 설치되었지만 더 이상 필요하지 않습니다:

  linux-image-3.13.0-66-generic linux-image-3.13.0-68-generic

  linux-image-3.13.0-70-generic linux-image-3.13.0-71-generic

  linux-image-3.13.0-73-generic linux-image-3.13.0-74-generic

  linux-image-3.13.0-76-generic linux-image-extra-3.13.0-66-generic

  linux-image-extra-3.13.0-68-generic linux-image-extra-3.13.0-70-generic

  linux-image-extra-3.13.0-71-generic linux-image-extra-3.13.0-73-generic

  linux-image-extra-3.13.0-74-generic linux-image-extra-3.13.0-76-generic

Use ‘apt-get autoremove’ to remove them.

다음 새 패키지를 설치할 것입니다:

  trickle

0개 업그레이드, 1개 새로 설치, 0개 제거 및 116개 업그레이드 안 함.

0 바이트/34.6 k바이트 아카이브를 받아야 합니다.

이 작업 후 158 k바이트의 디스크 공간을 더 사용하게 됩니다.

Selecting previously unselected package trickle.

(데이터베이스 읽는중현재 648717개의 파일과 디렉터리가 설치되어 있습니다.)

Preparing to unpack …/trickle_1.07-10ubuntu2_amd64.deb …

Unpacking trickle (1.07-10ubuntu2) …

Processing triggers for man-db (2.6.7.1-1ubuntu1) …

trickle (1.07-10ubuntu2) 설정하는 중입니다

# debian 계열 ubuntu 14.04 에서 apt-get install 명령어로 쉽게 설치가 가능하다

[root@controller ~]#  yum install epel-release

Loaded plugins: fastestmirror

Loading mirror speeds from cached hostfile

 * base: data.nicehosting.co.kr

 * extras: ftp.daumkakao.com

 * updates: data.nicehosting.co.kr

Resolving Dependencies

–> Running transaction check

—> Package epel-release.noarch 0:7-5 will be installed

–> Finished Dependency Resolution

Dependencies Resolved

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

 Package                                                Arch                                             Version                                          Repository                                        Size

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

Installing:

 epel-release                                           noarch                                           7-5                                              extras                                            14 k

Transaction Summary

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

Install  1 Package

Total download size: 14 k

Installed size: 24 k

Is this ok [y/d/N]: y

Downloading packages:

epel-release-7-5.noarch.rpm                                                                                                                                                               |  14 kB  00:00:00

Running transaction check

Running transaction test

Transaction test succeeded

Running transaction

  Installing : epel-release-7-5.noarch                                                                                                                                                                       1/1

  Verifying  : epel-release-7-5.noarch                                                                                                                                                                       1/1

Installed:

  epel-release.noarch 0:7-5

Complete!

[root@controller ~]# yum install trickle

Loaded plugins: fastestmirror

epel/x86_64/metalink                                                                                                                                                                      | 5.3 kB  00:00:00

epel                                                                                                                                                                                      | 4.3 kB  00:00:00

(1/3): epel/x86_64/group_gz                                                                                                                                                               | 169 kB  00:00:00

(2/3): epel/x86_64/primary_db                                                                                                                                                             | 3.9 MB  00:00:00

(3/3): epel/x86_64/updateinfo                                                                                                                                                             | 493 kB  00:00:05

Loading mirror speeds from cached hostfile

 * base: data.nicehosting.co.kr

 * epel: ftp.riken.jp

 * extras: ftp.daumkakao.com

 * updates: data.nicehosting.co.kr

Resolving Dependencies

–> Running transaction check

—> Package trickle.x86_64 0:1.07-19.el7 will be installed

–> Finished Dependency Resolution

Dependencies Resolved

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

 Package                                           Arch                                             Version                                                 Repository                                      Size

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

Installing:

 trickle                                           x86_64                                           1.07-19.el7                                             epel                                            48 k

Transaction Summary

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

Install  1 Package

Total download size: 48 k

Installed size: 103 k

Is this ok [y/d/N]: y

Downloading packages:

warning: /var/cache/yum/x86_64/7/epel/packages/trickle-1.07-19.el7.x86_64.rpm: Header V3 RSA/SHA256 Signature, key ID 352c64e5: NOKEY

Public key for trickle-1.07-19.el7.x86_64.rpm is not installed

trickle-1.07-19.el7.x86_64.rpm                                                                                                                                                            |  48 kB  00:00:00

Retrieving key from file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7

Importing GPG key 0x352C64E5:

 Userid     : “Fedora EPEL (7) <epel@fedoraproject.org>”

 Fingerprint: 91e9 7d7c 4a5e 96f1 7f3e 888f 6a2f aea2 352c 64e5

 Package    : epel-release-7-5.noarch (@extras)

 From       : /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7

Is this ok [y/N]: y

Running transaction check

Running transaction test

Transaction test succeeded

Running transaction

  Installing : trickle-1.07-19.el7.x86_64                                                                                                                                                                    1/1

  Verifying  : trickle-1.07-19.el7.x86_64                                                                                                                                                                    1/1

Installed:

  trickle.x86_64 0:1.07-19.el7

Complete!

# redhat 계열 CentOS 7에서는 epel repository를 설치하고 yum 설치가 가능하다.

– ftp 트래픽 조절

# trickle 사용전

root@smileserv-desktop:~# lftp -u SND xxx.xxx.xxx.xxx

비밀번호

lftp SDN@xxx.xxx.xxx.xxx:~> cd smileserv/Linux_iso/    

lftp SDN@xxx.xxx.xxx.xxx:~/smileserv/Linux_iso> get CentOS\ 7\ x86_64-0.iso

`CentOS 7 x86_64-0.iso’ at 132024912 (3%) 9.19M/초 남은시간:7m [자료 받는 중]

# trickle 사용후

root@smileserv-desktop:~# trickle -s -u 1000 -d 1000 lftp -u SND 211.55.113.55

lftp SDN@xxx.xxx.xxx.xxx:~> cd smileserv/Linux_iso/

lftp SDN@xxx.xxx.xxx.xxx:~/smileserv/Linux_iso> get -c CentOS\ 7\ x86_64-0.iso

`CentOS 7 x86_64-0.iso’ at 192482168 (4%) 1.07M/초 남은시간:61m [자료 받는 중]

# 사용법은 명령어 전에 trickle을 붙여주는 것이며 -u, -d옵션으로 Kbyte 단위의 업, 다운로드

 대역폭 할당이 가능하다.

[Nginx] Rewrite Rule

nginx rewrite

도메인이 www 로 시작하지 않는 것을 www로 가게

Query Parameter 삭제

      • nginx rewrite는 rewrite 후에 쿼리 파라미터를 자동으로 붙여버린다.
      • 쿼리 파라미터가 붙는 것을 막으려면 타겟 URL의 끝에 물음표(?)가 있어야 한다.
        rewrite ^ http://www.example.com/? last; # 쿼리 파라미터를 무시하고 무조건 http://www.example.com 으로 보내버림

http로 온 것을 모두 https

[linux] sudo 커맨드 환경 변수 (env) 등록

아래와 같이 sudo env 명령을 사용하면 된다.

 

아래 예시는 sudo 명령어 자체에 alias를 설정하는 과정이며,

Centos6 에서 python27을 사용하기 위해 rh 의 LIBRARY 를 PATH에 등록하는 과정이다.

 

alias sudo=’sudo env PATH=/opt/rh/python27/root/usr/bin${PATH:+:${PATH}} LD_LIBRARY_PATH=/opt/rh/python27/root/usr/lib64${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}} XDG_DATA_DIRS=/opt/rh/python27/root/usr/    share${XDG_DATA_DIRS:+:${XDG_DATA_DIRS}}  PKG_CONFIG_PATH=/opt/rh/python27/root/usr/lib64/pkgconfig${PKG_CONFIG_PATH:+:${PKG_CONFIG_PATH}}’

[기타] 신뢰할수 있는 루트 인증서 등록 하는 법

Mac OS X

Add

Use command:

sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ~/new-root-certificate.crt

Remove

Use command:

sudo security delete-certificate -c “<name of existing certificate>”

Windows

Add

Use command:

certutil -addstore -f “ROOT” new-root-certificate.crt

Remove

Use command:

certutil -delstore “ROOT” serial-number-hex

Linux (Ubuntu, Debian)

Add

  1. Copy your CA to dir /usr/local/share/ca-certificates/
  2. Use command:

sudo cp foo.crt /usr/local/share/ca-certificates/foo.crt

  1. Update the CA store:

sudo update-ca-certificates

Remove

  1. Remove your CA.
  2. Update the CA store:

sudo update-ca-certificates –fresh

Restart Kerio Connect to reload the certificates in the 32-bit versions or Debian 7.

Linux (CentOs 6)

Add

  1. Install the ca-certificates package:

yum install ca-certificates

  1. Enable the dynamic CA configuration feature:

update-ca-trust force-enable

  1. Add it as a new file to /etc/pki/ca-trust/source/anchors/:

cp foo.crt /etc/pki/ca-trust/source/anchors/

  1. Use command:

update-ca-trust extract

Restart Kerio Connect to reload the certificates in the 32-bit version.

Linux (CentOs 5)

Add

Append your trusted certificate to file /etc/pki/tls/certs/ca-bundle.crt

cat foo.crt >> /etc/pki/tls/certs/ca-bundle.crt

Restart Kerio Connect to reload the certificates in the 32-bit version.

[linux] redis clustering (redis-trib 이용)

redis 3.0 이상 필요.

설치하고 난 뒤에 다음과 같이 redis.conf를 변경해줍니다.

daemonize yes

pidfile /var/run/redis.pid

port 6379

tcp-backlog 511

timeout 0

tcp-keepalive 0

loglevel notice

logfile “/services/log/redis/redis.log”

databases 16

save 900 1

save 300 10

save 60 10000

stop-writes-on-bgsave-error yes

rdbcompression yes

rdbchecksum yes

dbfilename dump.rdb

dir /services/data/redis/

slave-serve-stale-data yes

slave-read-only yes

repl-diskless-sync no

repl-diskless-sync-delay 5

repl-disable-tcp-nodelay no

slave-priority 100

appendonly yes

appendfilename “appendonly.aof”

appendfsync everysec

no-appendfsync-on-rewrite no

auto-aof-rewrite-percentage 100

auto-aof-rewrite-min-size 64mb

aof-load-truncated yes

lua-time-limit 5000

cluster-enabled yes

cluster-node-timeout 2000

cluster-slave-validity-factor 1

cluster-config-file nodes.conf

slowlog-log-slower-than 10000

slowlog-max-len 128

latency-monitor-threshold 0

notify-keyspace-events “”

hash-max-ziplist-entries 512

hash-max-ziplist-value 64

list-max-ziplist-entries 512

list-max-ziplist-value 64

set-max-intset-entries 512

zset-max-ziplist-entries 128

zset-max-ziplist-value 64

hll-sparse-max-bytes 3000

activerehashing yes

client-output-buffer-limit normal 0 0 0

client-output-buffer-limit slave 256mb 64mb 60

client-output-buffer-limit pubsub 32mb 8mb 60

hz 10

aof-rewrite-incremental-fsync yes

그 다음 루비루비젬을 설치해주고, redis 를 설치해줘야 한다그래야 클러스터 관련 스크립트가 실행됨 (include redis)

yum install ruby rubygem

gem install –http-proxy http://10.10.10.100:8080 redis

이후 레디스 소스파일이 위치한 경로에 src 폴더안에 redis-trib.rb 를 이용하면된다.

명령어

for i in $(cat centos_redis30.txt);do ssh $i “hostname;yum install ruby rubygem -y”;done

for i in $(cat centos_redis30.txt);do ssh $i “hostname;gem install –http-proxy http://10.10.10.100:8080 redis “;done

설정파일은 master / slave 구분없이 동일하므로 scp로 넣어준다.

설정 파일 복사 후 적용을 위해서 service redis restart

그다음 1번 서버에서 다음과 같은 명령어를 날려준다.

echo yes | /services/src/redis-3.0.1/src/redis-trib.rb create –replicas 1 10.10.10.21:6379 10.10.10.22:6379 10.10.10.23:6379 10.10.10.24:6379 10.10.10.25:6379 10.10.10.26:6379

(클러스터링 및 리플리카를  M M M S S S 순으로 넣어줍니다. )

레디스 클러스터링에서는

사용 포트가 서비스포트 + 10000번이 자동 할당된다.

해당 포트를 통해서 redis clustering command 가 실행되며해당 포트를열지 않으면클러스터링이 안됨.

.

Redis-trib 사용법

Redis-trib 사용법

http://download.redis.io/redis-stable/src/redis-trib.rb

명령 설명

o    create   클러스터를 생성한다. replicas 지정해서 슬레이브 개수를 지정할  있다.

o    reshard   슬롯을 노드에 할당 또는 재할당한다. Source 노드와 destination 노드를 지정한다.

o    add-node   클러스터에 노드를 추가한다마스터 또는 슬레이브로 추가할  있다.

o    del-node   클러스터에서 노드를 제거한다.

redis-trib CREATE

o    클러스터를 생성한다.

o    명령   redis-trib.rb create [–replicas n] ip1:port1 … ipn:portn

o    –replicas n   마스터  슬레이브 노드를   만들지를 정한다.   생략하거나 0으로 설정하면 슬레이브 노드를 만들지 않고 마스터로만 클러스터를 구성한다.  

o    ip1:port1 … ipn:portn   클러스터에 참여할 레디스 노드들의 ip:port 입력한다.   명령을 실행하는 머신과 같은 ip 사용해도 ip 반드시 입력해야 한다.

o    Standalone mode 시작한 레디스는 클러스터에 참여할  없다.   지정한 ip:port  standalone mode Redis-trib 종료한다.

o    DB 데이터가 있으면 클러스터를 생성하지 못하고 종료한다.   그러므로 클러스터를 생성할 노드는 AOF  RDB 부터 데이터를 읽어들이면 안된다.   Cluster mode 시작한 레디스는 클러스터가 구성되지 않은 상태에서는 set 명령같은 데이터를 입력/수정/삭제/조회하는 명령을 수행할  없다.   하지만 Flushdb 또는 flushall 명령은 실행가능하다 명령을 실행해서 데이터를 모두 삭제했어도 클러스터는 구성되지 않는다처음부터 데이터를 읽어 들이지 않는 방법이 가장 좋다.

o    레디스 노드는 최소 3 이상을 지정해야 한다.   Replicas 0으로 지정하면 참여한 노드가 모두 마스터가 된다.   Replicas 1 지정하면 최소 마스터슬레이브 3쌍으로 구성되어 6노드 이상이 있어야 한다.   Cluster 명령을 직접 사용하면 이러한 제한은 없어서, 1 노드로도 클러스터를 만들  있다.

o    IP 같은 경우 클러스터 구성   IP 같으면 명령에 지정된 순서대로 마스터와 슬레이브가 정해진다.

o    다음과 같이 replicas 1 지정하고 5001부터 5006까지 포트를 지정하면 아래와 같이 구성된다.

$ src/redis-trib.rb create –replicas 1 127.0.0.1:5001 127.0.0.1:5002 127.0.0.1:5003 127.0.0.1:5004 127.0.0.1:5005 127.0.0.1:5006

설명: Redis Cluster Create redis_trib

o    replicas 2 지정하고 9 노드를 지정하면 다음과 같이 구성된다.

설명: Redis Cluster Create redis-trib replicas 2

o    3 IP 레디스 노드 2개씩 지정하고 replicas 1 하면 다음과 같이 구성된다.   세번째 박스(IP 105)  박스안에 마스터슬레이브가 구성되었으므로  박스가 다운되면 클러스터가 다운되는 상황이 된다.

설명: Redis Cluster Create redis_trib 3boxes 6nodes

o    redis-trib 클러스터 구성을   하려고 하지만완벽하지 않아서 위와 같은 상황이 발생할  있으므로세밀한 구성을 위해서는 클러스터 명령으로 직접 구성하는 것이 좋은 방법이다.

o    redis-trib create했을때 구성 형태에 대한 자세한 내용은 여기를 보세요.   레디스 클러스터 자동 구성 형태

o    다음은 6 노드로 마스터 3, 슬레이브 3으로 구성했을때 나오는 메시지이다.   redis 3.0.2 포한된 redis-trib.rb 실행한 것이다.    길지만 생략하지 않고 그대로 보여준다.

$ src/redis-trib.rb create –replicas 1 127.0.0.1:5001 127.0.0.1:5002 127.0.0.1:5003 127.0.0.1:5004 127.0.0.1:5005 127.0.0.1:5006

>>> Creating cluster

Connecting to node 127.0.0.1:5001: OK

Connecting to node 127.0.0.1:5002: OK

Connecting to node 127.0.0.1:5003: OK

Connecting to node 127.0.0.1:5004: OK

Connecting to node 127.0.0.1:5005: OK

Connecting to node 127.0.0.1:5006: OK

>>> Performing hash slots allocation on 6 nodes…

Using 3 masters:

127.0.0.1:5001

127.0.0.1:5002

127.0.0.1:5003

Adding replica 127.0.0.1:5004 to 127.0.0.1:5001

Adding replica 127.0.0.1:5005 to 127.0.0.1:5002

Adding replica 127.0.0.1:5006 to 127.0.0.1:5003

M: a2c1abd1e2db46fe31beed7e4d40f81cc8abe28d 127.0.0.1:5001

     slots:0-5460 (5461 slots) master

M: ed6274c72384c208154e9f06e3c40a7f893197f6 127.0.0.1:5002

     slots:5461-10922 (5462 slots) master

M: 4c385777933bf54eb0636ebe7bda4903e0da0ade 127.0.0.1:5003

     slots:10923-16383 (5461 slots) master

S: 813e57347d2de9f3a9f36f7846642a5732c1519e 127.0.0.1:5004

     replicates a2c1abd1e2db46fe31beed7e4d40f81cc8abe28d

S: cfd9827e915e79c4550afddad2b546c3d1298872 127.0.0.1:5005

     replicates ed6274c72384c208154e9f06e3c40a7f893197f6

S: d324144ecfb33f75ef5e90b47388423f0656ab95 127.0.0.1:5006

     replicates 4c385777933bf54eb0636ebe7bda4903e0da0ade

Can I set the above configuration? (type ‘yes’ to accept): yes

>>> Nodes configuration updated

>>> Assign a different config epoch to each node

>>> Sending CLUSTER MEET messages to join the cluster

Waiting for the cluster to join…

>>> Performing Cluster Check (using node 127.0.0.1:5001)

M: a2c1abd1e2db46fe31beed7e4d40f81cc8abe28d 127.0.0.1:5001

     slots:0-5460 (5461 slots) master

M: ed6274c72384c208154e9f06e3c40a7f893197f6 127.0.0.1:5002

     slots:5461-10922 (5462 slots) master

M: 4c385777933bf54eb0636ebe7bda4903e0da0ade 127.0.0.1:5003

     slots:10923-16383 (5461 slots) master

M: 813e57347d2de9f3a9f36f7846642a5732c1519e 127.0.0.1:5004

     slots: (0 slots) master

     replicates a2c1abd1e2db46fe31beed7e4d40f81cc8abe28d

M: cfd9827e915e79c4550afddad2b546c3d1298872 127.0.0.1:5005

     slots: (0 slots) master

     replicates ed6274c72384c208154e9f06e3c40a7f893197f6

M: d324144ecfb33f75ef5e90b47388423f0656ab95 127.0.0.1:5006

     slots: (0 slots) master

     replicates 4c385777933bf54eb0636ebe7bda4903e0da0ade

[OK] All nodes agree about slots configuration.

>>> Check for open slots…

>>> Check slots coverage…

[OK] All 16384 slots covered.

redis-trib RESHARD

o    슬롯을 재할당한다슬롯과 데이터를 같이 옮겨준다.

o    명령   redis-trib.rb reshard ip:port

o    ip:port 접속해서 작업할 노드이다. Reshard  source 노드나 destination 노드로 접속할 필요는 없다.

o    Reshard  노드를 추가했을때  노드에 슬롯을 할당하기 위해 사용하거나기존 노드의 슬롯을 다른 노드로 옮길때 사용한다.   Reshard 명령은 destination 노드로 데이터를 migrate 명령으로 옮긴다.

o    Source 노드는 1 이상 또는 모두를 지정할  있고, destination 노드는 하나만 지정한다.   옮길 슬롯의 개수를 지정한다특정 슬롯을 지정하거나 특정 범위를 지정할  없다.

o    다음은 reshard할때 나오는 메시지이다옮길 슬롯의 갯수만큼 메시지가 나오므로여기서는 5 슬롯만 지정했다.   Source node #1 에서 all 입력하면 모든 노드로 부터 슬롯을 받는다.   특정 노드 id 여러개 입력할  있다모두 입력했으면 done 입력한다.   Source node  Destination(Receiving) node 모두 마스터 노드만 지정해야 된다슬레이브 노드는 지정할  없다.   입력해야  부분은 굵게 표시했다.

redis-trib.rb reshard 127.0.0.1:5001

>>> Performing Cluster Check (using node 127.0.0.1:5001)

[OK] All nodes agree about slots configuration.

>>> Check for open slots…

>>> Check slots coverage…

[OK] All 16384 slots covered.

How many slots do you want to move (from 1 to 16384)? 5

What is the receiving node ID? 4c385777933bf54eb0636ebe7bda4903e0da0ade

Please enter all the source node IDs.

  Type ‘all’ to use all the nodes as source nodes for the hash slots.

  Type ‘done’ once you entered all the source nodes IDs.

Source node #1:a2c1abd1e2db46fe31beed7e4d40f81cc8abe28d

Source node #2:done

Ready to move 5 slots.

Do you want to proceed with the proposed reshard plan (yes/no)? yes

Moving slot 0 from 127.0.0.1:5001 to 127.0.0.1:5003:

Moving slot 1 from 127.0.0.1:5001 to 127.0.0.1:5003:

Moving slot 2 from 127.0.0.1:5001 to 127.0.0.1:5003:

Moving slot 3 from 127.0.0.1:5001 to 127.0.0.1:5003:

Moving slot 4 from 127.0.0.1:5001 to 127.0.0.1:5003:

redis-trib ADD-NODE

o    클러스터에 노드를 추가한다마스터 또는 슬레이브로 추가할  있다.

o    명령   redis-trib.rb add-node [–slave] [–master-id id] new_ip:port existing_ip:port

o    –slave    노드를 슬레이브로 추가할  사용한다지정하지 않으면 마스터로 추가된다.

o    –master-id id   slave 옵션을 사용했을때 마스터 노드 ID 지정한다생략할  있다생략하면 existing_ip:port 노드의 슬레이브가 된다.

o    new_ip:port   추가할 ip:port 지정한다. Cluster mode 시작되어 있어야 하고데이터가 없어야 한다.

o    existing_ip:port   접속해서 작업할 기존 노드를 지정한다.

o    다음은 5007 노드를 마스터로 클러스터에 등록하는 명령과 메시지이다.   중간에 입력해야 하는 것은 없다.   이후에 reshard 명령으로 슬롯을 할당해야 마스터로서 역할을 수행할  있다.

redis-trib.rb add-node 127.0.0.1:5007 127.0.0.1:5001

>>> Adding node 127.0.0.1:5007 to cluster 127.0.0.1:5001

>>> Performing Cluster Check (using node 127.0.0.1:5001)

[OK] All nodes agree about slots configuration.

>>> Check for open slots…

>>> Check slots coverage…

[OK] All 16384 slots covered.

Connecting to node 127.0.0.1:5007: OK

>>> Send CLUSTER MEET to node 127.0.0.1:5007 to make it join the cluster.

[OK] New node added correctly.

o    다음은 5007 노드를 5002 슬레이브로 등록하는 명령이다마지막에 다른 부분만 표시한다.  

redis-trib.rb add-node –slave 127.0.0.1:5007 127.0.0.1:5002

>>> Adding node 127.0.0.1:5007 to cluster 127.0.0.1:5002

….. 중간 생략 …..

[OK] All 16384 slots covered.

Automatically selected master 127.0.0.1:5002

Connecting to node 127.0.0.1:5007: OK

>>> Send CLUSTER MEET to node 127.0.0.1:5007 to make it join the cluster.

Waiting for the cluster to join.

>>> Configure node as replica of 127.0.0.1:5002.

[OK] New node added correctly.

o    다음은 master-id 옵션을 지정한 명령 예이다.

$ redis-trib.rb add-node –slave –master-id 3c3a0c74aae0b56170ccb03a76b60cfe7dc1912e 127.0.0.1:5007 127.0.0.1:5001

redis-trib DEL-NODE

o    클러스터에서 노드를 제거한다.   슬롯이 할당되어 있으면 제거할  없다.   Reshard 명령으로 슬롯과 데이터를 다른 노드에 할당한  del-node 명령을 실행한다.   제거할 노드가 슬레이브면 reshard  필요없다.

o    명령   redis-trib.rb del-node ip:port node-id

o    ip:port   접속해서 작업할 노드를 지정한다.

o    node-id   제거할 노드 ID 지정한다.

o     명령은 마지막에 레디스 인스턴스를 shutdown 한다.

o    다운된 노드에 대해서는  명령을 실행할  없다.   왜냐하면  명령은 해당 노드에 접속해서 확인  진행하는데접속할  없기 때문이다.   이때는 redis-cli 접속해서 cluster forget node-id 명령으로 제거한다.

o    다음은 5001번에 접속해서 5007 노드를 제거하는 명령과 메시지다.

redis-trib.rb del-node 127.0.0.1:5001 b8b8b72fb2b5305ad63290bb1aa24cf81fce1bc2

>>> Removing node b8b8b72fb2b5305ad63290bb1aa24cf81fce1bc2 from cluster 127.0.0.1:5001

>>> Sending CLUSTER FORGET messages to the cluster…

>>> SHUTDOWN the node.

원본 위치 <http://www.redisgate.com/redis/cluster/redis-trib.php>

확인 작업

아래 생성된 슬롯수 및 ok가 일치하면 (클러스터링 개당 슬롯이 분리되어있음)

Nodes 수가 설정값과 일치하는지 known nodes 확인

Size 에서 클러스터링 값을 확인

[root@ip-10-24-20-62 redis]# redis-cli -h localhost

localhost:6379> cluster info

cluster_state:ok

cluster_slots_assigned:16384

cluster_slots_ok:16384

cluster_slots_pfail:0

cluster_slots_fail:0

cluster_known_nodes:6

cluster_size:3

cluster_current_epoch:6

cluster_my_epoch:4

cluster_stats_messages_sent:4481

cluster_stats_messages_received:4440

localhost:6379>

클러스터 노드수는 아래와 같이 확인

localhost:6379> cluster nodes

[linux] BASE64 Encode / Decode 손쉽게 이용하기

 

Php를 이용해서 아래와 같이 편하게 할 수 있음

#!/bin/bash -e

INPUT=$1;

 

if [ -z $INPUT ];

then

echo ” Input your encoding Plain text”

else

php -r “echo base64_encode($INPUT);”;

echo “\n”;

fi

 

 

예전엔, 이렇게 openssl을 이용했엇따.

 

[root@jinstalk ~]# printf “mail.shhong” | openssl base64

bWFpbC5zaGhvbmc=

 

Decode는 해당 openssl을 이용해서 이런식으로 가능합니다.

#!/bin/bash -e

INPUT=$1;

 

if [ -z $INPUT ];

then

echo ” Input your decoding Base64Encoded text”

else

echo $INPUT | openssl base64 -d;

echo “”;

fi

 

[linux] RPM BUILD 환경 구성하기

#RPM BUILD INSTALL

yum install rpm-build

yum install redhat-rpm-config

#STATUS FOR RPM-BUILD

rpm -qs rpm-build

#Environment for BUILD

mkdir -p ~/rpmbuild/{BUILD,RPMS,SOURCES,SPECS,SRPMS}

# rpm 설치시 /etc/rpm/macro.dist 설정

#아래 매크로는 따로 설정하지 않아도 동작함.

echo ‘%_topdir %(echo $HOME)/rpmbuild’ > ~/.rpmmacros

#COMPILER Install

yum install make gcc

# 쌘트 6에서 공식 지원하는건 gcc 4.4

# RH 프로젝트를 통해서 비공식적으로 파이선 2.7 버전과, gcc 4.8을 Virtual ENV 형태로 제공 받을 수 있음.

[nginx] HTTPS Optimizing (OCSP Stapling)

Nginx에서 HTTPS Optimizing

  1. 연결 인증서 캐싱(Connection credentials caching)

SSL/TLS의 대부분 오버헤드는 초기의 연결 setup이다.

 

이 연결을 캐싱하면 다음 요청들이 좀 더 빨라진다.

 

설정에 다음을 추가한다.

 

ssl_session_cache shared:SSL:20m;
ssl_session_timeout 10m;

이는 모든 워커 프로세스들 사이에 공유되는 캐쉬를 생성한다.

캐쉬 사이즈는 bytes이고 4000 세션은 1MB에 저장된다고 한다. 20MB는 80000 세션을 저장하게 될 것이다.

 

  1. SSL을 사용하지 않기~

 

SSL은 TLS에 의해 대체된다. SSL을 계속 이야기 하는 건 오래된 습관과 관습이 아닐까 한다.(이 건 원본 저자의 의견)

 

SSL은 몇 가지 약점을 가지고 있기 때문에(이건 찾아봐야 함) 실지적으로 다양한 공격이 있었다.

 

TLS를 지원 안 하는 브라우저는 IE 6이다. (굿바이 했으니~ 패스)

 

TLS의 최신 버전은 1.2다. 그러나 새로운 브라우저들과 라이브러리들이 여전히 TLS 1.0을 사용한다.

 

따라서 설정에 다음을 추가한다.

 

ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

  1. 암호화 모듈들을 옵티마이징

 

저자가 왜 이것을 옵티마이징 해야하는지.. 사용할 때 안전한 것만 지정해서 쓰면 될 거 같은데.. 여튼 한 번 해봤다.

 

설정에 다음을 추가하고

 

ssl_prefer_server_ciphers on;

아래 설정 중에 하나면 선택해서 쓰면 된다. (옵션 1과 옵션 2의 차이는 원본 참조)

 

# Cipher suite option 1:
ssl_ciphers ECDH+AESGCM:ECDH+AES256:ECDH+AES128:!ADH:!AECDH:!MD5;

# Cipher suite option 2:
#ssl_ciphers ECDH+AESGCM:ECDH+AES256:ECDH+AES128:DH+3DES:!ADH:!AECDH:!MD5;

# If you absolutely need IE8 compatibility, use this:
#ssl_ciphers ECDH+AESGCM:ECDH+AES256:ECDH+AES128:DH+3DES:RSA+3DES:!ADH:!AECDH:!MD5;

  1. OCSP stapling

Online Certificate Status Protocol(OCSP) 는 현재 인증서의 폐지 상태를 체크하는 프로토콜이다. 브라우저가 인증서를 볼 때 해당 인증서가 폐지 안 됐는지 체크하기 위해 인증서를 발행한 곳과 접촉한다. 물론 이 것은 연결을 초기화하는데 오버헤드가 된다. 또한 이 과정에서 3자(인증서를 발행한 곳)가 포함되어서 프라이버시 이슈가 있다.

 

이것을 적용하려면 Nginx 1.3.7 이상이 필요하다.

그리고 인증서를 발행하는 사이트에 가서 아래 파일을 다운 받는다.

AddTrustExternalCARoot.crt PositiveSSLCA2.crt

우리는 Comodo 인증서를 다운 받기 때문에 아래 URL에서 다운받았다.

https://support.comodo.com/index.php?/Default/Knowledgebase/Article/View/853/74/addtrustexternalcaroot

https://support.comodo.com/index.php?/Default/Knowledgebase/Article/View/943/74/intermediate-positivessl-ca-2

 

그런 다음 한개의 파일로 합친다.

 

cat AddTrustExternalCARoot.crt PositiveSSLCA2.crt > trustchain.crt

이제 적절한 위치(예: /etc/nginx/cert/trustchain.crt)에 넣고 Nginx의 설정을 아래와 같이 추가한다.

ssl_stapling on;
ssl_stapling_verify on;
ssl_trusted_certificate /etc/nginx/cert/trustchain.crt;
resolver 8.8.8.8 8.8.4.4;

stapling과 관련 없이 resolver가 들어가 있다. 이건 DNS 주소이고 2개의 DNS주소는 구글의 public DNS 주소이다. 다른 DNS 주소를 넣어도 상관없다.

 

  1. Strict Transport Security

SPDY를 사용할 때 모든 HTTP 요청을 HTTPS로 redirect하고 싶다면 Strict Transport Security를 사용하고 싶을 거라고 하는데 SPDY를 사용 안 하므로 패스 했다.

 

  1. 적용 결과

적용해보니 https로 사용하는 우리 사이트에서는 약 400ms 정도 빨라졌다.

 

좀 더 정확한 내용을 보고 싶으면 아래 원본을 읽어 보시길~

 

 

원본:

https://bjornjohansen.no/optimizing-https-nginx

 

원본 위치 <http://chickenlabs.blogspot.kr/2014/08/nginx-https-optimizing.html>

[linux] Nginx proxy_pass 에서 origin URI 제공

톰켓 proxypass 시에 header 에 Original URI 전달하기.

관련해서 proxy backend   넘겨줄 X-Original-URI 말고 X-forwarded-URI 로도 넘겨주는 방법(동일?) 선택하면 될듯합니다.

참고 : http://nerds.qminderapp.com/request-url-behind-proxy.html

nginx 설정

header X-Original-URI

location / {

            proxy_set_header X-Original-URI $request_uri;

            proxy_pass http://127.0.0.1:8080/;

        }

         location /testuri {

            proxy_set_header X-Original-URI $request_uri;

            proxy_pass http://127.0.0.1:8080/;

        }

java 설정

request.getHeader(“X-Original-URI”); 

실제 패킷 분석 결과

(톰켓으로 넘어가는 loopback 8080 캡쳐 : # tcpdump i lo qexX port 8080)

get http://test.hongstalk.com

09:54:56.618161 00:00:00:00:00:00 (oui Ethernet) > 00:00:00:00:00:00 (oui Ethernet), IPv4, length 623: localhost.47502 > localhost.webcache: tcp 557

        0x0000:  4500 0261 210a 4000 4006 198b 7f00 0001  E..a!.@.@…….

        0x0010:  7f00 0001 b98e 1f90 7f44 b41a 86a9 4ace  ………D….J.

        0x0020:  8018 0200 0056 0000 0101 080a 4fc9 9511  …..V……O…

        0x0030:  4fc9 9511 4745 5420 2f20 4854 5450 2f31  O…GET./.HTTP/1

        0x0040:  2e30 0d0a 582d 4f72 6967 696e 616c 2d55  .0..X-Original-U

        0x0050:  5249 3a20 2f0d 0a48 6f73 743a 2031 3237  RI:./..Host:.127

get http://test.hongstalk.com/testuri

09:58:54.909510 00:00:00:00:00:00 (oui Ethernet) > 00:00:00:00:00:00 (oui Ethernet), IPv4, length 543: localhost.47504 > localhost.webcache: tcp 477

        0x0000:  4500 0211 f02b 4000 4006 4ab9 7f00 0001  E….+@.@.J…..

        0x0010:  7f00 0001 b990 1f90 59d0 c7ce 9d52 e649  ……..Y….R.I

        0x0020:  8018 0200 0006 0000 0101 080a 4fcd 37e4  …………O.7.

        0x0030:  4fcd 37e4 4745 5420 2f20 4854 5450 2f31  O.7.GET./.HTTP/1

        0x0040:  2e30 0d0a 582d 4f72 6967 696e 616c 2d55  .0..X-Original-U

        0x0050:  5249 3a20 2f74 6573 7475 7269 0d0a 486f  RI:./testuri..Ho