Beispiel #1
0
 def _cliGetNetworks(self):
     networks = self.client.nova.networks.list()
     networks.sort(key=lambda x: x.label.lower())
     if not networks:
         raise errors.ParameterError(
             "No networks defined, please create one")
     return networks
Beispiel #2
0
 def _launchSpecificDescriptorFields(self, descr, extraArgs=None):
     avzones = self._get_availability_zones()
     descr.addDataField(
         "availabilityZone",
         descriptions=[("Availability Zone", None),
                       (u"Zone de disponibilit\u00e9", "fr_FR")],
         help=[("launch/availabilityZones.html", None)],
         default=[avzones[0].zoneName],
         required=True,
         type=descr.EnumeratedType([
             descr.ValueWithDescription(x.zoneName, descriptions=x.zoneName)
             for x in avzones
         ]))
     targetFlavors = self._get_flavors()
     if not targetFlavors:
         raise errors.ParameterError("No instance flavors defined")
     flavors = [
         descr.ValueWithDescription(
             str(f.id),
             descriptions="%s (VCPUs: %d, RAM: %d MB)" %
             (f.name, f.vcpus, f.ram)) for f in targetFlavors
     ]
     descr.addDataField(
         'flavor',
         descriptions='Flavor',
         required=True,
         help=[('launch/flavor.html', None)],
         type=descr.EnumeratedType(flavors),
         default=flavors[0].key,
     )
     networks = self._cliGetNetworks()
     descr.addDataField(
         'network',
         descriptions='Network',
         required=True,
         help=[('launch/network.html', None)],
         type=descr.EnumeratedType(
             descr.ValueWithDescription(x.id, descriptions=x.label)
             for x in networks),
         default=[networks[0].id],
     )
     descr.addDataField("keyName",
                        descriptions=[("SSH Key Pair", None),
                                      ("Paire de clefs", "fr_FR")],
                        help=[("launch/keyPair.html", None)],
                        type=descr.EnumeratedType(
                            self._retriveSSHKeyPairs(descr)))
     fpList = self._cliGetFloatingIps()
     descr.addDataField(
         'floatingIp',
         descriptions='Floating IP',
         required=True,
         help=[('launch/floatingIp.html', None)],
         type=descr.EnumeratedType(
             descr.ValueWithDescription(x['id'], descriptions=x['label'])
             for x in fpList),
         default=fpList[0]['id'],
     )
     return descr
Beispiel #3
0
    def _retriveSSHKeyPairs(self, descr):
        keyPairs = [
            descr.ValueWithDescription(x[0], descriptions=x[1])
            for x in self._cliGetKeyPairs()
        ]
        if not keyPairs:
            raise errors.ParameterError(
                "No OpenStack SSH key pairs defined, please create one")

        return keyPairs
Beispiel #4
0
    def destroy(self, request, userId):
        if userId != request.auth[0]:
            raise errors.ParameterError("Mismatching users %s, %s" %
                                        (userId, request.auth[0]))

        store = self._getUserDataStore(request)
        key = request.unparsedPath

        key = self._sanitizeKey(key)
        store.delete(key)
        url = self.url(request, 'users', '%s/%s' % (userId, key))
        data = '<?xml version="1.0" encoding="UTF-8"?><id>%s</id>' % (url)
        return XmlStringResponse(data)
Beispiel #5
0
    def update(self, request, userId):
        "update a key"
        if userId != request.auth[0]:
            raise errors.ParameterError("Mismatching users %s, %s" %
                                        (userId, request.auth[0]))

        dataLen = request.getContentLength()
        data = request.read(dataLen)

        keyId = request.unparsedPath
        key = self._sanitizeKey(keyId)

        store = self._getUserDataStore(request)
        store.set(key, data)
        data = '<?xml version="1.0" encoding="UTF-8"?><id>%s</id>' % (self.url(
            request, 'users', '%s/%s' % (userId, key)))
        return XmlStringResponse(data)
Beispiel #6
0
    def process(self, request, userId):
        "create a new key entry in the store"
        if userId != request.auth[0]:
            raise errors.ParameterError("Mismatching users %s, %s" %
                                        (userId, request.auth[0]))
        key = request.unparsedPath

        dataLen = request.getContentLength()
        data = request.read(dataLen)
        store = self._getUserDataStore(request)

        # Sanitize key
        key = key.rstrip('/')
        keyPrefix = self._sanitizeKey(key)

        newId = store.store(data, keyPrefix=keyPrefix)
        url = self.url(request, 'users', '%s/%s' % (userId, newId))
        txt = '<?xml version="1.0" encoding="UTF-8"?><id>%s</id>' % (url)
        return XmlStringResponse(txt)
