vi 에디터에서 DOS 모드, UNIX 모드 설정하기

 오늘 회사에서 작업하던 중, 분명히 vi 에디터로 스크립트 파일을 열어서 확인을 할때는 개행문자와 파일 내용들이 이상없이 나타나 있는데, 콘솔로 스크립트를 실행시키면 라인의 끝에 “^M” 이 붙어있어서 제대로 실행을 할 수 없다는 에러메시지만 자꾸 나타났다.

 역시나 인터넷에서 검색을 해보니 답은 금방 나왔다.

*** 검색어: nabiro, vi, dos, unix, mode, 모드, ^M, 컨트롤M, Ctrl + M

vi 편집기로 작업 완료해서 UNIX에 업로드 하면 가끔 특정 파일의 라인끝에 ^M 문자가 붙는 경우가 있습니다.
이것은 윈도우에서 편집하여 저장할 때 DOS 모드로 저장이 되어 모든 라인의 끝 (엔터키를 친곳)에 CR/LF가 붙기
때문입니다.

유닉스에서는 CR 이던가 LF 이던가 하나만 엔터로 인식하여 ^M 문자가 라인 끝에 붙게 됩니다.

이를 막기 위해서는 윈도우의 vi 에디터에서 파일을 저장할 때 UNIX 모드로 저장해야 합니다.
유닉스 모드로 변경하는 명령어는 아래와 같습니다.

set fileformat=unix

DOS 모드는

set fileformat=dos

위 명령어를 적용한 후 저장하면 각각의 모드로 저장됩니다.

출처 : http://nabiro.tistory.com/entry/vi-%EC%97%90%EB%94%94%ED%84%B0%EC%97%90%EC%84%9C-DOS-%EB%AA%A8%EB%93%9C-UNIX-%EB%AA%A8%EB%93%9C-%EC%84%A4%EC%A0%95%ED%95%98%EA%B8%B0

 간단한 것이었는데… 역시나 기본기가 정말 중요하다는 것을 새삼스레 느낀다..

