#!/bin/sh

# Maintainer    : gogisnim (gogisnim@gmail.com)
# Last Modify   : 2007.09.06
# Usage         : vps_make.sh
# Note          :
# This is tool OpenVZ create guest system on interactive.
# Check vzctl!. http://openvz.org
# This script must be installed dialog utility and root authority.

TEMPLATE="gentoo-2.6.18"
TMPFILE="/tmp/tmp.$$"
PRIVATE="/vz/private/"
FLAG=0

! which dialog > /dev/null 2>&1 && echo "ERROR: The dialog utility is required for vps_make.sh.  Exiting!" && exit 1

if [ "$USER" != "root" ]; then
   echo "ERROR: You must be root authority"
   exit 1
fi

umask 177
trap 'rm -f $TMPFILE; exit 1' EXIT INT

number_check() {
   if [ -z "$1" ]; then
       echo "usage: number_check num"
       exit 1
   fi 
   echo $1 | grep ^[[:digit:]]*$ > /dev/null 2>&1
   return $?
}


for no in `ls $PRIVATE`; do
   test "${num:-0}" -lt "$no" && num=$no
done
new_num=`expr $num + 1`

# VEID input and check
until false; do
   dialog --title "VEID" --inputbox "Please enter new VEID : " 20 60 $new_num 2> $TMPFILE
   VEID=`cat $TMPFILE`

   test -z "$VEID" && FLAG=1 && continue
   for no in `ls $PRIVATE`; do
       FLAG=0
       test "$VEID" -eq "$no" && FLAG=1 && break
   done
   number_check $VEID || FLAG=1

   test "$FLAG" = "0" && break
done

# hostname input
dialog --title "hostname" --inputbox "Please enter new hostname : " 20 60 "vps$VEID" 2> $TMPFILE
HOSTNAME=`cat $TMPFILE`

# IP address input
dialog --title "IP Address" --inputbox "Please enter IP : " 20 60 "192.168.0.1" 2> $TMPFILE
IP=`cat $TMPFILE`

# nameserver input
dialog --title "nameserver" --inputbox "Please enter nameserver : " 20 60 "168.126.63.1" 2> $TMPFILE
NAMESERVER=`cat $TMPFILE`

# onboot yes/no
dialog --title "onbook option" --menu "VEID $VEID active on boot time" 20 60 2 yes "Yes, I'll be active vps on boot" no "No, unactive" 2> $TMPFILE
ONBOOT=`cat $TMPFILE`

dialog --title "Information" --msgbox "System is ready to make VPS $VEID...\n\nVEID : $VEID\nHostname : $HOSTNAME\nIP Address : $IP\nNameserver : $NAMESERVER\nOn Boot : $ONBOOT" 20 60

vzctl create $VEID --ostemplate $TEMPLATE &&
vzctl set $VEID --save --onboot=$ONBOOT --ipadd $IP --nameserver $NAMESERVER --hostname $HOSTNAME

exit 0

사용자 삽입 이미지
# vzctl --help
vzctl version 3.0.16
Copyright (C) 2000-2007 SWsoft.
This program may be distributed under the terms of the GNU GPL License.

Usage: vzctl [options] <command> <veid> [parameters]
vzctl destroy | mount | umount | stop | status | enter <veid>
vzctl create <veid> {--ostemplate <name>] [--config <name>]
  [--private <path>] [--root <path>] [--ipadd <addr>] | [--hostname <name>]
