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 __init__(self, configHolder): self.endpoint = None self.verboseLevel = 1 self.portTranslation = False self.portTranslationClient = None super(Monitor, self).__init__(configHolder) self._setCloud() self.hostInfoDetailAttributes = (['id', 4], ['name', 16], ['im_mad', 8], ['vm_mad', 8], ['tm_mad', 8]) self.hostInfoListAttributes = (['id', 4], ['name', 16]) self.vmInfoDetailAttributes = [['id', 4], ['state_summary', 10], ['template_vcpu', 5], ['memory', 10], ['cpu', 5], [Monitor.TEMPLATE_NIC_HOSTNAME, 24], ['name', 16]] self.vmInfoListAttributes = [['id', 4], ['state_summary', 10], ['template_vcpu', 5], ['memory', 10], ['cpu', 5], [Monitor.TEMPLATE_NIC_HOSTNAME, 24], ['name', 16]] self.labelDecorator = {'state_summary': 'state', Monitor.TEMPLATE_NIC_HOSTNAME: 'host/ip', Monitor.TEMPLATE_NIC_IP: 'ip', 'template_vcpu': 'vcpu', 'cpu': 'cpu%'} if Util.isTrueConfVal(self.portTranslation): self.portTranslationClient = PortTranslationWebClient(configHolder) self.vmInfoDetailAttributes.insert(-1, ['template_pat', 16]) self.vmInfoListAttributes.insert(-1, ['template_pat', 16]) self.labelDecorator['template_pat'] = 'pat(VM:GW)'
def _dhcpNetTypesDefined(): return any( [ Util.isTrueConfVal(getattr(self, self._assembleDhcpAttributeName(v), "False")) for v in self.NET_TYPES_DHCP ] )
def isTranslatedNetwork(self, network): return Util.isTrueConfVal(self.portTranslation) and network in self.patNetworks
def _httpCall(self, url, method, body=None, contentType="application/xml", accept="application/xml", retry=True): def _convertContent(content): size = len(content) if size > 2048: return "<content too large; %d bytes>" % size try: return unicode(content, "utf-8") except: return "<non-text content>" def _getErrorMessageFromJsonContent(content): try: return json.loads(content)["message"] except: return "" def _handle3xx(resp): if resp.status == 302: # Redirected resp, content = self._httpCall(resp["location"], method, body, accept) else: raise Exception("Should have been handled by httplib2!! " + str(resp.status) + ": " + resp.reason) return resp, content def _handle4xx(resp): error_message = _getErrorMessageFromJsonContent(content) raise ClientException( "Failed calling method %s on url %s, with reason: %s. Error: %s" % (method, url, str(resp.status) + ": " + resp.reason, error_message), content=content, status=str(resp.status), ) def _handle5xx(resp): if retry: return self._httpCall(url, method, body, contentType, accept, False) raise ServerException( "Failed calling method %s on url %s, with reason: %s" % (method, url, str(resp.status) + ": " + resp.reason), status=str(resp.status), ) def _handleResponse(resp, content): self._printDetail("Received response: %s" % resp + "\nwith content:\n %s" % _convertContent(content)) if str(resp.status).startswith("2"): return resp, content if str(resp.status).startswith("3"): resp, content = _handle3xx(resp) if str(resp.status).startswith("4"): resp, content = _handle4xx(resp) if str(resp.status).startswith("5"): resp, content = _handle5xx(resp) proxy = self.getHttpProxyForUrl(url) if Util.isTrueConfVal(self.useHttpCache): h = httplib2.Http(".cache", proxy_info=proxy) else: h = httplib2.Http(proxy_info=proxy) h.force_exception_to_status_code = False h.disable_ssl_certificate_validation = True self._printDetail("Contacting the server with %s, at: %s" % (method, url)) headers = {} if contentType: headers["Content-Type"] = contentType if accept: headers["Accept"] = accept # See https://github.com/StratusLab/client/issues/8 if method == "POST": self._addCredentialsToHeader(headers) self._addCredentials(h) self._addCertificate(h) try: resp, content = self._retryHttpRequestOnSSLError(h, url, method, body, headers) except httplib.BadStatusLine: raise NetworkException("BadStatusLine when contacting " + url) except AttributeError: raise NetworkException("Cannot contact " + url) if self.handleResponse: try: _handleResponse(resp, content) except ClientException, ex: ex.mediaType = headers["Accept"] raise
def _dhcpDefined(): return Util.isTrueConfVal(getattr(self, 'dhcp', 'False'))
def _isCertificateAuthority(): return Util.isTrueConfVal(getattr(self, 'certificateAuthority', False))
def addCloudAdminToExtraGroups(self): if Util.isTrueConfVal(self.persistentDisk) and self.persistentDiskStorage == 'lvm': self._addCloudAdminToExtraGroup(self.persistentDiskLvmDevfilesGroup)
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)
def _dhcpDefined(): return Util.isTrueConfVal(getattr(self, "dhcp", "False"))