시스템 최적화 – 동시사용자 늘리기 위한 커널 조정(ulimit)

 이 글은 http://wiki.kldp.org/KoreanDoc/Ulimit-KLDP (문태준님 작성, 2000년 2월 24일(목))을 토대로 필자가 나름 내용을 추가하여 작성하는 글이다.

 최대한 원글의 내용을 그대로 유지하되, 이미 10년이란 세월이 흘렀으므로 많은 변화가 있었다. 워낙 중요하고 좋은 글이라 그냥 그대로 가져다 쓰려고 했으나, 뭔가 아쉬운 느낌이 들어 없는 실력이지만 약간의 보충을 덧붙여보기로 했다.

  * 이 글은 실제로 제가 대형서버를 운영하고 있는 상황에서 나온 글은 절대 아니며, 그냥 여기저기서 주워들은 이야기들과 자료들을 토대로 해서 작성한 것입니다. 동시접속이 몇백명에서 몇천명되는 서비스를 하려면 단순하게 커널 컴파일 한번 하고 끝나는 것이 아니라 여러가지 조정을 해주어야 할 것이 많습니다. 또한 하드웨어와 OS 제한이 있으므로 로드밸런싱(부하분산), 트래픽 분산 등을 하는 스위칭 장비, 클러스터링 시스템 구성이 필요할 수 있습니다. 그만큼 설계를 잘해야합니다. 여기에 언급한 것은 단지 쉽게 할 수 있는 맛보기 정도이지요. 이로 인해서 생기는 손해에 대해서는 본인이 절대 책임을 지지 않습니다. 또한 내용 중 틀린 부분도 많이 있을 것입니다.

  * 들어가며

 대규모 서비스를 준비하는 경우 운영체제의 제한사항을 먼저 확인해야 한다. 동시에 열수 있는 총파일 수, 한 프로세스가 열수 있는 파일 수 등등.

 예를 들어 대형 웹서버를 아파치로 서비스하는 경우를 생각해보자. 아파치는 기본적으로 프로세스 방식으로 서비스를 처리한다. 이건 사용자의 요구가 올때마다 하나의 프로세스를 띄우므로 만약 동시에 10명의 사용자가 접속을 하면 10개의 프로세스가 떠야한다는 것이다. 최근의 아파치 서버는 MaxClients 150 이라고 설정되어 있다. 이건 동시에 150 개의 프로세스를 띄울 수 있으며 결국 동시에 150명을 받아 들일 수 있다는 것이다(실제로 이정도만 하더라도 절대로 작은 규모는 아니다). 그런데 만약 nobody가 만들어낼 수 있는 최대 프로세스 개수가 그 이하라면? 당연히 문제가 생길 것이다. 물론 최근 레드햇 6.0 이상 버전은 그 이상으로 맞추어져 있어서 문제가 생기지는 않겠지만.

 문제는 프로세스가 많이 뜨면 프로세스뿐만 아니라 열 수 있는 파일 수에서도 문제가 된다.

 그러면 먼저 프로세스의 자원 한도에 대해서 알아보자.

 -주
 이 글을 작성하는 현재(2010.07.08) 많은 것이 바뀌어졌다. 현재 필자가 운용하는 아파치의 버전은 2.2.14 버전을 사용중이고, (원 글님이 글을 작성하셨을 10년전에는 아마 1.7.X 버전으로 사용되었으리라 생각한다) 아파치의 구동 방식도 하나의 요청마다 하나의 프로세스를 띄우는 방식이 아닌 메소드 및 기타 방식을 사용하는 형식으로 바뀌었다. 그리고 아울러 MaxClient의 수도 증가했음은 물론이다.

 * 프로세스의 자원한도

 프로세스의 자원한도를 리눅스에서는 ulimit 를 통해서 알 수 있다.

 ulimit 옵션

 -a 모든 제한 사항을 보여준다.
 -c 최대 코어 파일 사이즈
 -d 프로세스 데이터 세그먼트의 최대 크기
 -f shell에 의해 만들어질 수 있는 파일의 최대 크기
 -s 최대 스택 크기
 -p 파이프 크기
 -n 오픈 파일의 최대 수
 -u 프로세스 최대 수
 -v 최대 가상 메모리의 량

 # ulimit -a (또는 ulimit -Sa) —> soft 한도

jonathan@jonathan-laptop:~$ ulimit -a
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 20
file size               (blocks, -f) unlimited
pending signals                 (-i) 16382
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 1024
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) unlimited
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

 # ulimit -Ha —-> Hard 한도

jonathan@jonathan-laptop:~$ ulimit -Ha
core file size          (blocks, -c) unlimited
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 20
file size               (blocks, -f) unlimited
pending signals                 (-i) 16382
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 1024
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) unlimited
cpu time               (seconds, -t) unlimited
max user processes              (-u) unlimited
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

 소프트 한도(soft)는 새로운 프로세스가 만들어졌을 때 디폴트로 적용되는 자원의 한도이다. 이것을 하드한도까지 등가시킬 수 있다. 그렇지만 이 한도를 넘어서 확장하는 것은 슈퍼유저만이 가능하다.

 즉, 하드한도는 절대적인 선이다.

 그렇다면 하드한도는 슈퍼유저라고 무한대로 늘릴 수 있는가?
-> 절대 아니다. 이건 커널차원에서 지정을 해야 한다.

 위에서의 각 항목을 살펴보자면…