vzctl start <veid> [--force] [--wait]
vzctl exec | exec2 <veid> <command> [arg ...]
vzctl runscript <veid> <script>
vzctl chkpnt <veid> [--dumpfile <name>]
vzctl restore <veid> [--dumpfile <name>]
vzctl set veid [--save] [--setmode restart|ignore]
  [--ipadd <addr>] [--ipdel <addr>|all] [--hostname <name>]
  [--nameserver <addr>] [--searchdomain <name>] [--onboot yes|no]
  [--userpasswd <user>:<passwd>] [--cpuunits <N>] [--cpulimit <N>] [--cpus <N>]
  [--diskspace <soft>[:<hard>]] [--diskinodes <soft>[:<hard>]]
  [--quotatime <N>] [--quotaugidlimit <N>]
  [--noatime yes|no] [--capability <name>:on|off ...]
  [--devices b|c:major:minor|all:r|w|rw]
  [--devnodes device:r|w|rw|none]
  [--netif_add <ifname[,mac,host_ifname,host_mac]]>] [--netif_del <ifname>]
  [--applyconfig <name>] [--applyconfig_map <name>]
  [--features <name:on|off>] [--name <vename>]
  [--ioprio <N>]
  [--iptables <name>] [--disabled <yes|no>]
  [UBC parameters]
UBC parameters (N - items, P - pages, B - bytes):
Two numbers divided by colon means barrier:limit.
In case the limit is not given it is set to the same value as the barrier.
  --numproc N[:N]      --numtcpsock N[:N]      --numothersock N[:N]
  --vmguarpages P[:P]  --kmemsize B[:B]        --tcpsndbuf B[:B]
  --tcprcvbuf B[:B]    --othersockbuf B[:B]    --dgramrcvbuf B[:B]
  --oomguarpages P[:P] --lockedpages P[:P]     --privvmpages P[:P]
  --shmpages P[:P]     --numfile N[:N]         --numflock N[:N]
  --numpty N[:N]       --numsiginfo N[:N]      --dcachesize N[:N]
  --numiptent N[:N]    --physpages P[:P]       --avnumproc N[:N]

#

현재 본인이 사용하는 vzctl 환경 및 옵션

# vzctl create 3205 --ostemplate gentoo-2.6.18
# vzctl set 3205 --save --onboot=yes --ipadd 1.1.3.205 --nameserver 1.1.1.200 --nameserver 168.126.63.1 --hostname mail.ddong.ac.kr --diskspace 700000:800000 --userpasswd test:1111

- 시스템 기동과 동시에 VE를 실행시키고 이 설정을 /etc/vz/conf/<VEID>.conf 에 저장
- VEID는 호스트ID 영역의 값
- nameserver는 자체네임서버, 한통네임서버 2개 사용
- diskspace는 soft 700M, hard 800M (--diskspace 옵션 default, kbyte)
- VE의 일반사용자/비번 test/1111

주의
--diskspace 값을 최소 운영체제 설치 용량보다 적게 잡으면 아래와 같은 메시지가 나온다

ddong ~ # vzctl start 2200
Starting VE ...
vzquota : (warning) block_soft_limit [400100] < block_current_usage [418972]
VE is mounted
Adding IP address(es): 1.1.2.200
ERROR: Can't copy file /etc/conf.d/net
/bin/cp: writing `/etc/conf.d/net.15569': Disk quota exceeded
Setting CPU units: 1000
Set hostname: ns2.ddong.ac.kr
/bin/cp: writing `/etc/hosts.15598': Disk quota exceeded
ERROR: Can't copy file /etc/hosts
vzquota : (warning) block_soft_limit [400000] < block_current_usage [418972]
VE start in progress...

TAG OpenVZ, VE, vzctl
사전지식 :
Virtual Private Server, VPS, 가상화
관련 포스팅 :
http://innu.pe.kr/tt/386

본인의 상태:
노트북(웹서핑,프로그래밍,게임을 위한 Gentoo 와 Windows XP가 설치된)이 있다.
놀고있는 데스크탑 PC(Windows XP, FreeBSD가 설치된)가 있는데 이 PC에 VPS 환경을 구성할 것이다.
남아있는 파티션에 Gentoo(커널버전 2.6.21)를 설치했다. 여기까지 준비완료 ~~~


사용자 삽입 이미지