Beispiel #7
0
    def get(self, request, userId):
        if userId != request.auth[0]:
            raise errors.ParameterError("Mismatching users %s, %s" %
                                        (userId, request.auth[0]))
        keyPath = request.unparsedPath
        key = self._sanitizeKey(keyPath)
        prefix = self.url(request, 'users', '%s/' % (userId))
        store = self._getUserDataStore(request)

        xmlHeader = '<?xml version="1.0" encoding="UTF-8"?>'
        key = key.rstrip('/')
        if key != keyPath:
            # A trailing / means retrieving the contents from a collection
            if not store.isCollection(key):
                data = xmlHeader + '<list></list>'
                return XmlStringResponse(data)
                #raise Exception("XXX 2", prefix, keyPath)

        if store.isCollection(key):
            node = userData.IdsNode()
            snodes = store.enumerate(keyPrefix=key)

            if key == keyPath:
                # No trailing /
                snodes = [
                    userData.IdNode().characters("%s%s" % (prefix, x))
                    for x in snodes
                ]
                node.extend(snodes)
                return XmlResponse(node)
            # Grab contents and wrap them in some XML
            data = [store.get(x) for x in snodes]
            data = xmlHeader + '<list>%s</list>' % ''.join(data)
            return XmlStringResponse(data)
        else:
            data = store.get(key)
            if data is None:
                raise NotImplementedError
            return XmlStringResponse(data)
Beispiel #8
0
 def connect(self):
     try:
         return restclient.Client.connect(self)
     except restclient.ConnectionError, e:
         msg = "%s (%s://%s%s)" % (e, self.scheme, self.hostport, self.path)
         raise errors.ParameterError(msg)
Beispiel #9
0
 def _drvPopulateDescriptorFromTarget(self, descr, withNetwork=True):
     client = self.client
     vdcs = list(client.iterVdcs())
     dataCenters = []
     networksMap = {}
     # self._id makes the resulting reference a bit more explicit,
     # but we need to map networks based on it too
     for vdc in vdcs:
         vdcKey = self._id(vdc.href, 'vdc')
         nm = networksMap[vdcKey] = []
         for network in client.iterNetworksForVdc(vdc):
             nwKey = self._id(network.href, 'network')
             nm.append(
                 descr.ValueWithDescription(nwKey,
                                            descriptions=network.name))
         if withNetwork and not nm:
             # No networks found for this data center, so skip it
             continue
         dataCenters.append(
             descr.ValueWithDescription(vdcKey, descriptions=vdc.name))
     if not dataCenters:
         raise errors.ParameterError(
             "Unable to find a functional datacenter for user %s" %
             self.credentials['username'])
     catalogs = [
         descr.ValueWithDescription(item[1], descriptions=item[0])
         for item in sorted((x.name, self._id(x.href, 'catalog'))
                            for x in client.iterWritableCatalogs())
     ]
     if not catalogs:
         raise errors.ParameterError(
             "Unable to find writable catalogs for user %s" %
             self.credentials['username'])
     descr.addDataField(
         'catalog',
         descriptions='Catalog',
         required=True,
         help=[('launch/catalog.html', None)],
         type=descr.EnumeratedType(catalogs),
         default=catalogs[0].key,
     )
     descr.addDataField(
         'dataCenter',
         descriptions='Data Center',
         required=True,
         help=[('launch/dataCenter.html', None)],
         type=descr.EnumeratedType(dataCenters),
         default=dataCenters[0].key,
     )
     if withNetwork:
         for vdcKey, networks in networksMap.items():
             networkKey = 'network-' + vdcKey
             descr.addDataField(networkKey,
                                descriptions='Network',
                                required=True,
                                help=[('launch/network.html', None)],
                                type=descr.EnumeratedType(networks),
                                default=networks[0].key,
                                conditional=descr.Conditional(
                                    fieldName='dataCenter',
                                    operator='eq',
                                    fieldValue=vdcKey))
     return descr
