def testfilePutGetContentStr(self): _, filename = tempfile.mkstemp() try: Util.filePutContent(filename, str('Element')) assert 'Element' == Util.fileGetContent(filename) finally: os.unlink(filename)
def _configureNetworkInterface(self, device, ip, netmask): deviceConf = '/etc/sysconfig/network-scripts/ifcfg-%s' % device data = """DEVICE=%s IPADDR=%s NETMASK=%s """ % (device, ip, netmask) Util.filePutContent(deviceConf, data)
def testfilePutGetContentUnicode(self): _, filename = tempfile.mkstemp() try: Util.filePutContent(filename, unicode('Élément', encoding='utf8')) assert 'Élément' == Util.fileGetContent(filename) finally: os.unlink(filename)
def _writeToFilesRemote(self, listOfFileNameContentTuples): tmpFilename = tempfile.mktemp() for remoteFilename, content in listOfFileNameContentTuples: Util.filePutContent(tmpFilename, content) self._nodeCopy(tmpFilename, remoteFilename) try: os.unlink(tmpFilename) except: pass
def buildAndSave(self, filename=''): manifestText = self.build() if not filename: filename = '%s-%s-%s-%s-%s%s' % (self.os, self.osversion, self.arch, self.type, self.version, Util.manifestExt) Util.filePutContent(filename, manifestText) Util.printDetail("Manifest: %s" % filename, self.verboseLevel, Util.VERBOSE_LEVEL_DETAILED)
def downloadVolume(self, uuid, filename): # Don't cache http response as it will contain the image in the body. configHolder = self.configHolder.copy() configHolder.set('useHttpCache', False) self._initPDiskConnection(configHolder=configHolder) self._printContacting() volumeUrl = '%s/disks/%s/' % (self.endpoint, uuid) headers, content = self._getGzip(volumeUrl) self._raiseOnErrors(headers, content) Util.filePutContent(filename, content, True)
def _configure(self): Util.printStep('Configuring OpenLDAP server') Util.printStep('Updating sysconfig') shutil.copyfile(self._sysconfigLdapTemplate, self._sysconfigLdap) Util.appendOrReplaceInFile(self._sysconfigLdap, 'SLAPD_LDAP=', 'SLAPD_LDAP=yes') Util.printStep('Setting root account access') Util.appendOrReplaceMultilineBlockInFile(self._openLdapConfig, self._accessValue, start='olcAccess: {0}to *', until='olcAddContentAcl:') Util.printStep('(Re-)starting slapd') cmd = 'service %s restart' % self._serviceName self._executeExitOnError(cmd) Util.printStep('Generating test certificate and moving into place') self._executeExitOnError(self._testCertCmd) self._executeExitOnError('mkdir -p /etc/openldap/cacerts') self._executeExitOnError('mv -f cacrt.jks /etc/openldap/cacerts/cacrt.jks') self._executeExitOnError('mv -f cacrt.pem /etc/openldap/cacerts/cacrt.pem') self._executeExitOnError('mv -f serverkey.pem /etc/openldap/serverkey.pem') self._executeExitOnError('mv -f servercrt.pem /etc/openldap/servercrt.pem') os.chmod('/etc/openldap/serverkey.pem', stat.S_IRUSR | stat.S_IWUSR) self._executeExitOnError('chown ldap:ldap /etc/openldap/serverkey.pem') Util.printStep('Updating server config. for generated certs') cmd = "ldapmodify -Y EXTERNAL -H ldapi:/// -f %s" % self._certConfigLdif Util.execute(cmd.split(' ')) Util.printStep('Updating client config. for generated certs') Util.appendOrReplaceInFile(self._ldapClientConfig, 'TLS_CACERT', 'TLS_CACERT /etc/openldap/cacerts/cacrt.pem') Util.printStep('Creating o=cloud database') Util.filePutContent(self._completeDatabaseTemplate, Util.fileGetContent(self._databaseTemplate) % self.__dict__) cmd = "ldapadd -Y EXTERNAL -H ldapi:/// -f %s" % self._completeDatabaseTemplate Util.execute(cmd.split(' ')) Util.printStep('Adding cloud database entries') cmd = "ldapadd -x -H ldaps://%s -D %s -w %s -f %s" % (self._nodename, self._openLdapAdminDn, self.openldapPassword, self._cloudDatabaseSkeleton) self._executeExitOnError(cmd)
def _fixUdevForLvmMonitoring(self): """See the issue: https://bugzilla.redhat.com/show_bug.cgi?id=577798#c5 1. Modify 80-udisks.rules 2. Install a cron job to modify 80-udisks.rules file to safeguard against udev package updates. """ fileName = '/lib/udev/rules.d/80-udisks.rules' if not os.path.exists(fileName): return search = 'KERNEL=="dm-*", OPTIONS+="watch"' replace = '#KERNEL=="dm-*", OPTIONS+="watch"' if re.search('^KERNEL=="dm-\*", OPTIONS\+="watch"', Util.fileGetContent(fileName), re.MULTILINE): Util.appendOrReplaceInFile(fileName, search, replace) #self.system.restartService('udev') data = """*/15 * * * * root sed -i -e 's/^KERNEL==\"dm-\*\", OPTIONS+=\"watch\"/%s/' %s""" % \ (replace, fileName) Util.filePutContent('/etc/cron.d/fix-udev-for-lvm-monitoring.cron', data)
def addRepositories(self, packages): """Accepts package names and aliases as defined in self.packages. """ repos = [] for pkgName in packages: repo = '' if pkgName in self.packages: repo = self.packages[pkgName].repository else: for pkgInfo in self.packages.values(): if pkgInfo.packageName == pkgName: repo = pkgInfo.repository if repo and repo not in repos: repos.append(repo) for repo in repos: if repo in self.extraRepos: filename = self.extraRepos[repo]['filename'] content = self.extraRepos[repo]['content'] Util.filePutContent(filename, content) else: Util.printError("Repository '%s' is not defined in the extra list of repositories (%s)." % \ (repo, ', '.join(self.extraRepos)))
def _confgureDhcp(self): def _isAllDhcpGroupsDefined(_groups): return all(_groups.values()) def _getConfGlobals(): _globals = """ ddns-update-style none; ignore unknown-clients; ignore bootp; """ if hasattr(self, 'dhcpNtpServers') and self.dhcpNtpServers: _globals += 'option ntp-servers %s;\n' % self.dhcpNtpServers return _globals def _getConfSubnets(): subnetTemplate = """ subnet %(subnet)s netmask %(netmask)s { option routers %(routers)s; } """ subnet = '' # All net types are defined together with NATing. Assuming NATing for # Local net type. Need to create a shared network. if Util.isTrueConfVal(self.nat) and _isAllDhcpGroupsDefined(dhcpGroups): subnet = """ shared-network StratusLab-LAN { """ for _type in self.NET_TYPES_DHCP: subnet += subnetTemplate % { 'subnet' : getattr(self, self._assembleDhcpAttributeName('%sSubnet' % _type)), 'netmask' : getattr(self, self._assembleDhcpAttributeName('%sNetmask' % _type)), 'routers' : getattr(self, self._assembleDhcpAttributeName('%sRouters' % _type))} subnet += "}\n" elif Util.isTrueConfVal(self.nat) and dhcpGroups['OneLocalNetwork']: subnet = """ shared-network StratusLab-LAN { """ # main interface subnet += """ subnet %(subnet)s netmask %(netmask)s { } """ % {'subnet' : self.dhcpSubnet, 'netmask' : self.dhcpNetmask} # virtual interface natGateway = getattr(self, 'natGateway', '') if not natGateway: natGateway = Util.gatewayIpFromNetAddress(self.natNetwork) subnet += subnetTemplate % {'subnet' : self.natNetwork, 'netmask' : self.natNetmask, 'routers' : natGateway} subnet += "}\n" elif dhcpGroups['OnePublicNetwork']: # main interface subnet += """ subnet %(subnet)s netmask %(netmask)s { } """ % {'subnet' : self.dhcpSubnet, 'netmask' : self.dhcpNetmask} elif dhcpGroups['OneLocalNetwork']: # virtual interface subnet = subnetTemplate % { 'subnet' : self.dhcpOneLocalNetworkSubnet, 'netmask' : self.dhcpOneLocalNetworkNetmask, 'routers' : self.dhcpOneLocalNetworkRouters} else: Util.printWarning('Invalid parameters combination to configure DHCP.') return subnet def _getConfGroups(): groupHeadTemplate = """ group { option broadcast-address %(broadcast)s; option subnet-mask %(netmask)s; option routers %(routers)s; option domain-name "%(domainName)s"; option domain-name-servers %(nameservers)s; """ hostTemplate = """ host %(type)s-vm%(id)s { hardware ethernet %(mac)s; fixed-address %(ip)s; max-lease-time %(leaseTime)s; } """ groups = '' for _type,ipsMacs in dhcpGroups.items(): if not ipsMacs: continue groups += groupHeadTemplate % \ {'broadcast' : getattr(self, self._assembleDhcpAttributeName('%sBroadcast' % _type)), 'netmask' : getattr(self, self._assembleDhcpAttributeName('%sNetmask' % _type)), 'routers' : getattr(self, self._assembleDhcpAttributeName('%sRouters' % _type)), 'domainName' : getattr(self, self._assembleDhcpAttributeName('%sDomainName' % _type)), 'nameservers' : getattr(self, self._assembleDhcpAttributeName('%sDomainNameServers' % _type))} hosts = '' for i,ipMac in enumerate(ipsMacs): hosts += hostTemplate % {'type' : _type.lower(), 'id' : str(i), 'mac' : ipMac[1], 'ip' : ipMac[0], 'leaseTime' : self.dhcpLeaseTime} groups += hosts groups += '}\n' return groups Util.printDetail('Configuring DHCP server.') _NOTHING = [] dhcpGroups = dict.fromkeys(self.NET_TYPES_DHCP, _NOTHING) for netType in self.NET_TYPES_DHCP: if Util.isTrueConfVal(getattr(self, self._assembleDhcpAttributeName(netType), False)): dhcpGroups[netType] = self.__getIpMacTuplesForNetworkType(netType) if not any(dhcpGroups.values()): Util.printError('When configuring DHCP %s networks IP/MAC pairs should be given.' % ','.join(self.NET_TYPES_DHCP)) content = _getConfGlobals() + \ _getConfSubnets() + \ _getConfGroups() confFile = self.getPackageConfigFileName('dhcp') Util.filePutContent(confFile, content)