Esempio n. 1
0
def getWebserverUsernameAndGroupname():
    '''
	Returns the name of the user and group belonging to the webserver \
in the default configuration.

	:raises RuntimeError: If running on an Unsupported distribution.
	'''
    if isDebian() or isUbuntu() or isUCS():
        return 'www-data', 'www-data'
    elif isOpenSUSE() or isSLES():
        return 'wwwrun', 'www'
    elif isCentOS() or isRHEL():
        return 'apache', 'apache'
    else:
        raise RuntimeError("Unsupported distribution.")
Esempio n. 2
0
def getWebserverRepositoryPath():
    """
	Returns the path to the directory where packages for Linux netboot \
installations may be.

	On an unsuported distribution or without the relevant folder
	existing `None` will be returned.
	"""
    if any(func() for func in (isDebian, isCentOS, isRHEL, isUbuntu)):
        path = u'/var/www/html/opsi'
    elif isUCS():
        path = u'/var/www/opsi'
    elif isOpenSUSE() or isSLES():
        path = u'/srv/www/htdocs/opsi'
    else:
        LOGGER.info("Unsupported distribution.")
        return

    if not os.path.exists(path):
        LOGGER.debug(u"Oops, found path {0!r} but does not exist.", path)
        path = None

    return path
Esempio n. 3
0
def setDefaultWorkbenchLocation(backend):
	"""
	Set the possibly missing workbench location on the server.

	The value is regarded as missing if it is not set to None.
	`workbenchLocalUrl` will be set to `file:///var/lib/opsi/workbench`
	on SUSE system and to `file:///home/opsiproducts` on others.
	`workbenchRemoteUrl` will use the same value for the depot address
	that is set in `depotRemoteUrl` and then will point to the samba
	share _opsi_workbench_.
	"""
	servers = backend.host_getObjects(type=["OpsiDepotserver", "OpsiConfigserver"])

	if isSLES() or isOpenSUSE():
		# On Suse
		localWorkbenchPath = u'file:///var/lib/opsi/workbench'
	else:
		# On non-SUSE systems the path was usually /home/opsiproducts
		localWorkbenchPath = u'file:///home/opsiproducts'

	changedServers = set()
	for server in servers:
		if server.getWorkbenchLocalUrl() is None:
			LOGGER.notice("Setting missing value for workbenchLocalUrl on {} to {}", server.id, localWorkbenchPath)
			server.setWorkbenchLocalUrl(localWorkbenchPath)
			changedServers.add(server)

		if server.getWorkbenchRemoteUrl() is None:
			depotAddress = getServerAddress(server.depotRemoteUrl)
			remoteWorkbenchPath = u'smb://{}/opsi_workbench'.format(depotAddress)
			LOGGER.notice("Setting missing value for workbenchRemoteUrl on {} to {}", server.id, remoteWorkbenchPath)
			server.setWorkbenchRemoteUrl(remoteWorkbenchPath)
			changedServers.add(server)

	if changedServers:
		backend.host_updateObjects(changedServers)
Esempio n. 4
0
def getPxeDirectory():
    if isSLES() or isOpenSUSE():
        return u'/var/lib/tftpboot/opsi'
    else:
        return u'/tftpboot/linux'
