2021-05-12 14:32:11
CentOS 6.2下KVM管理平台WebVirtMgr的部署
Git地址:https://github.com/retspen/webvirtmgr
環境:
Linux system:CentOS 6.2
libvirt: 0.10.2
webvirtmgr的安裝,參考:https://github.com/retspen/webvirtmgr/wiki/Install-WebVirtMgr
1.安裝虛擬化環境
yum -y groupinstall 'Virtualization Tools'
yum -y groupinstall 'Virtualization'
yum -y groupinstall 'Virtulization Client'
yum -y groupinstall 'Virtulization Platform'
2.安裝依賴包
$ sudo yum -y install http://dl.Fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm
$ sudo yum -y install git Python-pip libvirt-python libxml2-python python-websockify supervisor nginx
3.克隆程式碼
$ git clone git://github.com/retspen/webvirtmgr.git
$ cd webvirtmgr
$ sudo pip install -r requirements.txt # or python-pip (RedHat, Fedora, CentOS, OpenSUSE)
用pip安裝django不太順利,報錯:
[root@vm03 ~]# pip install Django==1.5.5
Collecting Django==1.5.5
Could not find a version that satisfies the requirement Django==1.5.5 (from versions: 1.7plus-email-as-username-1.7.0, 4store-0.3, 503-0.1)
No matching distribution found for Django==1.5.5
折騰許久,只能去django官網下載了個Django-1.5.12.tar.gz包來安裝
4.Django環境初始化
執行syncdb時,報錯,未安裝mysqldb
於是下載MySQL-Python-1.2.5.zip,解壓安裝,又是一個報錯:command ‘gcc’ failed with exit status 1
原因是未安裝:mysql-devel,python-devel,mysql-python
$ ./manage.py syncdb
$ ./manage.py collectstatic
5.設定nginx
vim /etc/nginx/conf.d/webvirtmgr.conf 內容如下:
server {
listen 80 default_server;
server_name $hostname;
#access_log /var/log/nginx/webvirtmgr_access_log;
location /static/ {
root /var/www/webvirtmgr/webvirtmgr; # or /srv instead of /var
expires max;
}
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-for $proxy_add_x_forwarded_for;
proxy_set_header Host $host:$server_port;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 600;
proxy_read_timeout 600;
proxy_send_timeout 600;
client_max_body_size 1024M; # Set higher depending on your needs
}
}
注釋掉nginx的default內容,vim /etc/nginx/conf.d/default.conf 。然後啟動nginx
sudo service nginx restart
6.啟動django
./manage.py runserver 0.0.0.0:8000
存取:http://x.x.x.x:8000 (x.x.x.x - your server IP address ),輸入建立的django使用者和密碼,如果沒有建立,請用python manager.py createsuperuser,命令建立。登入後如下圖所示
webvirtmgr用戶端就這樣搭建完了,接下來需要設定虛擬機器所在宿主機的,參考git地址:https://github.com/retspen/webvirtmgr/wiki/Setup-Host-Server
設定宿主機環境:
system: centos 6.6
libvirt: 0.10.2
1.下載並執行指令碼:libvirt-bootstrap.sh
如果虛擬機器比較多,該指令碼執行時間會比較長,因為會執行service libvirt-guests restart,會將所有執行的虛擬機器掛起然後再恢復,感覺這一步不是必須的,因為我有一台只設定ssh認證,也可以正常連線。
curl http://retspen.github.io/libvirt-bootstrap.sh | sudo sh
2.設定防火牆:
sudo iptables -I INPUT -m state --state NEW -m tcp -p tcp --dport 16509 -j ACCEPT
3.設定TCP認證Setup TCP authorization
參考:https://github.com/retspen/webvirtmgr/wiki/Setup-TCP-authorization,webvirtmgr新建伺服器連線時需要此賬號
$ sudo saslpasswd2 -a libvirt fred
Password: xxxxxx
Again (for verification): xxxxxx
檢視新加的賬號
$ sudo sasldblistusers2 -f /etc/libvirt/passwd.db
fred@webvirtmgr.net: userPassword
刪除新加的賬號:
sudo saslpasswd2 -a libvirt -d fred
驗證新加的賬號:
virsh -c qemu+tcp://IP_address/system nodeinfo
Please enter your authentication name: fred@webvirtmgr.net
Please enter your password: xxxxxx
CPU model: x86_64
CPU(s): 2
CPU frequency: 2611 MHz
CPU socket(s): 1
Core(s) per socket: 2
Thread(s) per core: 1
NUMA cell(s): 1
Memory size: 2019260 kB
注意:賬號全名帶hostname,如fred@webvirtmgr.NET
4.設定ssh認證
ssh和tcp設定一種即可,其實就是設定無密碼登入,要注意的是從webvirtmgr的什麼使用者到宿主機的什麼使用者的無密碼登入,比如我用root跑的django webvirtmgr,而宿主機也是root跑的virsh,所以需要設定root到root的無密碼登入。而git官網推薦的是用nginx使用者跑django webvirtmgr,webvirtmgr使用者跑的virsh,所以設定的是nginx使用者到宿主機webvirtmgr使用者的無密碼登入。
參考:https://github.com/retspen/webvirtmgr/wiki/Setup-SSH-Authorization
5.使用tcp認證連線伺服器
存取:http://xxxx:8000,xxxx是webvirtmgr的ip地址,點選new connection
使用TCP連線,label填寫ip地址,FQDN/IP 填寫ip地址,使用者名稱填寫第三步設定tcp認證所增加的賬號,這裡的使用者名稱不用加@hostname,點選新增完成。如下圖:
6.使用ssh認證連線伺服器
存取存取:http://xxxx:8000,xxxx是webvirtmgr的ip地址,點選new connection,使用ssh認證涉及到一個問題,比如我用賬號webvirtmgr登入了宿主機,但是使用命令virsh list的時候,並不能列出虛擬機器資訊,只有root使用者使用virsh list時才能檢視資訊。於是我設定了nginx到宿主機root的ssh認證,但是在使用webvirtmgr網頁登入時,發現並不能登入,需要手動輸入,而且手動輸入後發現,是可用的。
後來找到原因了,因為我用root跑的webvirtmgr,所以需要設定webvirtmgr伺服器的root使用者宿主機的root使用者的無密碼登入,設定後,可以使用。
7.虛擬機器控制台使用
點選虛機範例,每台虛機最後的按鈕”控制台”,點選後發現報錯,如下圖所示
檢視django後台的錯誤為:
ERROR:django.request:Internal Server Error: /console/
Traceback (most recent call last):
File “/usr/lib/python2.6/site-packages/django/core/handlers/base.py”, line 113, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File “/data/apps/webvirtmgr/console/views.py”, line 58, in console
response.set_cookie(‘token’, token)
AttributeError: ‘str’ object has no attribute ‘set_cookie’
查詢其原始碼,發現可能的錯誤是由於虛機沒有安裝vnc等圖形管理工具,於是在虛機的xml組態檔新增如下設定:
virsh edit oss.webvirtmgr.001
<graphics type='vnc' port='5910' autoport='no' listen='0.0.0.0'>
<listen type='address' address='0.0.0.0'/>
</graphics>
再重新啟動虛機,如果還是不行,就先undefine,然後重新根據xml設定create試試。下載個VNC-Viewer,輸入IP:5910,看能否存取,如下圖所示:說明設定VNC是成功
但是從網頁點選控制台按鈕,發現還是不行,報錯是server disconnected
存取時django後台只有如下資訊:
[26/Apr/2016 05:59:56] “GET /console/?token=4-bcc6ca3b-ca6d-6e51-505a-9c86cf58a6b2 HTTP/1.1” 200 7270
參考這篇:http://ju.outofmemory.cn/entry/145497
安裝了novnc,仍然報同樣的錯,百度谷歌也找不到相應的資訊。yum -y install novnc後,無意間在伺服器上發現了這個命令novnc-server
於是敲了如下命令:novnc_server –vnc IPADDR:5920,其中IPADDR為宿主機ip地址,5920是定義的虛擬機器的vnc埠號。
[root@oss-webvirtmgr-001 ~]# novnc_server –vnc 192.168.200.230:5920
Warning: could not find self.pem
Starting webserver and WebSockets proxy on port 6080
WebSocket server settings:
- Listen on :6080
- Flash security policy server
- Web server. Web root: /usr/share/novnc
- No SSL/TLS support (no cert file)
- proxying from :6080 to 192.168.200.230:5920
Navigate to this URL:
http://oss-webvirtmgr-001:6080/vnc.html?host=oss-webvirtmgr-001&port=6080
Press Ctrl-C to exit
1: 10.1.196.211: Plain non-SSL (ws://) WebSocket connection
1: 10.1.196.211: Version hybi-13, base64: ‘False’
1: connecting to: 192.168.200.230:5920
結果居然ok了,console控制台起來了
問題是:假如我有30台虛擬機器,每個虛擬機器都有一個vnc埠,我是不是得寫30條這樣的命令,監控每一個埠??
後來發現是由於有一個指令碼沒起,才會導致這種情況,起了這個指令碼後,所有控制台應該都能正常存取。pyhton指令碼為
webvirtmgr/console/webvirtmgr-console
有興趣的可以研究下指令碼內容:
#!/usr/bin/env python
import os
import sys
import logging
DIR_PATH = os.path.dirname(os.path.abspath(__file__))
ROOT_PATH = os.path.abspath(os.path.join(DIR_PATH, '..', ''))
# VENV_PATH = ROOT_PATH + '/venv/lib/python2.7/site-packages'
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "webvirtmgr.settings")
CERT = DIR_PATH + '/cert.pem'
if ROOT_PATH not in sys.path:
sys.path.append(ROOT_PATH)
# if VENV_PATH not in sys.path:
# sys.path.append(VENV_PATH)
import Cookie
import socket
from webvirtmgr.settings import WS_PORT, WS_HOST, WS_CERT
from vrtManager.connection import CONN_SSH, CONN_SOCKET
import re
from tunnel import Tunnel
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-v",
"--verbose",
dest="verbose",
action="store_true",
help="Verbose mode",
default=False)
parser.add_option("-d",
"--debug",
dest="debug",
action="store_true",
help="Debug mode",
default=False)
parser.add_option("-H",
"--host",
dest="host",
action="store",
help="Listen host",
default=WS_HOST)
parser.add_option("-p",
"--port",
dest="port",
action="store",
help="Listen port",
default=WS_PORT or 6080)
parser.add_option("-c",
"--cert",
dest="cert",
action="store",
help="Certificate file path",
default=WS_CERT or CERT)
(options, args) = parser.parse_args()
FORMAT="%(asctime)s - %(name)s - %(levelname)s : %(message)s"
if options.debug:
logging.basicConfig(level=logging.DEBUG,format=FORMAT)
options.verbose=True
elif options.verbose:
logging.basicConfig(level=logging.INFO,format=FORMAT)
else:
logging.basicConfig(level=logging.WARNING,format=FORMAT)
try:
from websockify import WebSocketProxy
try:
from websockify import ProxyRequestHandler
except ImportError:
USE_HANDLER = False
else:
USE_HANDLER = True
except ImportError:
try:
from novnc.wsproxy import WebSocketProxy
except ImportError:
print('Unable to import a websockify implementation, ' +
'please install one')
sys.exit(1)
else:
USE_HANDLER = False
def get_connection_infos(token):
from instance.models import Instance
from vrtManager.instance import wvmInstance
try:
temptoken = token.split('-', 1)
host = int(temptoken[0])
uuid = temptoken[1]
instance = Instance.objects.get(compute_id=host, uuid=uuid)
conn = wvmInstance(instance.compute.hostname,
instance.compute.login,
instance.compute.password,
instance.compute.type,
instance.name)
if instance.compute.hostname.count(':'):
connhost = instance.compute.hostname.split(':')[0]
connport = instance.compute.hostname.split(':')[1]
else:
connhost = instance.compute.hostname
connport = 22
connuser = instance.compute.login
conntype = instance.compute.type
console_host = conn.get_console_listen_addr()
console_port = conn.get_console_port()
console_socket = conn.get_console_socket()
except Exception,e:
logging.error('Fail to retrieve console connexion infos for token %s : %s' % (token,e))
raise
return (connhost, connport, connuser, conntype, console_host,
console_port, console_socket)
class CompatibilityMixIn(object):
def _new_client(self, daemon, socket_factory):
cookie = Cookie.SimpleCookie()
cookie.load(self.headers.getheader('cookie'))
if 'token' not in cookie:
self.msg('No token cookie found !')
return False
token = cookie['token'].value
(connhost, connport, connuser, conntype, console_host, console_port,
console_socket) = get_connection_infos(token)
cnx_debug_msg = "Connexion infos :n"
cnx_debug_msg += "- connhost : '%s'n" % connhost
cnx_debug_msg += "- connport : '%s'n" % connport
cnx_debug_msg += "- connuser : '%s'n" % connuser
cnx_debug_msg += "- conntype : '%s'n" % conntype
cnx_debug_msg += "- console_host : '%s'n" % console_host
cnx_debug_msg += "- console_port : '%s'n" % console_port
cnx_debug_msg += "- console_socket : '%s'n" % console_socket
logging.debug(cnx_debug_msg)
if console_socket and conntype == CONN_SOCKET:
# Local socket on local host
self.msg('Try to open local socket %s' % console_socket)
tsock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
tsock.connect(console_socket)
elif console_socket or re.match('^127.', console_host):
# Need tunnel to physical host
if conntype != CONN_SSH:
self.msg("Need a tunnel to access console but can't mount " +
"one because it's not a SSH host")
raise
try:
# generate a string with all placeholders to avoid TypeErrors
# in sprintf
# https://github.com/retspen/webvirtmgr/pull/497
error_msg = "Try to open tunnel on %s@%s:%s on console %s:%s "
error_msg += "(or socket %s)"
self.msg(error_msg % (connuser, connhost, connport,
console_host, console_port, console_socket))
tunnel = Tunnel()
fd = tunnel.open(connhost, connuser, connport,
console_host, console_port, console_socket)
tsock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
except Exception as e:
self.msg("Fail to open tunnel : %s" % e)
raise
self.msg("Tunnel openned")
else:
# Direct access
self.msg("connecting to: %s:%s" % (connhost, console_port))
tsock = socket_factory(connhost, console_port, connect=True)
tunnel = None
if self.verbose and not daemon:
print(self.traffic_legend)
# Start proxying
try:
self.msg("Start proxying")
self.do_proxy(tsock)
except:
if tunnel:
self.vmsg(
"%s:%s (via %s@%s:%s) : Target closed" %
(console_host, console_port, connuser, connhost, connport))
if tsock:
tsock.shutdown(socket.SHUT_RDWR)
tsock.close()
if tunnel:
tunnel.close()
raise
if USE_HANDLER:
class NovaProxyRequestHandler(ProxyRequestHandler, CompatibilityMixIn):
def msg(self, *args, **kwargs):
self.log_message(*args, **kwargs)
def vmsg(self, *args, **kwargs):
if self.verbose:
self.msg(*args, **kwargs)
def new_websocket_client(self):
"""
Called after a new WebSocket connection has been established.
"""
# Setup variable for compatibility
daemon = self.server.daemon
socket_factory = self.server.socket
self._new_client(daemon, socket_factory)
else:
class NovaWebSocketProxy(WebSocketProxy, CompatibilityMixIn):
def new_client(self):
"""
Called after a new WebSocket connection has been established.
"""
# Setup variable for compatibility
daemon = self.daemon
socket_factory = self.socket
self._new_client(daemon, socket_factory)
if __name__ == '__main__':
if USE_HANDLER:
# Create the WebSocketProxy with NovaProxyRequestHandler handler
server = WebSocketProxy(RequestHandlerClass=NovaProxyRequestHandler,
listen_host=options.host,
listen_port=options.port,
source_is_ipv6=False,
verbose=options.verbose,
cert=options.cert,
key=None,
ssl_only=False,
daemon=False,
record=False,
web=False,
traffic=False,
target_host='ignore',
target_port='ignore',
wrap_mode='exit',
wrap_cmd=None)
else:
# Create the NovaWebSockets proxy
server = NovaWebSocketProxy(listen_host=options.host,
listen_port=options.port,
source_is_ipv6=False,
verbose=options.verbose,
cert=options.cert,
key=None,
ssl_only=False,
daemon=False,
record=False,
web=False,
target_host='ignore',
target_port='ignore',
wrap_mode='exit',
wrap_cmd=None)
server.start_server()
本文永久更新連結地址:http://www.linuxidc.com/Linux/2017-02/140376.htm
相關文章