core file size          -> 코어파일의 최대크기
data seg size           -> 프로세스의 데이터 세그먼트 최대크기
scheduling priority
file size               (blocks, -f) unlimited  -> 쉘에서 생성되는 파일의 최대 크기
pending signals                 (-i) 16382
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited  -> resident set size의 최대 크기(메모리 최대크기)
open files                      (-n) 1024    -> 한 프로세스에서 열 수 있는 open file descriptor의 최대 숫자(열수 있는 최대 파일 수)
pipe size            (512 bytes, -p) 8    -> 512-바이트 블럭의 파이프 크기
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited     -> 총 누적된 CPU 시간(초)
max user processes              (-u) unlimited   -> 단일 유저가 사용가능한 프로세스의 최대 갯수
virtual memory          (kbytes, -v) unlimited   -> 쉘에서 사용가능 한 가상 메모리의 최대 용량
file locks                      (-x) unlimited

 의 뜻을 가지고 있다.

 위의 내용 중 주의깊게 살펴볼 부분이 바로 한 프로세스에서 열 수 있는 file descriptor 의 갯수를 표시한 open files 항목과 한 유저가 생성 가능한 프로세스의 갯수 부분이다.

 사실 이미 한 유저가 생성 가능한 프로세스의 갯수가 무한정으로 되어 있으므로 file descriptor 의 갯수는 그다지 큰 의미가 없다. 하지만 file descriptor의 갯수를 늘리고 싶다면 다음의 방법으로 가능하다.

 1. 소스파일을 수정한 후, 커널 재컴파일을 하는 방법.

 2. /proc 를 이용하여 변경하는 방법.

 3. /etc/security/limits.conf 파일을 수정하는 방법

 사실 ulimit 명령으로 조절이 가능하나, 단지 보여주기만 할 뿐 실제적인 수정이 되지 않는다고 원글에는 나와있었다. 그래서 ulimit 관련 부분은 패스.

 그러나, 프로그래밍의 경우는 ulimit 함수를 통해서 수정이 가능하다.

NAME
       ulimit – get and set user limits

SYNOPSIS
       #include <ulimit.h>

       long ulimit(int cmd, long newlimit);

DESCRIPTION
       Warning: This routine is obsolete.  Use getrlimit(2), setrlimit(2), and
       sysconf(3) instead.  For the shell command ulimit(), see bash(1).

       The ulimit() call will get or set some limit for the  calling  process.
       The cmd argument can have one of the following values.

       UL_GETFSIZE
              Return the limit on the size of a file, in units of 512 bytes.

       UL_SETFSIZE
              Set the limit on the size of a file.

       3      (Not  implemented  for  Linux.)   Return  the  maximum  possible
              address of the data segment.

       4      (Implemented but no symbolic  constant  provided.)   Return  the
              maximum number of files that the calling process can open.

RETURN VALUE
       On  success,  ulimit()  returns  a non-negative value.  On error, -1 is
       returned, and errno is set appropriately.

ERRORS
       EPERM  A non-root process tried to increase a limit.

CONFORMING TO
       SVr4, POSIX.1-2001.  POSIX.1-2008 marks ulimit() as obsolete.

SEE ALSO
       bash(1), getrlimit(2), setrlimit(2), sysconf(3)

 2. proc를 이용한 방법

 proc를 이용하여 간단히 변경하는 방법이 있다.

pchero@MyNote:~$ cat /proc/sys/fs/file-max
6553600
pchero@MyNote:~$ sudo echo 7000000 > /proc/sys/fs/file-max

 하지만 /proc 를 사용하여 시스템 설정을 변경할 경우, 매 부팅시 설정을 다시 해주어야 한다는 단점이 있다.
 /etc/rc.local 파일을 이용하여 명령어를 설정하던가 아니면 다음에 나오는 limits.conf 파일을 이용하도록 한다.

 3. 사용자에 따른 자원 한도 설정 파일
/etc/security/limits.conf

