Permalink
Switch branches/tags
Nothing to show
Find file
Fetching contributors…
Cannot retrieve contributors at this time
219 lines (191 sloc) 7.93 KB
#! /usr/bin/env python
###############################################################################
# Copyright (c) 2008-2009 VMware, Inc.
#
# This file is part of Weasel.
#
# Weasel is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation version 2 and no later version.
#
# Weasel is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# version 2 for more details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
#
'''
workarounds
The intent of this module is to store code that doesn't belong in Weasel,
but code that does important things in order for the install to happen
properly.
As functionality is added to vmkctl and the COS scripts (esxcfg-*, etc),
the functions within this module can be deleted and we should eventually
get to the point where this file will eventually disappear.
'''
import os
import glob
import shutil
import errno
import consts
import util
import struct
import vmkctl
from log import log
import urlparse
import remote_files
import userchoices
def ChangeNetworkScriptsToBash():
import glob
files = glob.glob('/etc/sysconfig/network-scripts/if*')
for fname in files:
fp = open(fname,'r')
contents = fp.read()
fp.close()
if contents.startswith( '#!/bin/sh' ) or contents.startswith('#! /bin/sh'):
contents = '#! /bin/bash\n' + contents
fp = open(fname,'w')
fp.write(contents)
fp.close()
def BlacklistIPv6Driver():
if not os.path.exists("/etc/modprobe.d"):
os.makedirs("/etc/modprobe.d")
fp = open('/etc/modprobe.d/blacklist', 'w')
fp.write('# automatically generated by the workaround module\n')
fp.close()
def WriteMissingNetworkConfigFiles():
# dhclient writes to /etc/ntp.conf with any ntp servers it
# discovers, but only if the ntp.conf file already exists.
util.execCommand('touch /etc/ntp.conf')
if not os.path.exists('/etc/xinetd.d'):
# XXX Used by NetworkInfoImpl::SetCosIpv6Enabled().
os.makedirs('/etc/xinetd.d')
def CopyConfigFilesToCOS():
instRoot = '/mnt/sysimage'
shutil.copy('/etc/ntp.conf', instRoot + '/etc/ntp.conf' )
def TouchAuthFiles():
# XXX should these files be in an rpm we install? They seem to be needed
# by esxcfg-auth.
open("/mnt/sysimage/etc/krb.realms", "w").close()
open("/mnt/sysimage/etc/yp.conf", "w").close()
def PrepareSystemForNetworking():
WriteMissingNetworkConfigFiles()
ChangeNetworkScriptsToBash()
#os.system( 'ln -s /usr/bin/bash /bin/bash' )
#os.system( 'ln -s /etc/rc.d/init.d /etc/init.d' )
def hostActionCopyConfig(_context):
try:
CopyConfigFilesToCOS()
BlacklistIPv6Driver()
except Exception:
log.exception('Copying the config files to the COS failed')
def setSwapUUID(devicePath):
import fsset
# TODO: The current version of busybox's mkswap does not write out a
# UUID, so we have to do it manually. Update busybox or use a real
# mkswap so we don't have to do this...
while True:
uuid = open("/proc/sys/kernel/random/uuid").read()
# libblkid does not believe a swap uuid can start with zero, so we have
# to spin until we get a "valid" one. See bug 269129.
if not uuid.startswith('00'):
break
uuidBits = util.uuidStringToBits(uuid)
devFile = open(devicePath, 'w')
devFile.seek(struct.calcsize(fsset.swapFileSystem.headerFmt) -
len(uuidBits))
devFile.write(uuidBits)
devFile.close()
def rebuildRpmDb():
instRoot = '/mnt/sysimage'
for path in glob.glob(os.path.join(instRoot, "var/lib/rpm/__db.0*")):
os.remove(path)
args = ["/bin/rpm", "--rebuilddb"]
status = util.execWithLog(args[0], args, root=instRoot)
assert status == 0
def hostActionRedirectLKMLoading(_context):
'''Enables automatic kernel module loading so that the modules are pulled
from the installed system.'''
# Write out our replacement for modprobe, which just does a chroot and runs
# the modprobe in there.
MODPROBE_PATH = "/sbin/modprobe"
try:
shutil.move(MODPROBE_PATH, "%s.nonchroot" % MODPROBE_PATH)
except Exception, e:
log.debug("cannot move away old modprobe -- %s" % str(e))
chrootModprobe = open(MODPROBE_PATH, "w")
chrootModprobe.write("#! /bin/bash\n"
"chroot %s %s $*\n" % (
consts.HOST_ROOT, MODPROBE_PATH))
chrootModprobe.close()
os.chmod(MODPROBE_PATH, 0555)
def hostActionSetCosMemory(_context):
'''Tells vmkctl to set the Console OS memory size. This is also done
in the bootloader, however vmkctl will nuke it upon rebooting.
'''
from precheck import getConsoleMemorySize # avoid circular imports
mem = vmkctl.MemoryInfoImpl()
currentMemSize = mem.GetServiceConsoleReservedMem()
cosMemory = getConsoleMemorySize(currentMemSize,
mem.GetPhysicalMemory() / 1024 / 1024)
mem.SetServiceConsoleReservedMem(cosMemory, True)
def hostActionUpdateEsxupdateDatabase(_context):
'''Updates the esxudpate database with any meta-data on the source image.'''
# In a nutshell:
# 1. Copy metadata.zip from source image to host root (/mnt/sysimage).
# 2. Run esxupdate syncdb command in /mnt/sysimage chroot.
# 3. Remove metadata.zip from host root.
# It would be nice if we could just import an esxupdate module and call a
# function or method to do this. Unfortunately, esxupdate has a lot of
# dependencies on configuration files and a database being in a certain
# place, so it's just easier to call the esxupdate command line from a
# chroot environment.
mediaroot = userchoices.getMediaLocation().get(
'mediaLocation',
'file://' + consts.MEDIA_DEVICE_MOUNT_POINT
)
if not mediaroot.endswith('/'):
mediaroot += '/'
metasrc = urlparse.urljoin(mediaroot, 'metadata.zip')
# Squelching any metadata.zip errors/warnings. See PR:428781
# We increase the log level required to print to tty6 to a ridiculous level,
# then return it to normal.
import scui
err = None
if scui.tty6Handler:
prevLevel = scui.tty6Handler.level
scui.tty6Handler.setLevel(9001)
try:
metadst = remote_files.downloadLocally(metasrc, clobberCache = True)
if os.path.getsize(metadst) == 0:
log.warn("The server gave '%s' as an empty file" % metadst)
os.unlink(metadst)
err = True
except Exception, err:
# downloadLocally() function doesn't distinguish between not found and
# transfer or other error.
log.warn('Esxupdate meta-data not present or not retrievable: %s' % err)
if scui.tty6Handler:
scui.tty6Handler.setLevel(prevLevel)
if err:
return
if not metadst.startswith(consts.HOST_ROOT):
# If file was not downloaded to somewhere under HOST_ROOT, move it.
try:
tmploc = os.path.join(consts.HOST_ROOT, 'tmp', 'metadata.zip')
shutil.move(metadst, tmploc)
metadst = tmploc
except Exception, e:
log.warn('Unable to move esxupdate meta-data to host root: %s' % e)
return
metachroot = os.path.join('/', metadst[len(consts.HOST_ROOT):])
args = ['/usr/sbin/esxupdate', 'syncdb', '-m', metachroot]
if util.execWithLog(args[0], args, root=consts.HOST_ROOT):
log.warn('Failed to import esxupdate database information.')
try:
os.unlink(metadst)
except Exception, e:
log.warn('Failed to remove esxupdate meta-data after import: %s' % e)