Esempio n. 1
0
def vm_define_list(request, data=None):
    """
    List (:http:get:`GET </vm/define>`) VM definitions.

    .. http:get:: /vm/define

        :DC-bound?:
            * |dc-yes|
        :Permissions:
            * |VmOwner|
        :Asynchronous?:
            * |async-no|
        :arg data.full: Display full VM definitions (including disk and nic lists) (default: false)
        :type data.full: boolean
        :arg data.active: Display currently active VM definitions on compute node (default: false)
        :type data.active: boolean
        :arg data.order_by: :ref:`Available fields for sorting <order_by>`: ``hostname`` (default: ``hostname``)
        :type data.order_by: string
        :status 200: SUCCESS
        :status 403: Forbidden
    """
    vms = get_vms(request,
                  sr=('node', 'owner', 'template', 'slavevm'),
                  order_by=VmDefineView.get_order_by(data))

    return VmDefineView(request).get(vms.prefetch_related('tags'),
                                     None,
                                     many=True)
Esempio n. 2
0
def vm_define_user(request, hostname_or_uuid, data=None):
    """
    vm_define alternative used only for updating hostname and alias.
    Used by non-admin VM owners from GUI.
    """
    vm = get_vm(request, hostname_or_uuid, sr=('owner', 'node', 'template', 'slavevm'), check_node_status=None,
                exists_ok=True, noexists_fail=True)
    allowed = {'hostname', 'alias', 'installed'}

    for i in data.keys():  # A copy of keys, because dict can change during iteration
        if i not in allowed:
            del data[i]

    return VmDefineView(request).put(vm, data)
Esempio n. 3
0
    def post(self):
        request, vm = self.request, self.vm
        ser = VmCreateSerializer(data=self.data)

        if not ser.is_valid():
            return FailureTaskResponse(request, ser.errors, vm=vm)

        if not vm.is_kvm():
            if not (vm.dc.settings.VMS_VM_SSH_KEYS_DEFAULT or vm.owner.usersshkey_set.exists()):
                raise PreconditionRequired('VM owner has no SSH keys available')

        apiview = self.apiview
        # noinspection PyTypeChecker
        cmd = 'vmadm create >&2; e=$? %s; vmadm get %s 2>/dev/null; vmadm start %s >&2; exit $e' % (
            self.fix_create(vm), vm.uuid, vm.uuid)

        recreate = apiview['recreate'] = ser.data['recreate']
        # noinspection PyAugmentAssignment
        if recreate:
            # recreate should be available to every vm owner
            if not (request.user and request.user.is_authenticated()):
                raise PermissionDenied

            if vm.locked:
                raise VmIsLocked

            if vm.status != vm.STOPPED:
                raise VmIsNotOperational('VM is not stopped')

            if not ser.data['force']:
                raise ExpectationFailed('Are you sure?')

            msg = LOG_VM_RECREATE
            # noinspection PyAugmentAssignment
            cmd = 'vmadm delete ' + vm.uuid + ' >&2 && sleep 1; ' + cmd

        elif vm.status == vm.NOTCREATED:
            # only admin
            if not (request.user and request.user.is_admin(request)):
                raise PermissionDenied

            if not vm.node:  # we need to find a node for this vm now
                logger.debug('VM %s has no compute node defined. Choosing node automatically', vm)
                VmDefineView(request).choose_node(vm)
                logger.info('New compute node %s for VM %s was chosen automatically.', vm.node, vm)

            msg = LOG_VM_CREATE

        else:
            raise VmIsNotOperational('VM is already created')

        # Check boot flag (KVM) or disk image (OS) (bug #chili-418)
        if not vm.is_bootable():
            raise PreconditionRequired('VM has no bootable disk')

        if vm.tasks:
            raise VmHasPendingTasks

        old_status = vm.status
        deploy = apiview['deploy'] = vm.is_deploy_needed()
        resize = apiview['resize'] = vm.is_resize_needed()

        if not vm.is_blank():
            vm.set_root_pw()

        # Set new status also for blank VM (where deployment is not needed)
        # This status will be changed in vm_status_event_cb (if everything goes well).
        vm.status = vm.CREATING
        vm.save()  # save status / node / vnc_port / root_pw

        stdin = vm.fix_json(deploy=deploy, resize=resize, recreate=recreate).dump()
        meta = {
            'output': {'returncode': 'returncode', 'stderr': 'message', 'stdout': 'json'},
            'replace_stderr': ((vm.uuid, vm.hostname),),
            'msg': msg,
            'vm_uuid': vm.uuid,
            'apiview': apiview
        }
        callback = ('api.vm.base.tasks.vm_create_cb', {'vm_uuid': vm.uuid})
        err = True

        try:
            # Possible node_image import task which will block this task on node worker
            block_key = self.node_image_import(vm.node, vm.json_get_disks())
            logger.debug('Creating new VM %s on node %s with json: """%s"""', vm, vm.node, stdin)
            tid, err = execute(request, vm.owner.id, cmd, stdin=stdin, meta=meta, expires=VM_VM_EXPIRES, lock=self.lock,
                               callback=callback, queue=vm.node.slow_queue, block_key=block_key)

            if err:
                return FailureTaskResponse(request, err, vm=vm)
            else:
                # Inform user about creating
                vm_status_changed(tid, vm, vm.CREATING, save_state=False)
                return TaskResponse(request, tid, msg=msg, vm=vm, api_view=apiview, data=self.data)
        finally:
            if err:  # Revert old status
                vm.status = old_status
                vm.save_status()