# /etc/security/limits.conf
#
#Each line describes a limit for a user in the form:
#
#<domain>        <type>  <item>  <value>
#
#Where:
#<domain> can be:
#        – an user name
#        – a group name, with @group syntax
#        – the wildcard *, for default entry
#        – the wildcard %, can be also used with %group syntax,
#                 for maxlogin limit
#        – NOTE: group and wildcard limits are not applied to root.
#          To apply a limit to the root user, <domain> must be
#          the literal username root.
#
#<type> can have the two values:
#        – “soft” for enforcing the soft limits
#        – “hard” for enforcing hard limits
#
#<item> can be one of the following:
#        – core – limits the core file size (KB)
#        – data – max data size (KB)
#        – fsize – maximum filesize (KB)
#        – memlock – max locked-in-memory address space (KB)
#        – nofile – max number of open files
#        – rss – max resident set size (KB)
#        – stack – max stack size (KB)
#        – cpu – max CPU time (MIN)
#        – nproc – max number of processes
#        – as – address space limit (KB)
#        – maxlogins – max number of logins for this user
#        – maxsyslogins – max number of logins on the system
#        – priority – the priority to run user process with
#        – locks – max number of file locks the user can hold
#        – sigpending – max number of pending signals
#        – msgqueue – max memory used by POSIX message queues (bytes)
#        – nice – max nice priority allowed to raise to values: [-20, 19]
#        – rtprio – max realtime priority
#        – chroot – change root to directory (Debian-specific)
#
#<domain>      <type>  <item>         <value>
#

#*               soft    core            0
#root            hard    core            100000
#*               hard    rss             10000
#@student        hard    nproc           20
#@faculty        soft    nproc           20
#@faculty        hard    nproc           50
#ftp             hard    nproc           0
#ftp             –       chroot          /ftp
#@student        –       maxlogins       4

# End of file

# Setting for oracle
oracle          soft    nproc           2047
oracle          hard    nproc           16383
oracle          soft    nofile          1023
oracle          hard    nofile          6553

  제일 아래 ‘oracle’ 과 같이 따로 설정된 부분과 같이 변경하면 된다. 이렇게 설정할 경우, 매 부팅시 자동 적용되어 별도로 적용하지 않아도 된다. 또한, 각각의 유저마다 다른 설정을 적용할 수 있으므로 보안 및 관리에도 용이하다.

 # 마지막으로 프로세스에서 열어놓은 파일을 확인하는 방법에 대해 알아보자.

 결론적으로 lsof 프로그램을 이용하면 된다.

 lsof는 ‘List Open File’의 약자로 해당 System에서 구동되고 있는 프로세스들에 의해서 열려진 파일들을 확인 할 수
있는 툴이다. 시스템의 의심스러운 프로세스에 대한 확인이 용이하고, 설치가 비교적 쉬워 많이 이용되고 있다.

 lsof에 관한 내용은 워낙 방대하여 아래에 해당 프로그램 사용에 대한 매뉴얼을 링크해둔다. 또한 man lsof를 이용하여 사용해도 무방하다.

http://www.superuser.co.kr/security/certcc/secu_certcc_15.htm

 

리눅스에서 윈도우 파일 열때의 문제점…

 리눅스에서 윈도우에서 만든 txt 파일을 열 경우, 개행이 되는 부분에 ^M 문자가 붙어 있는 것을 확인 할 수 있다.

 이는 리눅스(Unix)와 윈도우의 개행문자의 차이 때문인데 검색을 통해 dos2unix 의 유틸을 이용할 경우 해결할 수 있다는 것을 알 수 있었다.

 하지만 레드햇 계열의 배포판에 설치가 되어 있었고, 우분투는 해당 패키지를 찾을 수 없었다.

 대신, 다른 유틸의 사용이 가능했는데, 다음의 유틸리티를 이용할 경우, 매우 쉽게 해결할 수 있다.

$ sudo apt-get install tofrodos

 이 유틸리티를 설치 한 후, 다음의 명령어가 사용가능해진다.

 fromdos, todos

 이 명령어들을 이용해 ^M의 제거 및 역으로 윈도우를 위한 파일을 만들수도 있다.

 윈도우 파일을 리눅스에서 사용하기 위해..

 $ fromdos files.txt

 리눅스 파일을 윈도우에서 사용하기 위해…

 $ todos files.txt

 

