Ejemplo n.º 1
0
    def on_post(self, req, resp, tenant_id):
        body = json.loads(req.stream.read().decode())
        try:
            name = body['keypair']['name']
            key = body['keypair'].get('public_key', generate_random_key())
        except (KeyError, TypeError):
            return error_handling.bad_request(
                resp, 'Not all fields exist to create keypair.')

        validate_result = validate_keypair_name(resp, name)
        if not validate_result:
            return

        client = req.env['sl_client']
        mgr = SoftLayer.SshKeyManager(client)

        # Make sure the key with that label doesn't already exist
        existing_keys = mgr.list_keys(label=name)
        if existing_keys:
            return error_handling.duplicate(resp, 'Duplicate key by that name')

        try:
            keypair = mgr.add_key(key, name)
            resp.body = {'keypair': format_keypair(keypair)}
        except SoftLayer.SoftLayerAPIError as e:
            if 'Unable to generate a fingerprint' in e.faultString:
                return error_handling.bad_request(resp, e.faultString)
            if 'SSH key already exists' in e.faultString:
                return error_handling.duplicate(resp, e.faultString)
            raise
Ejemplo n.º 2
0
    def on_post(self, req, resp, tenant_id):
        body = json.loads(req.stream.read().decode())
        try:
            name = body['keypair']['name']
            key = body['keypair'].get('public_key', generate_random_key())
        except (KeyError, TypeError):
            return error_handling.bad_request(
                resp, 'Not all fields exist to create keypair.')

        validate_result = validate_keypair_name(resp, name)
        if not validate_result:
            return

        client = req.sl_client
        mgr = SoftLayer.SshKeyManager(client)

        # Make sure the key with that label doesn't already exist
        existing_keys = mgr.list_keys(label=name)
        if existing_keys:
            return error_handling.duplicate(resp, 'Duplicate key by that name')

        try:
            keypair = mgr.add_key(key, name)
            resp.body = {'keypair': format_keypair(keypair)}
        except SoftLayer.SoftLayerAPIError as e:
            if 'Unable to generate a fingerprint' in e.faultString:
                return error_handling.bad_request(resp, e.faultString)
            if 'SSH key already exists' in e.faultString:
                return error_handling.duplicate(resp, e.faultString)
            raise
Ejemplo n.º 3
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'))
            if flavor_id not in flavors.FLAVORS:
                return error_handling.bad_request(
                    resp, message="Invalid flavor id in the request body")
            flavor = flavors.FLAVORS[flavor_id]
            cci.upgrade(instance_id, cpus=flavor['cpus'],
                        memory=flavor['ram'] / 1024)
            resp.status = 202
            return
        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)
Ejemplo n.º 4
0
    def on_post(self, req, resp, tenant_id, instance_id):
        body = json.loads(req.stream.read().decode())

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

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

        try:
            instance_id = int(instance_id)
        except ValueError:
            return 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 SoftLayerAPIError as e:
                if 'Unable to pause instance' in e.faultString:
                    return 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: 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 SoftLayerAPIError as e:
                compute_fault(resp, e.faultString)
            return
        elif 'os-getConsoleOutput' in body:
            resp.status = 501
            return

        return bad_request(resp,
                           message="There is no such action: %s" %
                           list(body.keys()),
                           code=400)
Ejemplo n.º 5
0
    def on_post(self, req, resp, tenant_id, instance_id):
        body = json.loads(req.stream.read().decode())

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

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

        try:
            instance_id = int(instance_id)
        except ValueError:
            return 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 SoftLayerAPIError as e:
                if "Unable to pause instance" in e.faultString:
                    return 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: 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 SoftLayerAPIError as e:
                compute_fault(resp, e.faultString)
            return
        elif "os-getConsoleOutput" in body:
            resp.status = 501
            return

        return bad_request(resp, message="There is no such action: %s" % list(body.keys()), code=400)