1. openvz 소스 다운받은 다음 커널 설정/컴파일 한다
# USE=symlink emerge openvz-sources
# mount /boot
# cd /usr/src/linux

자신의 시스템에 맞는 커널 설정파일을 http://openvz.org/ 에서 다운받는다.
# wget http://download.openvz.org/kernel/stable/022stab076.1/configs/kernel-2.6.8-022stab076-i686-smp.config.ovz
# make menuconfig
"Load an alternate configuration file" 항목 선택후 다운받은 커널설정 파일을 입력한다.
# make && make modules_install
# cp arch/i386/boot/bzImage /boot/linux-2.6.18-openvz-027.028
# cp .config /boot/.config-linux-2.6.18-openvz-027.028


2. grub 파일편집, 커널파라미터 수정 후 새 커널로 재부팅
/boot/grub/grub.conf
title Gentoo-2.6.18-OpenVZ
root (hd0,5)
kernel /linux-2.6.18-openvz-027.028 root=/dev/hda8

/etc/sysctl.conf
net.ipv4.ip_forward = 1
net.ipv4.conf.default.proxy_arp = 0
net.ipv4.conf.all.rp_filter = 1
kernel.sysrq = 1
net.ipv4.conf.default.send_redirects = 1
net.ipv4.conf.all.send_redirects = 0

주의사항1:
sysctl -p 명령어는 현재 커널에 수정된 커널파라미터가 적용된다.
하지만, error: "kernel.sysrq" is an unknown key 메시지가 나오는데 재부팅되어야 적용이 된다.

주의사항2:
커널설정 파일을 다운받은 그대로 사용하면 본인의 시스템에 맞는 모듈을 알아서 올려야 한다.
본인의 ethernet adapter는 via-rhine 칩셋을 사용하는데 커널이미지에 포함되어 있지 않다. 올려준다.

# echo "via-rhine" >> /etc/modules.autoload.d/kernel-2.6
# reboot


3. OpenVZ에 필요한 유틸리티를 설치한 다음 데몬을 구동한다.
# emerge vzctl vzquota
# /bin/mknod /dev/vzctl c 126 0
# /etc/init.d/vz start
# rc-update add vz default

주의사항:
vzctl 패키지 설치전 미리 설치되어야 하는 패키지가 있는데 그 중 iproute2 패키지가 정상적으로 설치되지 않는다.
sys-apps/iproute2-2.6.19.20061214 패키지(최신버전) 대신 한단계 낮은 버전을 설치한다

# cd /usr/portage/sys-apps
# emerge iproute2-2.6.18.20061002.ebuild



4. OS Template을 생성한다.

1) stage3 소스 tarball을 다운로드 받고 압축을 해제한다.
# mkdir /vz/private/100
# tar xvzf /root/stage3-i686-2007.0.tar.bz2 -C /vz/private/100

2) VE(Virtual Environment) 설정파일(100.conf)을 생성한다.
/etc/vz/conf/100.conf 파일이 생성된다.
# vzctl set 100 --applyconfig vps.basic --save

3) 생성된 /etc/vz/conf/100.conf 파일에 다음을 추가한다.
DISTRIBUTION="gentoo-2.6.18"
OSTEMPLATE="gentoo-2.6.18"

4) Host 시스템의 /proc/mounts을 /vz/private/100/etc/mtab 링크
# ln -s /proc/mounts /vz/private/100/etc/mtab

5) Guest시스템에서 사용할 마운트 테이블 파일을 생성한다.
부팅시 /proc가 마운트 된다.
# echo "proc /proc proc defaults 0 0" > /vz/private/100/etc/fstab

6) /vz/private/100/etc/inittab 파일수정
getty 종류를 실행시키지 않음으로써 VE에서 존재하지 않는 tty로의 로그인을 못하게 한다.
c?:1235:respawn:/sbin/agetty 38400 tty? linux

