Beispiel #1
0
    def on_get(self, req, resp, tenant_id):
        client = req.env['sl_client']
        cci = SoftLayer.CCIManager(client)

        params = get_list_params(req)

        sl_instances = cci.list_instances(**params)
        if not isinstance(sl_instances, list):
            sl_instances = [sl_instances]

        results = []
        for instance in sl_instances:
            results.append({
                'id':
                instance['id'],
                'links': [{
                    'href':
                    self.app.get_endpoint_url('compute',
                                              req,
                                              'v2_server',
                                              server_id=id),
                    'rel':
                    'self',
                }],
                'name':
                instance['hostname'],
            })

        resp.status = 200
        resp.body = {'servers': results}
Beispiel #2
0
    def on_get(self, req, resp, tenant_id, server_id):
        client = req.env['sl_client']
        cci = SoftLayer.CCIManager(client)

        instance = cci.get_instance(server_id, mask=get_virtual_guest_mask())

        results = get_server_details_dict(self.app, req, instance, True)

        resp.body = {'server': results}
Beispiel #3
0
    def on_post(self, req, resp, tenant_id):
        payload = {}
        client = req.env['sl_client']
        body = json.loads(req.stream.read().decode())

        payload['hostname'] = body['server']['name']
        payload['domain'] = config.CONF['default_domain'] or 'jumpgate.com'
        payload['image_id'] = body['server']['imageRef']

        # TODO(kmcdonald) - How do we set this accurately?
        payload['hourly'] = True

        networks = utils.lookup(body, 'server', 'networks')
        cci = SoftLayer.CCIManager(client)

        try:
            self._handle_flavor(payload, body)
            self._handle_sshkeys(payload, body, client)
            self._handle_user_data(payload, body)
            self._handle_datacenter(payload, body)
            if networks:
                self._handle_network(payload, client, networks)
            new_instance = cci.create_instance(**payload)
        except Exception as e:
            return error_handling.bad_request(resp, message=str(e))

        # This should be the first tag that the VS set. Adding any more tags
        # will replace this tag
        try:
            flavor_id = int(body['server'].get('flavorRef'))
            vs = client['Virtual_Guest']
            vs.setTags('{"flavor_id": ' + str(flavor_id) + '}',
                       id=new_instance['id'])
        except Exception:
            pass

        resp.set_header('x-compute-request-id', 'create')
        resp.status = 202
        resp.body = {
            'server': {
                'id':
                new_instance['id'],
                'links': [{
                    'href':
                    self.app.get_endpoint_url('compute',
                                              req,
                                              'v2_server',
                                              instance_id=new_instance['id']),
                    'rel':
                    'self'
                }],
                'adminPass':
                '',
            }
        }
Beispiel #4
0
    def on_delete(self, req, resp, tenant_id, server_id):
        client = req.env['sl_client']
        cci = SoftLayer.CCIManager(client)

        try:
            cci.cancel_instance(server_id)
        except SoftLayer.SoftLayerAPIError as e:
            if 'active transaction' in e.faultString:
                return error_handling.bad_request(
                    resp,
                    message='Can not cancel an instance when there is already'
                    ' an active transaction',
                    code=409)
            raise
        resp.status = 204
Beispiel #5
0
    def on_put(self, req, resp, tenant_id, server_id):
        client = req.env['sl_client']
        cci = SoftLayer.CCIManager(client)
        body = json.loads(req.stream.read().decode())

        if 'name' in utils.lookup(body, 'server'):
            if utils.lookup(body, 'server', 'name').strip() == '':
                return error_handling.bad_request(
                    resp, message='Server name is blank')

            cci.edit(server_id, hostname=utils.lookup(body, 'server', 'name'))

        instance = cci.get_instance(server_id, mask=get_virtual_guest_mask())

        results = get_server_details_dict(self.app, req, instance, False)
        resp.body = {'server': results}
Beispiel #6
0
    def on_get(self, req, resp, tenant_id=None):
        client = req.env['sl_client']
        cci = SoftLayer.CCIManager(client)

        params = get_list_params(req)

        sl_instances = cci.list_instances(**params)
        if not isinstance(sl_instances, list):
            sl_instances = [sl_instances]

        results = []
        for instance in sl_instances:
            results.append(
                get_server_details_dict(self.app, req, instance, False))

        resp.status = 200
        resp.body = {'servers': results}
Beispiel #7
0
    def on_get(self, req, resp, tenant_id, server_id):
        client = req.env['sl_client']
        cci = SoftLayer.CCIManager(client)

        instance = cci.get_instance(
            server_id, mask='id, primaryIpAddress, primaryBackendIpAddress')

        addresses = {}
        if instance.get('primaryIpAddress'):
            addresses['public'] = [{
                'version': 4,
                'addr': instance['primaryIpAddress'],
            }]

        if instance.get('primaryBackendIpAddress'):
            addresses['private'] = [{
                'version': 4,
                'addr': instance['primaryBackendIpAddress'],
            }]

        resp.body = {'addresses': addresses}
Beispiel #8
0
    def on_get(self, req, resp, tenant_id, server_id, network_label):
        network_label = network_label.lower()

        network_mask = None
        if network_label == 'public':
            network_mask = 'primaryIpAddress'
        elif network_label == 'private':
            network_mask = 'primaryBackendIpAddress'
        else:
            return error_handling.not_found(resp,
                                            message='Network does not exist')

        client = req.env['sl_client']
        cci = SoftLayer.CCIManager(client)
        instance = cci.get_instance(server_id, mask='id, ' + network_mask)

        resp.body = {
            network_label: [
                {'version': 4, 'addr': instance[network_mask]},
            ]
        }