installing ubuntu-9.10-netbook_remix on the webmachines v10HC

 이번에 새로 산 웹 머신즈 V10HC 모델에 우분투를 설치하여 사용하더 중 한가지 문제점을 발견하였다.

 바로 무선랜이 안된다는 것.

 구글링을 해보니 다음의 주소에서 해결의 실마리를 얻을 수 있었다.

 http://spac.tistory.com/66?srchid=BR1http%3A%2F%2Fspac.tistory.com%2F66

 하지만 내가 설치한 넷북 전용 버전에서는 약간의 수고를 더 해야만 활용할 수 있었다.

 즉, 다음의 작업들이 실행되어야 한다.

 먼저 아래의 주소에서 리눅스용 무선랜 드라이버를 다운 받는다.

 http://122.146.118.42/downloads/downloadsView.aspx?Langid=1&PNid=48&PFid=48&Level=5&Conn=4&DownTypeID=3&GetDown=false&Downloads=true#RTL8192SE

 그리고 콘솔창을 열어 다음을 입력한다.

 # sudo su –

 # apt-get install build-essential linux-source-2.6.31
 # cd /usr/src
 # tar xvfz linux-source-2.6.31.tar.bz2

 다운 받은 파일이 있는 디렉토리로 이동한다. 필자의 경우 /home/pchero/다운로드

 # cd /home/pchero/다운로드
 # tar xvfz rtl8192se_linux_2.6.0013.1204.2009.tar.gz
 # cd rtl8192se_linux_2.6.0013.1204.2009
 # make
 # make install

 이로써 설치는 끝이다. 우분투를 재부팅한 후, 무선랜이 활성화가 되는것을 확인할 수 있다.

우분투 미러링 rsync 주소 변경

 우분투 9.10 업데이트에 대한 기대로 행복할 무렵..

 동아리 미러링 서버 상태를 확인해보니 아래의 메시지가 나타나 있었다.

Found all ISO images for series The Dapper Drake and flavour edubuntu.

Found all ISO images for series The Hardy Heron and flavour edubuntu.
Found all ISO images for series The Intrepid Ibex and flavour edubuntu.
Found all ISO images for series The Hardy Heron and flavour kubuntu.
Found all ISO images for series The Intrepid Ibex and flavour kubuntu.
Found all ISO images for series The Jaunty Jackalope and flavour kubuntu.
Failed http://mirror.knusoft.net/ubuntu-releases///kubuntu/.pool/kubuntu-9.10-alternate-amd64.iso: Bad response code: 404
Failed http://mirror.knusoft.net/ubuntu-releases///kubuntu/.pool/kubuntu-9.10-alternate-i386.iso: Bad response code: 404
Failed http://mirror.knusoft.net/ubuntu-releases///kubuntu/.pool/kubuntu-9.10-desktop-amd64.iso: Bad response code: 404
Failed http://mirror.knusoft.net/ubuntu-releases///kubuntu/.pool/kubuntu-9.10-desktop-i386.iso: Bad response code: 404
Failed http://mirror.knusoft.net/ubuntu-releases///kubuntu/.pool/kubuntu-9.10-netbook-i386.iso: Bad response code: 404
Found all ISO images for series The Dapper Drake and flavour ubuntu.
Found all ISO images for series The Hardy Heron and flavour ubuntu.
Found all ISO images for series The Intrepid Ibex and flavour ubuntu.
Found all ISO images for series The Jaunty Jackalope and flavour ubuntu.
Failed http://mirror.knusoft.net/ubuntu-releases///.pool/ubuntu-9.10-alternate-amd64.iso: Bad response code: 404
Failed http://mirror.knusoft.net/ubuntu-releases///.pool/ubuntu-9.10-alternate-i386.iso: Bad response code: 404
Failed http://mirror.knusoft.net/ubuntu-releases///.pool/ubuntu-9.10-desktop-amd64.iso: Bad response code: 404
Failed http://mirror.knusoft.net/ubuntu-releases///.pool/ubuntu-9.10-desktop-armel+dove.img: Bad response code: 404
Failed http://mirror.knusoft.net/ubuntu-releases///.pool/ubuntu-9.10-desktop-armel+imx51.img: Bad response code: 404
Failed http://mirror.knusoft.net/ubuntu-releases///.pool/ubuntu-9.10-desktop-i386.iso: Bad response code: 404
Failed http://mirror.knusoft.net/ubuntu-releases///.pool/ubuntu-9.10-netbook-remix-i386.iso: Bad response code: 404
Failed http://mirror.knusoft.net/ubuntu-releases///.pool/ubuntu-9.10-server-amd64.iso: Bad response code: 404
Failed http://mirror.knusoft.net/ubuntu-releases///.pool/ubuntu-9.10-server-i386.iso: Bad response code: 404

 아직 업데이트가 안되었다는 메시지…

 흠… 처음에는 그저 업데이트가 느리다는 생각 뿐이었다. 그러나 서버에서 rsync 프로세스를 확인해본 결과 rsync 프로세스는 실행되어 있지 않았다.

 cron 작업을 걸어두어 매일 새벽에 자동으로 체크하도록 해 놓았는데 실행이 되어있지 않다니… 문득 이상한 생각이 들어 직접 프로세스를 실행시켜 보았다.
 하지만 아래의 메시지만 나오고 제대로 실행되어 있지 않았다.

 rsync: failed to connect to releases.ubuntu.com: Network is unreachable (101)
