zone-vnc-console revision 4551
4049N/A#!/usr/bin/python2.7
3652N/A
3998N/A# Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved.
3998N/A#
3998N/A# Licensed under the Apache License, Version 2.0 (the "License"); you may
3998N/A# not use this file except in compliance with the License. You may obtain
3998N/A# a copy of the License at
3998N/A#
3998N/A# http://www.apache.org/licenses/LICENSE-2.0
3998N/A#
3998N/A# Unless required by applicable law or agreed to in writing, software
3998N/A# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
3998N/A# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
3998N/A# License for the specific language governing permissions and limitations
3998N/A# under the License.
3998N/A
4551N/Aimport ConfigParser
4551N/Aimport contextlib
3652N/Aimport errno
4551N/Aimport fcntl
3652N/Aimport os
3652N/Aimport pwd
3652N/Aimport smf_include
4551N/Aimport socket
3652N/Aimport subprocess
3652N/Aimport sys
4551N/Aimport tempfile
3998N/Aimport time
3652N/A
4551N/Afrom oslo_config import cfg
3652N/A
3998N/AGTF = "/usr/bin/gtf"
4551N/ASVCADM = "/usr/sbin/svcadm"
3652N/ASVCCFG = "/usr/sbin/svccfg"
3652N/ASVCPROP = "/usr/bin/svcprop"
3652N/AVNCSERVER = "/usr/bin/vncserver"
3998N/AXRANDR = "/usr/bin/xrandr"
4551N/ANOVACFG = "/etc/nova/nova.conf"
3652N/AXSTARTUPHDR = "# WARNING: THIS FILE GENERATED BY SMF.\n" + \
3652N/A "# DO NOT EDIT THIS FILE. EDITS WILL BE LOST.\n"
4046N/AXRESOURCES = "[[ -f ~/.Xresources ]] && /usr/bin/xrdb -merge ~/.Xresources\n"
3652N/AXTERM = "/usr/bin/xterm"
3998N/A# Borderless, Monospsce font, point size 14, white foreground on black
3998N/A# background are reasonable defaults.
3998N/AXTERMOPTS = ' -b 0 -fa Monospace -fs 14 -fg white -bg black -title ' + \
3998N/A '"Zone Console: $ZONENAME"'
3998N/AXWININFO = "/usr/bin/xwininfo"
4551N/A
4551N/A# Port ranges allocated for VNC and X11 sockets.
4551N/AVNCPORT_START = 5900
4551N/AVNCPORT_END = 5999
4551N/AX11PORT_START = 6000
4551N/A
3652N/A# Enclose command in comments to prevent xterm consuming zlogin opts
3652N/AZLOGINOPTS = ' -e "/usr/bin/pfexec /usr/sbin/zlogin -C -E $ZONENAME"\n'
4046N/AXSTARTUP = XSTARTUPHDR + XRESOURCES + XTERM + XTERMOPTS + ZLOGINOPTS
3652N/A
4551N/ACONF = cfg.CONF
4551N/ACONF.import_opt('vncserver_listen', 'nova.vnc')
4551N/A
3652N/A
3652N/Adef start():
4551N/A fmri = os.environ['SMF_FMRI']
4551N/A # This is meant to be an on-demand service.
4551N/A # Determine if nova-compute requested enablement of this instance.
4551N/A # Exit with SMF_EXIT_TEMP_DISABLE if not true.
4551N/A cmd = [SVCPROP, '-p', 'vnc/nova-enabled', fmri]
4551N/A svcprop = subprocess.Popen(cmd, stdout=subprocess.PIPE,
4551N/A stderr=subprocess.PIPE)
4551N/A out, err = svcprop.communicate()
4551N/A retcode = svcprop.wait()
4551N/A if retcode != 0:
4551N/A print "Error reading 'vnc/nova-enabled' property: " + err
4551N/A return smf_include.SMF_EXIT_ERR_FATAL
4551N/A enabled = out.strip() == 'true'
4551N/A if not enabled:
4551N/A smf_include.smf_method_exit(
4551N/A smf_include.SMF_EXIT_TEMP_DISABLE,
4551N/A "nova_enabled",
4551N/A "nova-compute starts this service on demand")
4551N/A
3652N/A check_vncserver()
3652N/A homedir = os.environ.get('HOME')
3652N/A if not homedir:
3652N/A homedir = pwd.getpwuid(os.getuid()).pw_dir
3652N/A os.putenv("HOME", homedir)
3652N/A set_xstartup(homedir)
4551N/A display = None
4551N/A vncport = None
3652N/A
3652N/A try:
3652N/A zonename = fmri.rsplit(':', 1)[1]
3652N/A os.putenv("ZONENAME", zonename)
3652N/A desktop_name = zonename + ' console'
4551N/A novacfg = ConfigParser.RawConfigParser()
4551N/A novacfg.readfp(open(NOVACFG))
4551N/A try:
4551N/A vnc_listenip = novacfg.get("DEFAULT", "vncserver_listen")
4551N/A except ConfigParser.NoOptionError:
4551N/A vnc_listenip = CONF.vncserver_listen
4551N/A
4551N/A with lock_available_port(vnc_listenip, VNCPORT_START, VNCPORT_END,
4551N/A homedir) as n:
4551N/A # NOTE: 'geometry' is that which matches the size of standard
4551N/A # 80 character undecorated xterm window using font style specified
4551N/A # in XTERMOPTS. The geometry doesn't matter too much because the
4551N/A # display will be resized using xrandr once the xterm geometry is
4551N/A # established.
4551N/A display = ":%d" % n
4551N/A cmd = [VNCSERVER, display, "-name", desktop_name,
4551N/A "-SecurityTypes=None", "-geometry", "964x580",
4551N/A "-interface", vnc_listenip, "-autokill"]
4551N/A
4551N/A vncport = VNCPORT_START + n
4551N/A x11port = X11PORT_START + n
4551N/A print "Using VNC server port: " + str(vncport)
4551N/A print "Using X11 server port: %d, display %s" % (x11port, display)
4551N/A vnc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
4551N/A stderr=subprocess.PIPE, env=None)
4551N/A out, err = vnc.communicate()
4551N/A vncret = vnc.wait()
3652N/A if vncret != 0:
3652N/A print "Error starting VNC server: " + err
3652N/A return smf_include.SMF_EXIT_ERR_FATAL
3652N/A except Exception as e:
3652N/A print e
3652N/A return smf_include.SMF_EXIT_ERR_FATAL
3652N/A
4551N/A # set SMF instance port num prop
4551N/A cmd = [SVCCFG, '-s', fmri, 'setprop', 'vnc/port', '=', 'integer:',
4551N/A str(vncport)]
3652N/A
4551N/A svccfg = subprocess.Popen(cmd, stdout=subprocess.PIPE,
4551N/A stderr=subprocess.PIPE)
4551N/A out, err = svccfg.communicate()
4551N/A retcode = svccfg.wait()
4551N/A if retcode != 0:
4551N/A print "Error updating 'vnc/port' property: " + err
4551N/A return smf_include.SMF_EXIT_ERR_FATAL
3998N/A resize_xserver(display, zonename)
3998N/A
3652N/A return smf_include.SMF_EXIT_OK
3652N/A
3652N/A
3652N/Adef stop():
3652N/A try:
3652N/A # first kill the SMF contract
4551N/A subprocess.check_call(["/usr/bin/pkill", "-c", sys.argv[2]])
4551N/A except subprocess.CalledProcessError as cpe:
3652N/A # 1 is returncode if no SMF contract processes were matched,
3652N/A # meaning they have already terminated.
3652N/A if cpe.returncode != 1:
3652N/A print "failed to kill the SMF contract: %s" % cpe
3652N/A return smf_include.SMF_EXIT_ERR_FATAL
3652N/A
3652N/A try:
3652N/A fmri = os.environ['SMF_FMRI']
3652N/A # reset port num prop to initial zero value
3652N/A cmd = [SVCCFG, '-s', fmri, 'setprop', 'vnc/port', '=', 'integer:',
3652N/A '0']
3652N/A svccfg = subprocess.Popen(cmd, stdout=subprocess.PIPE,
3652N/A stderr=subprocess.PIPE,)
3652N/A out, err = svccfg.communicate()
3652N/A retcode = svccfg.wait()
3652N/A if retcode != 0:
3652N/A print "Error resetting 'vnc/port' property: " + err
3652N/A return smf_include.SMF_EXIT_ERR_FATAL
3652N/A except Exception as e:
3652N/A print e
3652N/A return smf_include.SMF_EXIT_ERR_FATAL
3652N/A
3652N/A
3652N/Adef check_vncserver():
3652N/A if not os.path.exists(VNCSERVER):
3652N/A print("VNC console service not available on this compute node. "
3652N/A "%s is missing. Run 'pkg install x11/server/xvnc'"
3652N/A % VNCSERVER)
3652N/A return smf_include.SMF_EXIT_ERR_FATAL
3652N/A if not os.path.exists(XTERM):
3652N/A print("VNC console service not available on this compute node. "
3652N/A "%s is missing. Run 'pkg install terminal/xterm'"
3652N/A % XTERM)
3652N/A return smf_include.SMF_EXIT_ERR_FATAL
3652N/A
3652N/A
3652N/Adef set_xstartup(homedir):
3652N/A vncdir = os.path.join(homedir, '.vnc')
3652N/A xstartup_path = os.path.join(vncdir, 'xstartup')
3652N/A
3652N/A try:
3652N/A os.mkdir(vncdir)
3652N/A except OSError as ose:
3652N/A if ose.errno != errno.EEXIST:
3652N/A raise
3652N/A
3652N/A # Always clobber xstartup
3652N/A # stemp tuple = [fd, path]
4551N/A stemp = tempfile.mkstemp(dir=vncdir)
3652N/A os.write(stemp[0], XSTARTUP)
3652N/A os.close(stemp[0])
3652N/A os.chmod(stemp[1], 0700)
3652N/A os.rename(stemp[1], xstartup_path)
3652N/A
3652N/A
3998N/Adef resize_xserver(display, zonename):
3998N/A """ Try to determine xterm window geometry and resize the Xvnc display
3998N/A to match using XRANDR. Treat failure as non-fatal since an
3998N/A incorrectly sized console is arguably better than none.
3998N/A """
4046N/A class UninitializedWindowError(Exception):
4046N/A pass
4046N/A
3998N/A class UnmappedWindowError(Exception):
3998N/A pass
3998N/A
3998N/A def _get_window_geometry(display, windowname):
3998N/A """ Find the xterm xwindow by name/title and extract its geometry
3998N/A Returns: tuple of window [width, height]
4046N/A Raises:
4046N/A UninitializedWindowError if window not yet initialized
4046N/A UnmappedWindowError if window is not viewable/mapped
3998N/A """
3998N/A cmd = [XWININFO, '-d', display, '-name', windowname]
3998N/A xwininfo = subprocess.Popen(cmd, stdout=subprocess.PIPE,
3998N/A stderr=subprocess.PIPE)
3998N/A out, err = xwininfo.communicate()
3998N/A retcode = xwininfo.wait()
3998N/A if retcode != 0:
3998N/A print "Error finding console xwindow info: " + err
4046N/A raise UninitializedWindowError
3998N/A
3998N/A width = None
3998N/A height = None
3998N/A mapped = False
3998N/A for line in out.splitlines():
3998N/A line = line.strip()
3998N/A if line.startswith("Map State:"):
3998N/A if line.split()[-1] != "IsViewable":
3998N/A # Window is not mapped yet.
3998N/A raise UnmappedWindowError
3998N/A else:
3998N/A mapped = True
3998N/A if line.startswith("Width:"):
3998N/A width = int(line.split()[1])
3998N/A elif line.startswith("Height:"):
3998N/A height = int(line.split()[1])
3998N/A if width and height and mapped:
3998N/A return [width, height]
3998N/A else:
3998N/A # What, no width and height???
3998N/A print "No window geometry info returned by " + XWINFINFO
3998N/A raise UnmappedWindowError
3998N/A
4046N/A retries = 10
4046N/A sleep = 1
4046N/A uninit_count = 0
4046N/A unmap_count = 0
3998N/A width = 0
3998N/A height = 0
4046N/A while uninit_count < retries and unmap_count < retries:
3998N/A try:
3998N/A width, height = _get_window_geometry(display,
3998N/A 'Zone Console: ' + zonename)
3998N/A print "Discovered xterm geometry: %d x %d" % (width, height)
3998N/A break
4046N/A except UninitializedWindowError:
4046N/A if uninit_count < retries:
4046N/A print "xterm window not initialized yet. Retrying in %ds" \
4046N/A % sleep
4046N/A uninit_count += 1
4046N/A time.sleep(sleep)
4046N/A continue
4046N/A else:
4046N/A print "xterm window is taking too long to initialize"
4046N/A break
3998N/A except UnmappedWindowError:
4046N/A if unmap_count < retries:
4046N/A print "Discovered xterm not mapped yet. Retrying in %ds" \
4046N/A % sleep
4046N/A unmap_count += 1
4046N/A time.sleep(sleep)
3998N/A continue
3998N/A else:
3998N/A print "Discovered xterm window is taking too long to map"
4046N/A break
3998N/A else:
3998N/A print "Too many failed attempts to discover xterm window geometry"
3998N/A return
3998N/A
3998N/A # Generate a mode line for width and height, with a refresh of 60.0Hz
3998N/A cmd = [GTF, str(width), str(height), '60.0', '-x']
3998N/A gtf = subprocess.Popen(cmd, stdout=subprocess.PIPE,
3998N/A stderr=subprocess.PIPE)
3998N/A out, err = gtf.communicate()
3998N/A retcode = gtf.wait()
3998N/A if retcode != 0:
3998N/A print "Error creating new modeline for VNC display: " + err
3998N/A return
3998N/A
3998N/A for line in out.splitlines():
3998N/A line = line.strip()
3998N/A if line.startswith('Modeline'):
3998N/A modeline = line.split('Modeline')[1]
3998N/A print "New optimal modeline for Xvnc server: " + modeline
3998N/A mode = modeline.split()
3998N/A break
3998N/A
3998N/A # Create a new mode for the Xvnc server using the modeline generated by gtf
3998N/A cmd = [XRANDR, '-d', display, '--newmode']
3998N/A cmd.extend(mode)
3998N/A newmode = subprocess.Popen(cmd, stdout=subprocess.PIPE,
3998N/A stderr=subprocess.PIPE)
3998N/A out, err = newmode.communicate()
3998N/A retcode = newmode.wait()
3998N/A if retcode != 0:
3998N/A print "Error creating new xrandr modeline for VNC display: " + err
3998N/A return
3998N/A
3998N/A # Add the new mode to the default display output
3998N/A modename = mode[0]
3998N/A cmd = [XRANDR, '-d', display, '--addmode', 'default', modename]
3998N/A addmode = subprocess.Popen(cmd, stdout=subprocess.PIPE,
3998N/A stderr=subprocess.PIPE)
3998N/A out, err = addmode.communicate()
3998N/A retcode = addmode.wait()
3998N/A if retcode != 0:
3998N/A print "Error adding new xrandr modeline for VNC display: " + err
3998N/A return
3998N/A
3998N/A # Activate the new mode on the default display output
3998N/A cmd = [XRANDR, '-d', display, '--output', 'default', '--mode', modename]
3998N/A addmode = subprocess.Popen(cmd, stdout=subprocess.PIPE,
3998N/A stderr=subprocess.PIPE)
3998N/A out, err = addmode.communicate()
3998N/A retcode = addmode.wait()
3998N/A if retcode != 0:
3998N/A print "Error setting new xrandr modeline for VNC display: " + err
3998N/A return
3998N/A
4551N/A
4551N/A@contextlib.contextmanager
4551N/Adef lock_available_port(address, port_start, port_end, lockdir):
4551N/A """Ensures instance exclusive use of VNC, X11 service ports
4551N/A and related resources.
4551N/A Generator yields an integer of the port relative to port_start to use.
4551N/A eg. 32: VNC port 5932, X11 port 6032, X11 display :32
4551N/A lockfile is port specific and prevents multiple instances from
4551N/A attempting to use the same port number during SMF start method
4551N/A execution.
4551N/A Socket binding on address:port establishes that the port is not
4551N/A already in use by another Xvnc process
4551N/A """
4551N/A for n in range(port_end - port_start):
4551N/A vncport = port_start + n
4551N/A x11port = X11PORT_START + n
4551N/A lockfile = os.path.join(lockdir, '.port-%d.lock' % vncport)
4551N/A try:
4551N/A # Acquire port file lock first to lock out other instances trying
4551N/A # to come online in parallel. They will grab the next available
4551N/A # port lock.
4551N/A lock = open(lockfile, 'w')
4551N/A fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
4551N/A
4551N/A try:
4551N/A # Check the VNC/RFB and X11 ports.
4551N/A for testport in [vncport, x11port]:
4551N/A sock = socket.socket(socket.AF_INET)
4551N/A sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
4551N/A try:
4551N/A sock.bind((address, testport))
4551N/A finally:
4551N/A sock.close()
4551N/A
4551N/A # Ensure the standard X11 locking files are not present
4551N/A # /tmp/.X<n>-lock
4551N/A # /tmp/X11-unix/X<n>
4551N/A xfiles = ['/tmp/.X%d-lock' % n,
4551N/A '/tmp/X11-unix/X%d' % n]
4551N/A for xfile in xfiles:
4551N/A if os.path.exists(xfile):
4551N/A print ("Warning: X11 display :{0} is taken because of "
4551N/A "{1}\nRemove this file if there is no X "
4551N/A "server on display :{0}".format(str(n), xfile))
4551N/A raise Exception
4551N/A
4551N/A except (socket.error, Exception):
4551N/A lock.close()
4551N/A os.remove(lockfile)
4551N/A continue
4551N/A # Yay, we found a free VNC/X11 port pair.
4551N/A yield n
4551N/A lock.close()
4551N/A os.remove(lockfile)
4551N/A break
4551N/A except IOError:
4551N/A print "Port %d already reserved, skipping" % vncport
4551N/A
3652N/Aif __name__ == "__main__":
3652N/A os.putenv("LC_ALL", "C")
3652N/A smf_include.smf_main()