Beispiel #9
0
    def on_get(self, req, resp, tenant_id, target_id):
        client = req.env['sl_client']
        cci = SoftLayer.CCIManager(client)
        start_time = datetime.datetime.now() + datetime.timedelta(hours=-1)
        usage = {
            'server_usages': [],
            'start': start_time.isoformat(),
            'stop': datetime.datetime.now().isoformat(),
            'tenant_id': target_id,
            'total_hours': 0.0,
            'total_local_gb_usage': 0.0,
            'total_memory_mb_usage': 0.0,
            'total_vcpus_usage': 0.0,
        }

        params = {
            'mask': servers.get_virtual_guest_mask(),
        }

        for instance in cci.list_instances(**params):
            server_dict = {
                'ended_at': None,
                'flavor': 'custom',
                'hours': 0.0,
                'instance_id': instance['id'],
                'local_gb': 1,
                'memory_mb': instance['maxMemory'],
                'name': instance['hostname'],
                'started_at': instance.get('provisionDate'),
                'state': instance['status']['keyName'].lower(),
                'tenant_id': target_id,
                'uptime': 3600,
                'vcpus': instance['maxCpu'],
            }
            usage['total_vcpus_usage'] += instance['maxCpu']
            usage['total_memory_mb_usage'] += instance['maxMemory']
            usage['server_usages'].append(server_dict)

        resp.body = {'tenant_usage': usage}
Beispiel #10
0
    def on_get(self, req, resp, tenant_id):
        client = req.env['sl_client']
        cci = SoftLayer.CCIManager(client)

        all_options = cci.get_create_options()

        results = []
        # Load and sort all data centers
        for option in all_options['datacenters']:
            name = utils.lookup(option, 'template', 'datacenter', 'name')

            results.append({
                'zoneState': {
                    'available': True
                },
                'hosts': None,
                'zoneName': name
            })
        results = sorted(results, key=lambda x: x['zoneName'])

        resp.body = {'availabilityZoneInfo': results}
        resp.status = 200
Beispiel #11
0
    def on_post(self, req, resp, tenant_id, instance_id):
        body = json.loads(req.stream.read().decode())

        if len(body) == 0:
            return error_handling.bad_request(resp,
                                              message="Malformed request body")

        vg_client = req.env['sl_client']['Virtual_Guest']
        cci = SoftLayer.CCIManager(req.env['sl_client'])

        try:
            instance_id = int(instance_id)
        except Exception:
            return error_handling.not_found(resp,
                                            "Invalid instance ID specified.")

        instance = cci.get_instance(instance_id)

        if 'pause' in body or 'suspend' in body:
            try:
                vg_client.pause(id=instance_id)
            except SoftLayer.SoftLayerAPIError as e:
                if 'Unable to pause instance' in e.faultString:
                    return error_handling.duplicate(resp, e.faultString)
                raise
            resp.status = 202
            return
        elif 'unpause' in body or 'resume' in body:
            vg_client.resume(id=instance_id)
            resp.status = 202
            return
        elif 'reboot' in body:
            if body['reboot'].get('type') == 'SOFT':
                vg_client.rebootSoft(id=instance_id)
            elif body['reboot'].get('type') == 'HARD':
                vg_client.rebootHard(id=instance_id)
            else:
                vg_client.rebootDefault(id=instance_id)
            resp.status = 202
            return
        elif 'os-stop' in body:
            vg_client.powerOff(id=instance_id)
            resp.status = 202
            return
        elif 'os-start' in body:
            vg_client.powerOn(id=instance_id)
            resp.status = 202
            return
        elif 'createImage' in body:
            image_name = body['createImage']['name']
            disks = []

            for disk in filter(lambda x: x['device'] == '0',
                               instance['blockDevices']):
                disks.append(disk)

            try:
                vg_client.createArchiveTransaction(
                    image_name,
                    disks,
                    "Auto-created by OpenStack compatibility layer",
                    id=instance_id,
                )
                # Workaround for not having an image guid until the image is
                # fully created. TODO(nbeitenmiller): Fix this
                cci.wait_for_transaction(instance_id, 300)
                _filter = {
                    'privateBlockDeviceTemplateGroups': {
                        'name': {
                            'operation': image_name
                        },
                        'createDate': {
                            'operation': 'orderBy',
                            'options': [{
                                'name': 'sort',
                                'value': ['DESC']
                            }],
                        }
                    }
                }

                acct = req.env['sl_client']['Account']
                matching_image = acct.getPrivateBlockDeviceTemplateGroups(
                    mask='id, globalIdentifier', filter=_filter, limit=1)
                image_guid = matching_image.get('globalIdentifier')

                url = self.app.get_endpoint_url('image',
                                                req,
                                                'v2_image',
                                                image_guid=image_guid)

                resp.status = 202
                resp.set_header('location', url)
            except SoftLayer.SoftLayerAPIError as e:
                error_handling.compute_fault(resp, e.faultString)
            return
        elif 'os-getConsoleOutput' in body:
            resp.status = 501
            return
        elif 'resize' in body:
            flavor_id = int(body['resize'].get('flavorRef'))
            for flavor in self.flavors:
                if str(flavor_id) == flavor['id']:
                    cci.upgrade(instance_id,
                                cpus=flavor['cpus'],
                                memory=flavor['ram'] / 1024)
                    resp.status = 202
                    return
            return error_handling.bad_request(resp,
                                              message="Invalid flavor "
                                              "id in the request body")
        elif 'confirmResize' in body:
            resp.status = 204
            return

        return error_handling.bad_request(
            resp,
            message="There is no such action: %s" % list(body.keys()),
            code=400)
Beispiel #12
0
 def set_up(self):
     self.client = testing.FixtureClient()
     self.cci = SoftLayer.CCIManager(self.client)