Esempio n. 4
0
def vm_define(request, hostname_or_uuid, data=None):
    """
    Show (:http:get:`GET </vm/(hostname_or_uuid)/define>`),
    create (:http:post:`POST </vm/(hostname_or_uuid)/define>`),
    change (:http:put:`PUT </vm/(hostname_or_uuid)/define>`) or
    delete (:http:delete:`DELETE </vm/(hostname_or_uuid)/define>`)
    a VM definition.

    .. http:get:: /vm/(hostname_or_uuid)/define

        :DC-bound?:
            * |dc-yes|
        :Permissions:
            * |VmOwner|
        :Asynchronous?:
            * |async-no|
        :arg hostname_or_uuid: **required** - Server hostname or uuid
        :type hostname_or_uuid: string
        :arg data.full: Display full VM definition (including disk and nic lists) (default: false)
        :type data.full: boolean
        :arg data.active: Display currently active VM definition on compute node (default: false)
        :type data.active: boolean
        :arg data.diff: Display differences between active VM definition on compute node and current configuration \
(default: false)
        :type data.diff: boolean
        :status 200: SUCCESS
        :status 403: Forbidden
        :status 404: VM not found

    .. http:post:: /vm/(hostname_or_uuid)/define

        :DC-bound?:
            * |dc-yes|
        :Permissions:
            * |Admin|
        :Asynchronous?:
            * |async-no|
        :arg hostname_or_uuid: **required** - Server hostname
        :type hostname_or_uuid: string
        :arg data.alias: Short server name (default: ``hostname``)
        :type data.alias: string
        :arg data.template: VM template name (default: null)
        :type data.template: string
        :arg data.ostype: Operating system type (1 - Linux VM, 2 - SunOS VM, 3 - BSD VM, 4 - Windows VM, \
5 - SunOS Zone, 6 - Linux Zone) (default: 1)
        :type data.ostype: integer
        :arg data.vcpus: **required** - Number of virtual CPUs inside VM (1 - 64)
        :type data.vcpus: integer
        :arg data.ram: **required** - Size of RAM inside VM (32 - 524288 MB)
        :type data.ram: integer
        :arg data.note: Text note visible to every user with access to this VM (default: "")
        :type data.note: string
        :arg data.owner: User that owns the VM (default: logged in user)
        :type data.owner: string
        :arg data.node: Name of the host system \
(default: null => will be chosen automatically just before the VM is created)
        :type data.node: string
        :arg data.tags: Custom VM tags (default: [])
        :type data.tags: array
        :arg data.monitored: Enable VM synchronization with monitoring system (default: true)
        :type data.monitored: boolean
        :arg data.monitored_internal: Enable VM synchronization with internal monitoring system \
(requires |SuperAdmin| permission) (default: true)
        :type data.monitored: boolean
        :arg data.installed: Mark the server as installed (default: false)
        :type data.installed: boolean
        :arg data.snapshot_limit_manual: Maximum number of manual snapshots for this VM (default: null [unlimited])
        :type data.snapshot_limit_manual: integer
        :arg data.snapshot_size_limit: Maximum size of all snapshots for this VM (default: null [unlimited])
        :type data.snapshot_size_limit: integer
        :arg data.zpool: The zpool used for the VM zone (default: zones)
        :type data.zpool: string
        :arg data.cpu_shares: Number of VM's CPU shares relative to other VMs (requires |SuperAdmin| permission) \
(default: 100)
        :type data.cpu_shares: integer
        :arg data.zfs_io_priority: IO throttle priority relative to other VMs (requires |SuperAdmin| permission) \
(default: 100)
        :type data.zfs_io_priority: integer
        :arg data.cpu_type: **KVM only**; Type of the virtual CPU exposed to the VM. One of qemu64, host \
(default: qemu64; except for Windows ``ostype`` where the default is host)
        :type data.cpu_type: string
        :arg data.vga: **KVM only**; VGA emulation driver. One of std, cirrus, vmware (default: std)
        :type data.vga: string
        :arg data.routes: Key-value object that maps destinations to gateways. \
Items will be set as static routes in the OS (SunOS Zone only, default: {})
        :type data.routes: object
        :arg data.monitoring_hostgroups: Custom VM monitoring hostgroups (default: [])
        :type data.monitoring_hostgroups: array
        :arg data.monitoring_templates: Custom VM monitoring templates (default: [])
        :type data.monitoring_templates: array
        :arg data.mdata: Customer metadata accessible from within the VM (key=value string pairs) (default: {})
        :type data.mdata: object
        :status 201: SUCCESS
        :status 400: FAILURE
        :status 403: Forbidden
        :status 406: VM already exists

    .. http:put:: /vm/(hostname_or_uuid)/define

        :DC-bound?:
            * |dc-yes|
        :Permissions:
            * |Admin|
        :Asynchronous?:
            * |async-no|
        :arg hostname_or_uuid: **required** - Server hostname or uuid
        :type hostname_or_uuid: string
        :arg data.alias: Short server name
        :type data.alias: string
        :arg data.template: VM template name
        :type data.template: string
        :arg data.vcpus: Number of virtual CPUs inside VM (1 - 64)
        :type data.vcpus: integer
        :arg data.ram: Size of RAM inside VM (32 - 524288 MB)
        :type data.ram: integer
        :arg data.note: Text note visible to every user with access to this VM
        :type data.note: string
        :arg data.owner: User that owns the VM
        :type data.owner: string
        :arg data.node: Name of the host system
        :type data.node: string
        :arg data.tags: Custom VM tags
        :type data.tags: array
        :arg data.monitored: Enable VM synchronization with monitoring system
        :type data.monitored: boolean
        :arg data.monitored_internal: Enable VM synchronization with internal monitoring system \
(requires |SuperAdmin| permission)
        :type data.monitored: boolean
        :arg data.installed: Mark the server as installed
        :type data.installed: boolean
        :arg data.snapshot_limit_manual: Maximum number of manual snapshots for this VM
        :type data.snapshot_limit_manual: integer
        :arg data.snapshot_size_limit: Maximum size of all snapshots for this VM
        :type data.snapshot_size_limit: integer
        :arg data.zpool: The zpool used for the VM zone
        :type data.zpool: string
        :arg data.cpu_shares: Number of VM's CPU shares relative to other VMs (requires |SuperAdmin| permission)
        :type data.cpu_shares: integer
        :arg data.zfs_io_priority: IO throttle priority relative to other VMs (requires |SuperAdmin| permission)
        :type data.zfs_io_priority: integer
        :arg data.cpu_type: **KVM only**; Type of the virtual CPU exposed to the VM. One of qemu64, host
        :type data.cpu_type: string
        :arg data.vga: **KVM only**; VGA emulation driver. One of std, cirrus, vmware
        :type data.vga: string
        :arg data.routes: Key-value object that maps destinations to gateways. \
Items will be set as static routes in the OS (SunOS Zone only)
        :type data.routes: object
        :arg data.monitoring_hostgroups: Custom VM monitoring hostgroups
        :type data.monitoring_hostgroups: array
        :arg data.monitoring_templates: Custom VM monitoring templates
        :type data.monitoring_templates: array
        :arg data.mdata: Customer metadata accessible from within the VM (key=value string pairs)
        :type data.mdata: object
        :status 200: SUCCESS
        :status 400: FAILURE
        :status 403: Forbidden
        :status 404: VM not found
        :status 423: VM is not operational / VM is locked or has slave VMs

    .. http:delete:: /vm/(hostname_or_uuid)/define

        :DC-bound?:
            * |dc-yes|
        :Permissions:
            * |Admin|
        :Asynchronous?:
            * |async-no|
        :arg hostname_or_uuid: **required** - Server hostname or uuid
        :type hostname_or_uuid: string
        :status 200: SUCCESS
        :status 400: FAILURE
        :status 403: Forbidden
        :status 404: VM not found
        :status 423: VM is not operational / VM is not notcreated / VM is locked or has slave VMs
    """
    vm = get_vm(request,
                hostname_or_uuid,
                sr=('owner', 'node', 'template', 'slavevm'),
                check_node_status=None,
                noexists_fail=False,
                exists_ok=False)

    return VmDefineView(request).response(vm,
                                          data,
                                          hostname_or_uuid=hostname_or_uuid)