7) /etc/shadow 파일수정.
root:*:10071:0:::::
* 를 ! 으로 바꾼다.
이는 vzctl set VEID --userpasswd root:password 로 패스워드 변경할때까지
root로 로그인을 불가능하게 한다.

8) checkroot 스크립트 삭제
이 스크립트는 부팅시 활성화 되는것을 방지한다(?). 어쨌든 삭제
rm /vz/private/777/etc/runlevels/boot/checkroot

9) /sbin/rc 파일수정.
try mount -n ${mntcmd:--t sysfs sysfs /sys}
부분을 추가한다.
이는 /sys 로 마운트되는 것을 방지한다.
자동으로 업데이트 되는것을 방지하기위해 /vz/private/100/etc/make.conf 파일에 아래 항목을 추가한다.
CONFIG_PROTECT="/sbin/rc"

10) Set up udev
Delete /lib/udev-state/devices.tar.bz2 and create some device nodes needed to enter a VE:

cd /vz/private/777/lib
rm udev-state/devices.tar.bz2
mknod udev/devices/ttyp0 c 3 0
mknod udev/devices/ptyp0 c 2 0
mknod udev/devices/ptmx c 5 2

Set RC_DEVICES="static" in /vz/private/777/etc/conf.d/rc

You have to leave the directory you are in for the next step to be ok, otherwise you will get this error message :
vzquota : (error) Quota on syscall for 777: Device or resource busy
vzquota on failed [3]

주의사항:
vzctl, vzquota 패키지 설치한 다음 설정까지 끝내고 VE 생성할때 /var/vzquota에 파일을 생성할 수 없다는 메시지가 나오는데 /var 에 vzquota 디렉토리를 생성해주면 이상이 없다.

11) 기타
Host 시스템의 /etc/resolv.conf 파일을 복사한다.
이밖에 기본적으로 세팅되어져야 하는 설정파일이나 프로그램을 복사한다.

OS Template 을 만들기위한 모든 준비가 끝났다.
이제, /vz/private/100/ 에 있는 모든 내용을 gz으로 압축하여 /vz/template/cache 디렉토리에 넣어둔다.
# cd /vz/private/100/
# tar czf /vz/template/cache/gentoo-2.6.18.tar.gz *

OS Template 생성이 끝났다.

주의사항:
Guest 시스템에서도 패키지를 설치할 수 있다.
다만, Host 시스템의 Portage Tree를 사용한다.
# mkdir /vz/root/100/usr/portage
# mount -o bind /usr/portage /vz/root/100/usr/portage
만약, /usr/portage/distfiles 가 다른 파티션에 있다면,
# mount -n -o bind /usr/portage/distfiles /vz/root/100/usr/portage/distfiles

이렇게 하면 가상OS 에서 emerge package_name 형태로 패키지를 설치할 수 있다.
단, 보안측면에서 Guest 시스템에서 패키지 설치할때만 잠시 mount 시키고 그렇지 않을 경우 umount 한다.



5. OpenVZ 실행 및 테스트
# vzctl create 201 --ostemplate gentoo-2.6.18 --ipadd 192.168.0.201 --hostname vps201
Creating VE private area (gentoo-2.6.18)
Performing postcreate actions
VE private area was created

# vzctl start 201
Starting VE ...
VE is mounted
Adding IP address(es): 192.168.0.204
Setting CPU units: 1000
Set hostname: vps201
VE start in progress...


# vzctl enter 201
entered into VE 201

# exit
logout
exited from VE 204

# vzctl stop 201
Stopping VE ...
VE was stopped
VE is unmounted

# vzctl destroy 201
Destroying VE private area: /vz/private/204
VE private area was destroyed


사용자 삽입 이미지


참조 url:
http://gentoo-wiki.com/HOWTO_OpenVZ
http://wiki.openvz.org/VE_creation
http://wiki.openvz.org/Gentoo_template_creation