Beispiel #10
0
            if expectedStatusCodes and e.status in expectedStatusCodes:
                return e
            # XXX Munge exception here
            if self.getContentTypeFromHeaders(e.headers) == self.TYPES.error:
                try:
                    error = Models.handler.parseString(e.contents)
                    message = "vCloud error: %s" % error.message
                except:
                    error = message = e.contents
                raise errors.CatalogError(status=e.status,
                                          message=message,
                                          error=error)
            raise errors.CatalogError("Unknown error: %s" % e)
        if expectedStatusCodes:
            raise errors.ParameterError(
                "vCloud error: expected codes %s, got %s" %
                (expectedStatusCodes, e.status))
        return resp

    @classmethod
    def getContentTypeFromHeaders(cls, headers):
        data = headers.get('Content-Type')
        if data is None:
            return None
        # Take out any additional params
        return data.split(';', 1)[0]

    def verify(self):
        self.path = '/api/versions'
        try:
            self.connect()
    def _deployImageFromStream(self,
                               job,
                               image,
                               stream,
                               dataCenter,
                               dataStore,
                               computeResource,
                               resourcePool,
                               vmName,
                               uuid,
                               network,
                               diskProvisioning,
                               vmFolder=None,
                               asTemplate=False,
                               updateOnBoot=None):

        logger = lambda *x: self._msg(job, *x)
        dc = self.vicfg.getDatacenter(dataCenter)
        dcName = dc.properties['name']

        cr = dc.getComputeResource(computeResource)
        ds = self.vicfg.getMOR(dataStore)
        dsInfo = self.client.getDynamicProperty(ds, 'summary')
        dsName = dsInfo.get_element_name()
        rp = self.vicfg.getMOR(resourcePool)
        network = self.vicfg.getMOR(network)
        props = self.vicfg.getProperties()
        # find a host that can access the datastore
        hosts = [
            x for x in cr.properties['host'] if ds in props[x]['datastore']
        ]
        if not hosts:
            raise RuntimeError('no host can access the requested datastore')
        host = hosts[0]

        if vmFolder is None:
            vmFolderMor = dc.properties['vmFolder']
        else:
            vmFolderMor = self.vicfg.getMOR(vmFolder)
        dcName_, vmFolderPath = self.vicfg.getVmFolderLabelPath(vmFolderMor)
        if dcName_ is None:
            # Requested a folder with no path to the top level
            raise errors.ParameterError()
        inventoryPrefix = '/%s/%s/' % (dcName_, vmFolderPath)
        vmName = self._findUniqueName(inventoryPrefix, vmName)
        # FIXME: make sure that there isn't something in the way on
        # the data store

        vmMor = self._deployOvf(job,
                                vmName,
                                uuid,
                                stream,
                                dc,
                                dataStore=ds,
                                host=host,
                                resourcePool=rp,
                                network=network,
                                diskProvisioning=diskProvisioning,
                                vmFolder=vmFolderMor,
                                asTemplate=asTemplate)

        nwobj = self.client.getMoRefProp(vmMor, 'network')
        reconfigVmParams = dict()
        if not nwobj.get_element_ManagedObjectReference():
            # add NIC
            nicSpec = self.client.createNicConfigSpec(network)
            deviceChange = [nicSpec]
            reconfigVmParams['deviceChange'] = deviceChange

        if asTemplate:
            # Reconfiguring the uuid is unreliable, we're using the
            # annotation field for now
            reconfigVmParams['annotation'] = "rba-uuid: %s" % uuid

        conaryProxies = ' '.join(
            x.partition(':')[0] for x in self.zoneAddresses)
        zoneAddresses = ' '.join(self.zoneAddresses)

        vAppConfig = self.client.getMoRefProp(vmMor, 'config.vAppConfig')
        reconfigVmParams['vAppConfig'] = self._setVappConfig(
            vAppConfig,
            conaryProxies=conaryProxies,
            zoneAddresses=zoneAddresses,
            updateOnBoot=updateOnBoot)

        if reconfigVmParams:
            self._msg(job, 'Reconfiguring VM')
            self.client.reconfigVM(vmMor, reconfigVmParams)

        if asTemplate:
            self._msg(job, 'Converting VM to template')
            self.client.markAsTemplate(vm=vmMor)
        image.setShortName(vmName)
        return vmMor