Esempio n. 5
0
    def _set_vm_tags(self, vm, tags, task_id=None):
        from api.vm.define.vm_define import VmDefineView

        request = set_request_method(self.request, 'PUT')
        VmDefineView(request).put(vm, {'tags': list(tags)}, task_id=task_id)
Esempio n. 6
0
def vm_define(request, hostname_or_uuid, data=None):
    """
    Show (:http:get:`GET </vm/(hostname_or_uuid)/define>`),
    create (:http:post:`POST </vm/(hostname_or_uuid)/define>`),
    change (:http:put:`PUT </vm/(hostname_or_uuid)/define>`) or
    delete (:http:delete:`DELETE </vm/(hostname_or_uuid)/define>`)
    a VM definition.

    .. http:get:: /vm/(hostname_or_uuid)/define

        :DC-bound?:
            * |dc-yes|
        :Permissions:
            * |VmOwner|
        :Asynchronous?:
            * |async-no|
        :arg hostname_or_uuid: **required** - Server hostname or uuid
        :type hostname_or_uuid: string
        :arg data.full: Display full VM definition (including disk and nic lists) (default: false)
        :type data.full: boolean
        :arg data.active: Display currently active VM definition on compute node (default: false)
        :type data.active: boolean
        :arg data.diff: Display differences between active VM definition on compute node and current configuration \
(default: false)
        :type data.diff: boolean
        :status 200: SUCCESS
        :status 403: Forbidden
        :status 404: VM not found

    .. http:post:: /vm/(hostname_or_uuid)/define

        :DC-bound?:
            * |dc-yes|
        :Permissions:
            * |Admin|
        :Asynchronous?:
            * |async-no|
        :arg hostname_or_uuid: **required** - Server hostname
        :type hostname_or_uuid: string
        :arg data.alias: Short server name (default: ``hostname``)
        :type data.alias: string
        :arg data.template: VM template name (default: null)
        :type data.template: string
        :arg data.ostype: Operating system type (1 - Linux VM, 2 - SunOS VM, 3 - BSD VM, 4 - Windows VM, \
5 - SunOS Zone, 6 - Linux Zone) (default: 1)
        :type data.ostype: integer
        :arg data.vcpus: **required** - Number of virtual CPUs inside VM (1 - 1024); \
This number is used to calculate an internal compute node CPU limit for the VM (cpu_cap). \
When the :http:put:`VMS_VM_CPU_CAP_REQUIRED </dc/(dc)/settings>` DC setting is disabled, \
then the vcpus value can be 0, which will remove the compute node CPU limit entirely (SunOS and LX Zone only)
        :type data.vcpus: integer
        :arg data.ram: **required** - Size of RAM inside VM (1 - 1048576 MB)
        :type data.ram: integer
        :arg data.note: Text note visible to every user with access to this VM (default: "")
        :type data.note: string
        :arg data.owner: User that owns the VM (default: logged in user)
        :type data.owner: string
        :arg data.node: Name of the host system \
(default: null => will be chosen automatically just before the VM is created)
        :type data.node: string
        :arg data.tags: Custom VM tags (default: [])
        :type data.tags: array
        :arg data.monitored: Enable VM synchronization with monitoring system (default: true)
        :type data.monitored: boolean
        :arg data.monitored_internal: Enable VM synchronization with internal monitoring system \
(requires |SuperAdmin| permission) (default: true)
        :type data.monitored: boolean
        :arg data.installed: Mark the server as installed (default: false)
        :type data.installed: boolean
        :arg data.snapshot_limit_manual: Maximum number of manual snapshots for this VM (default: null [unlimited])
        :type data.snapshot_limit_manual: integer
        :arg data.snapshot_size_percent_limit: Maximum size of all snapshots for this VM relative to size of all \
defined VM disks. Ignored if ``snapshot_size_limit`` is defined (default: null [unlimited])
        :type data.snapshot_size_percent_limit: integer
        :arg data.snapshot_size_limit: Maximum absolute size of all snapshots for this VM in megabytes \
(default: null [unlimited])
        :type data.snapshot_size_limit: integer
        :arg data.zpool: The zpool used for the VM (default: zones)
        :type data.zpool: string
        :arg data.cpu_shares: Number of VM's CPU shares relative to other VMs (requires |SuperAdmin| permission) \
(default: 100)
        :type data.cpu_shares: integer
        :arg data.zfs_io_priority: IO throttle priority relative to other VMs (requires |SuperAdmin| permission) \
(default: 100)
        :type data.zfs_io_priority: integer
        :arg data.cpu_type: **KVM only**; Type of the virtual CPU exposed to the VM. One of qemu64, host \
(default: qemu64; except for Windows ``ostype`` where the default is host)
        :type data.cpu_type: string
        :arg data.vga: **KVM only**; VGA emulation driver. One of std, cirrus, vmware (default: std)
        :type data.vga: string
        :arg data.bootrom: **BHYVE only**; Default VM boot firmware. One of bios, uefi (default: bios). \
Only uefi mode supports VNC.
        :type data.bootrom: string
        :arg data.dns_domain: Search domain set in /etc/hosts (SunOS Zone only, default: domain part of ``hostname``)
        :type data.dns_domain: string
        :arg data.routes: Key-value object that maps destinations to gateways. \
Items will be set as static routes in the OS (SunOS Zone only, default: {})
        :type data.routes: object
        :arg data.monitoring_hostgroups: Custom VM monitoring hostgroups (default: [])
        :type data.monitoring_hostgroups: array
        :arg data.monitoring_templates: Custom VM monitoring templates (default: [])
        :type data.monitoring_templates: array
        :arg data.mdata: Customer metadata accessible from within the VM (key=value string pairs) (default: {})
        :type data.mdata: object
        :status 201: SUCCESS
        :status 400: FAILURE
        :status 403: Forbidden
        :status 406: VM already exists

    .. note:: The **cpu_cap** defines a percentage of a single compute node CPU that can be used by the VM. \
It is calculated automatically based on this formula: \
``(vcpus * VMS_VM_CPU_BURST_RATIO * 100) + VMS_VM_CPU_BURST_DEFAULT``, where \
*VMS_VM_CPU_BURST_RATIO* is by default 1.0 and \
*VMS_VM_CPU_BURST_DEFAULT* is by default 100 when ``vcpus > 1`` and 50 when ``vcpus == 1``.

    .. http:put:: /vm/(hostname_or_uuid)/define

        :DC-bound?:
            * |dc-yes|
        :Permissions:
            * |Admin|
        :Asynchronous?:
            * |async-no|
        :arg hostname_or_uuid: **required** - Server hostname or uuid
        :type hostname_or_uuid: string
        :arg data.alias: Short server name
        :type data.alias: string
        :arg data.template: VM template name
        :type data.template: string
        :arg data.vcpus: Number of virtual CPUs inside VM (1 - 1024); \
This number is used to calculate an internal compute node CPU limit for the VM (cpu_cap). \
When the :http:put:`VMS_VM_CPU_CAP_REQUIRED </dc/(dc)/settings>` DC setting is disabled, \
then the vcpus value can be 0, which will remove the compute node CPU limit entirely (SunOS and LX Zone only)
        :type data.vcpus: integer
        :arg data.ram: Size of RAM inside VM (1 - 1048576 MB)
        :type data.ram: integer
        :arg data.note: Text note visible to every user with access to this VM
        :type data.note: string
        :arg data.owner: User that owns the VM
        :type data.owner: string
        :arg data.node: Name of the host system
        :type data.node: string
        :arg data.tags: Custom VM tags
        :type data.tags: array
        :arg data.monitored: Enable VM synchronization with monitoring system
        :type data.monitored: boolean
        :arg data.monitored_internal: Enable VM synchronization with internal monitoring system \
(requires |SuperAdmin| permission)
        :type data.monitored: boolean
        :arg data.installed: Mark the server as installed
        :type data.installed: boolean
        :arg data.snapshot_limit_manual: Maximum number of manual snapshots for this VM
        :type data.snapshot_limit_manual: integer
        :type data.snapshot_limit_manual: integer
        :arg data.snapshot_size_percent_limit: Maximum size of all snapshots for this VM relative to size of all \
defined VM disks. Ignored if ``snapshot_size_limit`` is defined
        :arg data.snapshot_size_limit: Maximum absolute size of all snapshots for this VM in megabytes
        :type data.snapshot_size_limit: integer
        :arg data.zpool: The zpool used for the VM zone
        :type data.zpool: string
        :arg data.cpu_shares: Number of VM's CPU shares relative to other VMs (requires |SuperAdmin| permission)
        :type data.cpu_shares: integer
        :arg data.zfs_io_priority: IO throttle priority relative to other VMs (requires |SuperAdmin| permission)
        :type data.zfs_io_priority: integer
        :arg data.cpu_type: **KVM only**; Type of the virtual CPU exposed to the VM. One of qemu64, host
        :type data.cpu_type: string
        :arg data.vga: **KVM only**; VGA emulation driver. One of std, cirrus, vmware
        :type data.vga: string
        :arg data.bootrom: **BHYVE only**; Default VM boot firmware. One of bios, uefi (default: bios). \
Only uefi mode supports VNC.
        :type data.bootrom: string
        :arg data.dns_domain: Search domain set in /etc/hosts (SunOS Zone only)
        :type data.dns_domain: string
        :arg data.routes: Key-value object that maps destinations to gateways. \
Items will be set as static routes in the OS (SunOS Zone only)
        :type data.routes: object
        :arg data.monitoring_hostgroups: Custom VM monitoring hostgroups
        :type data.monitoring_hostgroups: array
        :arg data.monitoring_templates: Custom VM monitoring templates
        :type data.monitoring_templates: array
        :arg data.mdata: Customer metadata accessible from within the VM (key=value string pairs)
        :type data.mdata: object
        :status 200: SUCCESS
        :status 400: FAILURE
        :status 403: Forbidden
        :status 404: VM not found
        :status 409: VM has pending tasks
        :status 423: VM is not operational / VM is locked or has slave VMs

    .. http:delete:: /vm/(hostname_or_uuid)/define

        :DC-bound?:
            * |dc-yes|
        :Permissions:
            * |Admin|
        :Asynchronous?:
            * |async-no|
        :arg hostname_or_uuid: **required** - Server hostname or uuid
        :type hostname_or_uuid: string
        :status 200: SUCCESS
        :status 400: FAILURE
        :status 403: Forbidden
        :status 404: VM not found
        :status 409: VM has pending tasks
        :status 423: VM is not operational / VM is not notcreated / VM is locked or has slave VMs
    """
    vm = get_vm(request, hostname_or_uuid, sr=('owner', 'node', 'template', 'slavevm'), check_node_status=None,
                noexists_fail=False, exists_ok=False)

    return VmDefineView(request).response(vm, data, hostname_or_uuid=hostname_or_uuid)