rsync error: error in socket IO (code 10) at clientserver.c(122) [receiver=3.0.3]

 아니… 이건 무슨 에러지… 구글링을 해보니 똑같은 에러 메시지 몇개가 나왔다. 그런데 그중에 눈에 익은 글이 나왔다. 바로 내가 포스팅한 글이었다….

 전에도 이런 에러를 한번 겪었었는데 그때는 DNS 포트를 막아놔서 제대로된 쿼리와 응답을 받지 못해 생긴 오류였는데 이번에도 똑같은 에러 메시지였지만 상황이 달랐다. DNS 포트는 막혀있지 않았던 것이었다.

 무엇이 문제일까… 잠시 구글링을 포기하고 dig와 nslookup을 통해 releases.ubuntu.com 의 질의가 제대로 이루어 지는지를 확인하고, 혹시나 싶어 releases.ubuntu.com 의 도메인 네임 대신에 IP 주소를 입력하여 rsync 스크립트를 재 실행 해보았다.

 결과는 마찬가지였다.

 이래저래 고민을 하다가 결국 우분투 미러링 IRC 채널에 문의해보기로 했다.
 IRC 채널 : irc.freenode.org in #ubuntu-mirrors

 답은 간단했다.
https://lists.ubuntu.com/archives/ubuntu-mirrors-announce/2009-October/000015.html

 아래는 위의 링크에 나와있는 메시지의 전문이다.

Hi

As you may know, the newest version of Ubuntu (9.10) is scheduled to be
officially released on Thursday, 29 October. To ensure that this release
goes smoothly, we need your help!

* If you are rsyncing from releases.ubuntu.com please update your
scripts/cronjobs to rsync from rsync.releases.ubuntu.com ASAP!

* Please take a moment to verify that your mirror is ready and
syncing.

* Set any "releases" mirror (the CD images) to sync every 2 hours.
(These rsyncs are very small and quick, and you should not
notice any increased load on your server.)

/! rsyncing straight from releases.ubuntu.com will stop working
before the final release /!

Thank you very, very much for your help spreading Ubuntu, we really
appreciate it!

Cheers,
--
Chris Jones
cmsj at canonical.com
www.canonical.com

 즉, Ubuntu-9.10 릴리즈에 맞춰 rsunc 서버가 변경되었기 때문에 rsync 접속 주소의 수정이 필요하다는 내용이었다.

 모든 등록된 미러링 서버 관리자 이메일 주소로 이 메시지가 발송되었으나, 미처 확인을 안한 것이 문제였다. (설마….도메인이 변경되었을 줄이야…)

 즉시 rsync 스크립트를 고쳐 다시 실행하니 잘 작동한다. 🙂