Esempio n. 5
0
def configureDHCPD(configFile=DHCPD_CONF):
    """
	Configure the configuration file for DHCPD.

	If any changes are made the original file will be backed up.
	The backup file has a timestamp appended to the filename.

	:param configFile: The configuration file for DHCP.
	"""
    if not os.path.exists(configFile):
        logger.warning("Can't find an dhcpd.conf. Aborting configuration.")
        return

    sysConfig = getNetworkConfiguration()
    logger.notice(u"Configuring dhcpd")

    dhcpdConf = DHCPDConfFile(configFile)
    dhcpdConf.parse()

    confChanged = False
    if dhcpdConf.getGlobalBlock().getParameters_hash().get(
            'use-host-decl-names', False):
        logger.info(u"  use-host-decl-names already enabled")
    else:
        confChanged = True
        logger.notice(u"  enabling use-host-decl-names")
        dhcpdConf.getGlobalBlock().addComponent(
            DHCPDConf_Parameter(startLine=-1,
                                parentBlock=dhcpdConf.getGlobalBlock(),
                                key='use-host-decl-names',
                                value=True))

    subnets = dhcpdConf.getGlobalBlock().getBlocks('subnet', recursive=True)
    if not subnets:
        confChanged = True
        logger.notice(u"  No subnets found, adding subnet")
        dhcpdConf.getGlobalBlock().addComponent(
            DHCPDConf_Block(startLine=-1,
                            parentBlock=dhcpdConf.getGlobalBlock(),
                            type='subnet',
                            settings=[
                                'subnet', sysConfig['subnet'], 'netmask',
                                sysConfig['netmask']
                            ]))

    for subnet in dhcpdConf.getGlobalBlock().getBlocks('subnet',
                                                       recursive=True):
        logger.info(u"  Found subnet %s/%s" %
                    (subnet.settings[1], subnet.settings[3]))
        groups = subnet.getBlocks('group')
        if not groups:
            confChanged = True
            logger.notice(u"    No groups found, adding group")
            subnet.addComponent(
                DHCPDConf_Block(startLine=-1,
                                parentBlock=subnet,
                                type='group',
                                settings=['group']))

        for group in subnet.getBlocks('group'):
            logger.info(u"    Configuring group")
            params = group.getParameters_hash(inherit='global')

            if params.get('next-server'):
                logger.info(u"      next-server already set")
            else:
                confChanged = True
                group.addComponent(
                    DHCPDConf_Parameter(startLine=-1,
                                        parentBlock=group,
                                        key='next-server',
                                        value=sysConfig['ipAddress']))
                logger.notice(u"      next-server set to %s" %
                              sysConfig['ipAddress'])

            if params.get('filename'):
                logger.info(u"      filename already set")
            else:
                confChanged = True
                filename = 'linux/pxelinux.0'
                if isSLES() or isOpenSUSE():
                    filename = 'opsi/pxelinux.0'
                group.addComponent(
                    DHCPDConf_Parameter(startLine=-1,
                                        parentBlock=group,
                                        key='filename',
                                        value=filename))
                logger.notice(u"      filename set to %s" % filename)

    restartCommand = getDHCPDRestartCommand(
        default=u'/etc/init.d/dhcp3-server restart')
    if confChanged:
        logger.notice(u"  Creating backup of %s" % configFile)
        shutil.copy(configFile,
                    configFile + u'.' + time.strftime("%Y-%m-%d_%H:%M"))

        logger.notice(u"  Writing new %s" % configFile)
        dhcpdConf.generate()

        logger.notice(u"  Restarting dhcpd")
        try:
            execute(restartCommand)
        except Exception as error:
            logger.warning(error)

    logger.notice(u"Configuring sudoers")
    patchSudoersFileToAllowRestartingDHCPD(restartCommand)

    opsiconfdUid = pwd.getpwnam(OPSICONFD_USER)[2]
    adminGroupGid = grp.getgrnam(ADMIN_GROUP)[2]
    os.chown(configFile, opsiconfdUid, adminGroupGid)
    os.chmod(configFile, 0o664)

    if isRHEL() or isCentOS():
        dhcpDir = os.path.dirname(configFile)
        if dhcpDir == '/etc':
            return

        logger.notice(
            'Detected Red Hat-family system. Providing rights on "{dir}" '
            'to group "{group}"'.format(dir=dhcpDir, group=ADMIN_GROUP))
        os.chown(dhcpDir, -1, adminGroupGid)

    backendConfigFile = os.path.join('/etc', 'opsi', 'backends', 'dhcpd.conf')
    logger.notice('Configuring backend file {0}'.format(backendConfigFile))
    insertDHCPDRestartCommand(backendConfigFile, restartCommand)