Exemple #1
0
def destroy(caller_id, vm_ids):
    """
    This function only destroys VM. All the cleanup (removing disk, saving,
    rescuing resources, ...) is done by hook through
    \c contextualization.update_vm method (yeah, intuitive).

    Simple sequence diagram:

    @code
            CLM        CM         CTX           Node (HOOK)
             .
            Destroy -->destroy
             |          |       (LV.destroy)
             |          |------------------------->HookScript
             .          .                          |
             .          .          ctx.update_vm<--|
             .          .           |              |
             .          .           |------------->cp
             .          .           |------------->rm
             .          .          update_resources
    @endcode

    @cmview_user
    @param_post{vm_ids,list} list of virtual machines' ids

    @response{list(dict)} VM.destroy() retval
    """
    vms = []
    for vm_id in vm_ids:
        vms.append(VM.get(caller_id, vm_id))
    return VM.destroy(vms)
Exemple #2
0
    def save_and_shutdown(farm, name, description):
        """
        """
        from cm.models.vm import VM

        if farm.state == farm_states["failed"]:
            raise CMException("farm_wrong_state")

        head_vm = farm.head
        try:
            VM.save_and_shutdown(head_vm.user_id, head_vm, name, description)
        except Exception:
            CMException("farm_save")

        node_vms = []
        if farm.state == farm_states["init_head"]:
            for vm in farm.vms.all():
                if vm.is_head():
                    continue
                vm.release_resources()
                vm.state = vm_states["closed"]
        else:
            for vm in farm.vms.all():
                if not vm.is_head():
                    node_vms.append(vm)
            VM.destroy(node_vms)

        try:
            farm.state = farm_states["closed"]
            farm.save()
        except:
            CMException("farm_save")
Exemple #3
0
def destroy(caller_id, vm_ids):
    """
    This function only destroys VM. All the cleanup (removing disk, saving,
    rescuing resources, ...) is done by hook through
    \c contextualization.update_vm method (yeah, intuitive).

    Simple sequence diagram:

    @code
            CLM        CM         CTX           Node (HOOK)
             .
            Destroy -->destroy
             |          |       (LV.destroy)
             |          |------------------------->HookScript
             .          .                          |
             .          .          ctx.update_vm<--|
             .          .           |              |
             .          .           |------------->cp
             .          .           |------------->rm
             .          .          update_resources
    @endcode

    @cmview_user
    @param_post{vm_ids,list} list of virtual machines' ids

    @response{list(dict)} VM.destroy() retval
    """
    vms = []
    for vm_id in vm_ids:
        vms.append(VM.get(caller_id, vm_id))
    return VM.destroy(vms)
Exemple #4
0
    def save_and_shutdown(farm, name, description):
        """
        """
        from cm.models.vm import VM

        if farm.state == farm_states['failed']:
            raise CMException('farm_wrong_state')

        head_vm = farm.head
        try:
            VM.save_and_shutdown(head_vm.user_id, head_vm, name, description)
        except Exception:
            CMException('farm_save')

        node_vms = []
        if farm.state == farm_states['init_head']:
            for vm in farm.vms.all():
                if vm.is_head():
                    continue
                vm.release_resources()
                vm.state = vm_states['closed']
        else:
            for vm in farm.vms.all():
                if not vm.is_head():
                    node_vms.append(vm)
            VM.destroy(node_vms)

        try:
            farm.state = farm_states['closed']
            farm.save()
        except:
            CMException('farm_save')
Exemple #5
0
    def destroy(farms):
        """
        Destroyes farms' VMs (Head and Worker Nodes of each farm) without saving them.

        @parameter{farms,list} list of farms to destroy

        @response{list(dict)} list of statuses returned by destroyed VMs

        @raises{farm_wrong_state,CMException}
        @raises{farm_destroy,CMException}
        """
        from cm.models.vm import VM

        vm_resp = []
        for farm in farms:
            # those are states in which farm can not be destroyed
            if farm.state in (farm_states["init"], farm_states["closing"], farm_states["closed"]):
                raise CMException("farm_wrong_state")

        for farm in farms:
            # stop all threads
            if farm.state == farm_states["init_head"]:
                for vm in farm.vms.all():
                    if vm.is_head():
                        continue
                    vm.release_resources()
                    vm.state = vm_states["closed"]
                    vm.stop_time = datetime.now()
                    vm.save()
                    log.debug(vm.user.id, "vm state %s" % vm.state)
                r = VM.destroy([farm.head])
            else:
                for vm in farm.vms.all():
                    if vm.state == vm_states["init"]:
                        raise CMException("farm_wrong_state")
                log.debug(farm.user_id, "killing wn: %s" % farm.vms)
                r = VM.destroy(farm.vms.all())

            if True in [x["status"] != "ok" for x in r]:
                farm.state = farm_states["failed"]
                try:
                    farm.save()
                except Exception:
                    raise CMException("farm_destroy")
            vm_resp.append(r)

            farm.state = farm_states["closed"]

            try:
                farm.save()
            except Exception:
                raise CMException("farm_destroy")

            log.debug(farm.user_id, "session commited")
            for vm in farm.vms.all():
                log.debug(vm.user.id, "vm state %s" % vm.state)

        return vm_resp
Exemple #6
0
    def destroy(farms):
        """
        Destroyes farms' VMs (Head and Worker Nodes of each farm) without saving them.

        @parameter{farms,list} list of farms to destroy

        @response{list(dict)} list of statuses returned by destroyed VMs

        @raises{farm_wrong_state,CMException}
        @raises{farm_destroy,CMException}
        """
        from cm.models.vm import VM

        vm_resp = []
        for farm in farms:
            # those are states in which farm can not be destroyed
            if farm.state in (farm_states['init'], farm_states['closing'], farm_states['closed']):
                raise CMException('farm_wrong_state')

        for farm in farms:
            # stop all threads
            if farm.state == farm_states['init_head']:
                for vm in farm.vms.all():
                    if vm.is_head():
                        continue
                    vm.release_resources()
                    vm.state = vm_states['closed']
                    vm.stop_time = datetime.now()
                    vm.save()
                    log.debug(vm.user.id, "vm state %s" % vm.state)
                r = VM.destroy([farm.head])
            else:
                for vm in farm.vms.all():
                    if vm.state == vm_states['init']:
                        raise CMException('farm_wrong_state')
                log.debug(farm.user_id, "killing wn: %s" % farm.vms)
                r = VM.destroy(farm.vms.all())

            if True in [x['status'] != 'ok' for x in r]:
                farm.state = farm_states['failed']
                try:
                    farm.save()
                except Exception:
                    raise CMException('farm_destroy')
            vm_resp.append(r)

            farm.state = farm_states['closed']

            try:
                farm.save()
            except Exception:
                raise CMException('farm_destroy')

            log.debug(farm.user_id, "session commited")
            for vm in farm.vms.all():
                log.debug(vm.user.id, "vm state %s" % vm.state)

        return vm_resp
Exemple #7
0
def erase(caller_id, vm_id_list):
    """
    Cleans up after each of the specified VMs. Erase should be called for
    failed machines after the inspection of the failure.

    @cmview_admin_cm
    @param_post{vm_id_list,list} list of VM id's
    """

    for vm_id in vm_id_list:
        vm = VM.admin_get(vm_id)
        VM.erase(vm)
Exemple #8
0
def erase(caller_id, vm_id_list):
    """
    Cleans up after each of the specified VMs. Erase should be called for
    failed machines after the inspection of the failure.

    @cmview_admin_cm
    @param_post{vm_id_list,list} list of VM id's
    """

    for vm_id in vm_id_list:
        vm = VM.admin_get(vm_id)
        VM.erase(vm)
Exemple #9
0
def destroy(caller_id, vm_id_list):
    """
    Destroyes specified VMs. Destroyed VM can in no way be recovered.

    @cmview_admin_cm
    @param_post{vm_id_list,list} ids to destroy

    @response{src.cm.views.utils.image.destroy()}
    """

    vms = []
    for vm_id in vm_id_list:
        vms.append(VM.admin_get(vm_id))
    return VM.destroy(vms)
Exemple #10
0
def destroy(caller_id, vm_id_list):
    """
    Destroyes specified VMs. Destroyed VM can in no way be recovered.

    @cmview_admin_cm
    @param_post{vm_id_list,list} ids to destroy

    @response{src.cm.views.utils.image.destroy()}
    """

    vms = []
    for vm_id in vm_id_list:
        vms.append(VM.admin_get(vm_id))
    return VM.destroy(vms)
Exemple #11
0
def erase(caller_id, vm_id_list):
    """
    Method cleans up after each of VM, which id is in \c vm_ids. Should be
    called for failed machines.
    @cmview_admin_cm

    @parameter{vm_id_list,list} list of vm id's

    @noresponse
    """

    for vm_id in vm_id_list:
        vm = VM.admin_get(vm_id)
        VM.erase(vm)
Exemple #12
0
def destroy(caller_id, vm_id_list):
    """
    Method destroyes VMs with ids listed in \c vm_ids.
    @cmview_admin_cm

    @parameter{vm_ids,list} list of vm id's

    @response{src.cm.views.utils.image.destroy()}
    """

    vms = []
    for vm_id in vm_id_list:
        vms.append(VM.admin_get(vm_id))
    return VM.destroy(vms)
Exemple #13
0
def vm_stats(caller_id, vm_id, stat_name, time, stat_range, resolution):
    """
    Function returns requested statistics for specific VM. Stats are returned
    in format required by CC1 Web Interface's monitoring javascript.

    @cmview_admin_cm
    @param_post{vm_id}
    @param_post{stat_name,string|list(string)} type of required statistics
    @param_post{time,int} time of last row
    @param_post{stat_range,string} time interval between first and last stats
    @param_post{resolution,string} statistics resolution

    @response{list} usage of VM resources (format required by CC1 Web Interface)
    """

    vm_u = VM.admin_get(vm_id).long_dict['user_id']
    if type(stat_name) is int:
        stat_name = [stat_name]

    n = []
    for stat in stat_name:
        n.append(stat_names.keys()[stat_names.values().index(stat)])
    p = int(stat_ranges.keys()[stat_ranges.values().index(int(stat_range))])
    r = int(stat_resolutions.keys()[stat_resolutions.values().index(resolution)])

    return RrdHandler().get_vm_stats('vm-%d-%d' % (vm_id, vm_u), n, int(time) - p, time, r)
Exemple #14
0
    def hello(vm_ip, **args):
        """
        First function which must be called by VMs ctx module. It registers VM with status 'running ctx',
        also serves a special role when creating farms (tracking head, and worker nodes)

        @parameter{vm_ip,string}
        @parameter{args}
        """
        vm = VM.get_by_ip(vm_ip)
        log.debug(vm.user_id, "Hello from vm %d ip: %s" % (vm.id, vm_ip))

        vm.ctx_api_version = args.get('version', None)
        vm.state = vm_states['running ctx']

        if vm.ssh_username and vm.ssh_key:
            Command.execute('add_ssh_key', vm.user_id, vm.id, user=vm.ssh_username, ssh_key=vm.ssh_key)

        if vm.is_head():
            Command.register_head(vm)
        elif vm.is_farm():
            Command.register_node(vm)

        try:
            vm.save(update_fields=['state', 'ctx_api_version'])
        except Exception, e:
            log.error(vm.user_id, "Cannot update database for vm %d: %s" % (vm.id, e.message))
            return response('ctx_error', "Cannot update database: %s" % e.message)
Exemple #15
0
def attach(caller_id, storage_image_id, vm_id):
    # vm_id, img_id, destination='usb', check=True/False
    """
    Attaches selected storage disk to specified Virtual Machine. Such disk may be
    mounted to VM so that data generated by VM may be stored on it. VM also gains
    access to data already stored on that storage disk.

    @cmview_user

    @parameter{storage_image_id,int} id of block device (should be Storage type) - Disk Volume Image
    @parameter{vm_id,int} id of the VM which Storage Image should be attached to

    @response{None}
    """
    vm = VM.get(caller_id, vm_id)
    disk = StorageImage.get(caller_id, storage_image_id)

    # Check if disk is already attached to a vm
    if disk.vm:
        raise CMException('image_attached')

    disk.attach(vm)

    try:
        disk.save()
    except:
        raise CMException('storage_image_attach')
Exemple #16
0
def vm_stats(caller_id, vm_id, stat_name, time, stat_range, resolution):
    """
    Function returns statistics for specific \c vmid.
    @decoratedby{src.cm.utils.decorators.user_log}

    @parameter{vmid}
    @parameter{stat_name,string} type of required statistics
    @parameter{time,string} time of last row
    @parameter{range,string} period of time from time to past
    @parameter{resolution,string} statistics resolution

    @response{dict} list of the total usage of VM resources from start VM
    """

    vm_u = VM.admin_get(vm_id).long_dict['user_id']
    if type(stat_name) is int:
        stat_name = [stat_name]

    n = []
    for stat in stat_name:
        n.append(stat_names.keys()[stat_names.values().index(stat)])
    p = int(stat_ranges.keys()[stat_ranges.values().index(int(stat_range))])
    r = int(stat_resolutions.keys()[stat_resolutions.values().index(resolution)])

    return RrdHandler().get_vm_stats('vm-%d-%d' % (vm_id, vm_u), n, int(time) - p, time, r)
Exemple #17
0
    def hello(vm_ip, **args):
        """
        First function which must be called by VMs ctx module. It registers VM with status 'running ctx',
        also serves a special role when creating farms (tracking head, and worker nodes)

        @parameter{vm_ip,string}
        @parameter{args}
        """
        vm = VM.get_by_ip(vm_ip)
        log.debug(vm.user_id, "Hello from vm %d ip: %s" % (vm.id, vm_ip))

        vm.ctx_api_version = args.get('version', None)
        vm.state = vm_states['running ctx']

        if vm.ssh_username and vm.ssh_key:
            Command.execute('add_ssh_key',
                            vm.user_id,
                            vm.id,
                            user=vm.ssh_username,
                            ssh_key=vm.ssh_key)

        if vm.is_head():
            Command.register_head(vm)
        elif vm.is_farm():
            Command.register_node(vm)

        try:
            vm.save(update_fields=['state', 'ctx_api_version'])
        except Exception, e:
            log.error(
                vm.user_id,
                "Cannot update database for vm %d: %s" % (vm.id, e.message))
            return response('ctx_error',
                            "Cannot update database: %s" % e.message)
Exemple #18
0
def reset(caller_id, vm_ids):
    """
    Safely restarts selected callers VMs

    @cmview_user
    @param_post{vm_ids,list(int)} ids of the VMs to restart

    @response{src.cm.views.utils.image.restart()}
    """

    # get to check permissions on vms
    vms = []
    for vm_id in vm_ids:
        vms.append(VM.get(caller_id, vm_id))

    return VM.reset(vms)
Exemple #19
0
def create(caller_id, name, description, image_id, template_id, public_ip_id, iso_list, disk_list, vnc, groups, count=1, user_data=None,
           ssh_key=None, ssh_username=None):
    """
    Creates virtual machines.
    @cmview_user

    @parameter{name,string}
    @parameter{description,string}
    @parameter{image_id,int}
    @parameter{template_id,int}
    @parameter{ip_id,int}
    @parameter{iso_list,list(int)} ISOs' ids
    @parameter{vnc}
    @parameter{groups}
    @parameter{user_data} data accessible via ec2ctx
    @parameter{ssh_key}
    @parameter{ssh_username}

    @returns @asreturned{src.cm.views.utils.vm.create()}
    """
    user = User.get(caller_id)
    try:
        user.check_points()
    except:
        message.warn(caller_id, 'point_limit', {'used_points': user.used_points, 'point_limit': user.points})
    vms = VM.create(user, name=name, description=description, image_id=image_id,
                    template_id=template_id, public_ip_id=public_ip_id, iso_list=iso_list, disk_list=disk_list,
                    vnc=vnc, groups=groups, count=count, user_data=user_data, ssh_key=ssh_key, ssh_username=ssh_username)

    for vm in vms:
        thread = VMThread(vm, 'create')
        thread.start()

    return [vm.dict for vm in vms]
Exemple #20
0
def reset(caller_id, vm_ids):
    """
    Safely restarts selected callers VMs

    @cmview_user
    @param_post{vm_ids,list(int)} ids of the VMs to restart

    @response{src.cm.views.utils.image.restart()}
    """

    # get to check permissions on vms
    vms = []
    for vm_id in vm_ids:
        vms.append(VM.get(caller_id, vm_id))

    return VM.reset(vms)
Exemple #21
0
def instance_id(request):
    vm_ip = request.META.get('REMOTE_ADDR')

    vm = VM.get_by_ip( vm_ip )

    vm_id = 'i-' + str(vm.dict['vm_id'])
    return vm_id
Exemple #22
0
def get_command(remote_ip, **kw):
    """
    @param_post{remote_ip,string}
    @param_post{kw,dict} keyword params
    @returns{Command} next command from the que to the asking VM
    """
    vm = VM.get_by_ip(remote_ip)

    log.debug(0, "Get first command for %s" % vm.id)
    command = vm.command_set.filter(state=command_states['pending']).order_by('id')
    if len(command) == 0:
        return response('ctx_no_command')

    command = command[0]

    log.debug(0, "First command is %s" % command.id)
    command.state = command_states['executing']
    command.save()

    d = command.dict()

    r = response('ok', d)
    if int(kw.get('version', 0)) < VERSION:
        f = file(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'actions.py'), 'r')
        r['actions_file'] = f.read()
        f.close()
    return r
Exemple #23
0
def attach(caller_id, iso_image_id, vm_id):
    # vm_id, img_id, destination='usb', check=True/False
    """
    Attaches specified IsoImage to specified VM. It makes possible booting
    any operating system on created VM.

    @cmview_user
    @param_post{iso_image_id,int} id of block device (should be IsoImage type)
    @param_post{vm_id,int} id of the VM which IsoImage should be attached to

    @response{None}
    """

    vm = VM.get(caller_id, vm_id)
    disk = IsoImage.get(caller_id, iso_image_id)

    # Check if disk is already attached to a vm
    if disk.vm:
        raise CMException('image_attached')

    disk.attach(vm)

    try:
        disk.save()
    except:
        raise CMException('iso_image_attach')
Exemple #24
0
def ami_id(request):
    vm_ip = request.META.get('REMOTE_ADDR')
    vm = VM.get_by_ip( vm_ip )

    ami = 'ami-' + str(vm.dict['image_id'])

    return ami
Exemple #25
0
def create(caller_id, name, description, image_id, template_id, public_ip_id,
           iso_list, disk_list, vnc, node_id):
    """
    Creates new VM with specified attributes.

    @cmview_admin_cm
    @param_post{name,string}
    @param_post{description,string}
    @param_post{image_id,int}
    @param_post{template_id,int}
    @param_post{public_ip_id,int}
    @param_post{iso_list,list(int)}
    @param_post{disk_list,list(int)}
    @param_post{vnc}
    @param_post{node_id}
    """
    user = User.get(caller_id)
    vms = VM.create(user,
                    name=name,
                    description=description,
                    image_id=image_id,
                    template_id=template_id,
                    public_ip_id=public_ip_id,
                    iso_list=iso_list,
                    disk_list=disk_list,
                    vnc=vnc,
                    groups=[],
                    node_id=node_id)
    for vm in vms:
        thread = VMThread(vm, 'create')
        thread.start()

    return [vm.dict for vm in vms]
Exemple #26
0
def reservation_id(request):
    vm_ip = request.META.get('REMOTE_ADDR')
    vm = VM.get_by_ip( vm_ip )

    reservation_id = vm.long_dict['reservation_id']

    return 'r-' + str(reservation_id)
Exemple #27
0
def vm_stats(caller_id, vm_id, stat_name, time, stat_range, resolution):
    """
    Function returns requested statistics for specific VM. Stats are returned
    in format required by CC1 Web Interface's monitoring javascript.

    @cmview_admin_cm
    @param_post{vm_id}
    @param_post{stat_name,string|list(string)} type of required statistics
    @param_post{time,int} time of last row
    @param_post{stat_range,string} time interval between first and last stats
    @param_post{resolution,string} statistics resolution

    @response{list} usage of VM resources (format required by CC1 Web Interface)
    """

    vm_u = VM.admin_get(vm_id).long_dict['user_id']
    if type(stat_name) is int:
        stat_name = [stat_name]

    n = []
    for stat in stat_name:
        n.append(stat_names.keys()[stat_names.values().index(stat)])
    p = int(stat_ranges.keys()[stat_ranges.values().index(int(stat_range))])
    r = int(
        stat_resolutions.keys()[stat_resolutions.values().index(resolution)])

    return RrdHandler().get_vm_stats('vm-%d-%d' % (vm_id, vm_u), n,
                                     int(time) - p, time, r)
Exemple #28
0
def attach(caller_id, iso_image_id, vm_id):
    # vm_id, img_id, destination='usb', check=True/False
    """
    Attaches specified IsoImage to specified VM. It makes possible booting
    any operating system on created VM.

    @cmview_user
    @param_post{iso_image_id,int} id of block device (should be IsoImage type)
    @param_post{vm_id,int} id of the VM which IsoImage should be attached to

    @response{None}
    """

    vm = VM.get(caller_id, vm_id)
    disk = IsoImage.get(caller_id, iso_image_id)

    # Check if disk is already attached to a vm
    if disk.vm:
        raise CMException('image_attached')

    disk.attach(vm)

    try:
        disk.save()
    except:
        raise CMException('iso_image_attach')
Exemple #29
0
def user_data(request):
    vm_ip = request.META.get('REMOTE_ADDR')

    vm = VM.get_by_ip( vm_ip )
    user_data = vm.long_dict['user_data']

    return base64.b64decode( user_data )
Exemple #30
0
def restart(caller_id, vm_id_list):
    """
    @cmview_admin_cm

    @parameter{vm_id_list,list} list of vm id's
    """

    return VM.restart(vm_id_list)
Exemple #31
0
def save_and_shutdown(caller_id, vm_id, name, description):
    """
    Calls VM.save_and_shutdown() on specified VM

    @cmview_user
    @param_post{vm_id,int} id of the VM to save and shutdown.
    @param_post{name,string} name of the new SystemImage VM should be saved to
    @param_post{description,string} description of the new SystemImage VM
    should be saved to
    """
    user = User.get(caller_id)
    vm = VM.get(caller_id, vm_id)

    if user.used_storage + vm.system_image.size > user.storage:
        raise CMException('user_storage_limit')

    VM.save_and_shutdown(caller_id, vm, name, description)
Exemple #32
0
def save_and_shutdown(caller_id, vm_id, name, description):
    """
    Saves and shutdowns specified VM, without checking User quota.

    @cmview_admin_cm
    @param_post{vm_id,string} id of the VM to save
    @param_post{name,string}
    @param_post{description,string}
    """

    vm = VM.admin_get(vm_id)
    user = User.get(vm.user.id)

    if user.used_storage + vm.system_image.size > user.storage:
        raise CMException('user_storage_limit')

    VM.save_and_shutdown(user.id, vm, name, description)
Exemple #33
0
def save_and_shutdown(caller_id, vm_id, name, description):
    """
    Calls VM.save_and_shutdown() on specified VM

    @cmview_user
    @param_post{vm_id,int} id of the VM to save and shutdown.
    @param_post{name,string} name of the new SystemImage VM should be saved to
    @param_post{description,string} description of the new SystemImage VM
    should be saved to
    """
    user = User.get(caller_id)
    vm = VM.get(caller_id, vm_id)

    if user.used_storage + vm.system_image.size > user.storage:
        raise CMException('user_storage_limit')

    VM.save_and_shutdown(caller_id, vm, name, description)
Exemple #34
0
def save_and_shutdown(caller_id, vm_id, name, description):
    """
    Saves and shutdowns specified VM, without checking User quota.

    @cmview_admin_cm
    @param_post{vm_id,string} id of the VM to save
    @param_post{name,string}
    @param_post{description,string}
    """

    vm = VM.admin_get(vm_id)
    user = User.get(vm.user.id)

    if user.used_storage + vm.system_image.size > user.storage:
        raise CMException('user_storage_limit')

    VM.save_and_shutdown(user.id, vm, name, description)
Exemple #35
0
def save_and_shutdown(caller_id, vm_id, name, description):
    """
    Calls src.cm.views.utils.image.save_and_shutdown() for the VM selected.

    @cmview_user

    @parameter{vm_id,int} id of the VM to save and shutdown.
    @parameter{name,string}
    @parameter{description,string}
    """
    user = User.get(caller_id)
    vm = VM.get(caller_id, vm_id)

    if user.used_storage + vm.system_image.size > user.storage:
        raise CMException('user_storage_limit')

    VM.save_and_shutdown(caller_id, vm, name, description)
Exemple #36
0
def save_and_shutdown(caller_id, vm_id, name, description):
    """
    Method calls save_and_shutdown for each VM with id is in @prm{vm_id} (for
    administrator only).
    @cmview_admin_cm

    @parameter{vm_id,string}
    @parameter{name,string}
    @parameter{description,string}
    """

    vm = VM.admin_get(vm_id)
    user = User.get(vm.user.id)

    if user.used_storage + vm.system_image.size > user.storage:
        raise CMException('user_storage_limit')

    VM.save_and_shutdown(user.id, vm, name, description)
Exemple #37
0
def erase(caller_id, farm_ids):
    """
    Cleanes up after failed Farm. Only admin may erase Farm so that he
    previously may perform some analytics.

    @cmview_admin_cm
    @param_post{farm_ids,list(int)} ids of the Farms to erase
    """
    for fid in farm_ids:
        farm = Farm.admin_get(fid)
        for vm in farm.vms.all():
            VM.erase(vm)

            farm.state = farm_states['closed']
            try:
                farm.save()
            except Exception:
                log.exception('Cannot commit changes.')
Exemple #38
0
def erase(caller_id, farm_ids):
    """
    Cleanes up after failed Farm. Only admin may erase Farm so that he
    previously may perform some analytics.

    @cmview_admin_cm
    @param_post{farm_ids,list(int)} ids of the Farms to erase
    """
    for fid in farm_ids:
        farm = Farm.admin_get(fid)
        for vm in farm.vms.all():
            VM.erase(vm)

            farm.state = farm_states['closed']
            try:
                farm.save()
            except Exception:
                log.exception('Cannot commit changes.')
Exemple #39
0
def erase(caller_id, farm_ids):
    """
    Method erases (removes from database) details
    about VMs that haven't ran properly.
    @decoratedby{src.cm.utils.decorators.admin_cm_log}

    @parameter{farm_ids,list(int)} ids of the farms to erase
    """
    for fid in farm_ids:
        farm = Farm.admin_get(fid)
        for vm in farm.vms.all():
            VM.erase(vm)

            farm.state = farm_states['closed']
            try:
                farm.save()
            except Exception:
                log.exception('Cannot commit changes.')
Exemple #40
0
def get_by_id(caller_id, vm_id):
    """
    @cmview_admin_cm
    @param_post{vm_id} id of the requested VM

    @response{dict} VM with id @prm{id}
    """
    vm = VM.admin_get(vm_id)
    vm_mod = vm.long_dict
    return vm_mod
Exemple #41
0
def restart(caller_id, vm_id_list):
    """
    Sends signal to reboot specified VMs. VM is not saved to SystemImage
    during reboot.

    @cmview_admin_cm
    @param_post{vm_id_list,(list(int))} ids of the VMs to restart
    """

    return VM.restart(vm_id_list)
Exemple #42
0
def ami_launch_index(request):
    vm_ip = request.META.get('REMOTE_ADDR')
    vm = VM.get_by_ip( vm_ip )

    instance_id = vm.dict['vm_id']
    reservation_id = vm.long_dict['reservation_id']

    launch_index = reservation_id - instance_id + 1;

    return launch_index
Exemple #43
0
def restart(caller_id, vm_id_list):
    """
    Sends signal to reboot specified VMs. VM is not saved to SystemImage
    during reboot.

    @cmview_admin_cm
    @param_post{vm_id_list,(list(int))} ids of the VMs to restart
    """

    return VM.restart(vm_id_list)
Exemple #44
0
def get_by_id(caller_id, vm_id):
    """
    @cmview_admin_cm
    @param_post{vm_id} id of the requested VM

    @response{dict} VM with id @prm{id}
    """
    vm = VM.admin_get(vm_id)
    vm_mod = vm.long_dict
    return vm_mod
Exemple #45
0
def create(caller_id, name, description, image_id, template_id, public_ip_id, iso_list, disk_list, vnc, node_id):
    user = User.get(caller_id)
    vms = VM.create(user, name=name, description=description, image_id=image_id,
                    template_id=template_id, public_ip_id=public_ip_id, iso_list=iso_list, disk_list=disk_list,
                    vnc=vnc, groups=[], node_id=node_id)
    for vm in vms:
        thread = VMThread(vm, 'create')
        thread.start()

    return [vm.dict for vm in vms]
Exemple #46
0
def get_by_id(caller_id, vm_id):
    """
    Returns requested caller's VM.

    @cmview_user
    @param_post{vm_id,int} id of the requested VM

    @response{dict} VM.dict property of the requested VM
    """
    vm = VM.get(caller_id, vm_id)
    vm_mod = vm.long_dict
    return vm_mod
Exemple #47
0
def public_ipv4(request):
    vm_ip = request.META.get('REMOTE_ADDR')
    vm = VM.get_by_ip( vm_ip )

    leases = vm.dict['leases']
    ip =  leases
    for ip in leases:
        if ip.get('public_ip'):
            ip = ip.get('public_ip')
        else:
            ip = ""

    return ip
Exemple #48
0
def detach_vnc(caller_id, vm_id):
    """
    Detaches VNC redirection from VM.

    @cmview_user
    @param_post{vm_id,int} id of the VM to have detached VM redirection
    """
    vm = VM.get(caller_id, vm_id)
    vm.detach_vnc()

    try:
        vm.save()
    except:
        raise CMException('vnc_detach')
Exemple #49
0
def attach_vnc(caller_id, vm_id):
    """
    Attaches VNC redirection to VM.

    @cmview_admin_cm
    @param_post{vm_id,int} id of the VM to have attached VM redirection
    """
    vm = VM.admin_get(vm_id)
    vm.attach_vnc()

    try:
        vm.save()
    except:
        raise CMException('vnc_attach')
Exemple #50
0
def edit(caller_id, vm_id, name, description):
    """
    Updates VM's attributes.

    @cmview_user
    @param_post{vm_id,int} id of the VM to edit
    @param_post{name,string}
    @param_post{description,string}

    @response{src.cm.views.utils.image.edit()}
    """
    vm = VM.get(caller_id, vm_id)

    vm.name = name
    vm.description = description
    vm.save(update_fields=['name', 'description'])
Exemple #51
0
def detach(caller_id, storage_image_id, vm_id):
    """
    Detaches specified StorageImage from specified VM.

    @cmview_user
    @param_post{vm_id,int} id of the VM StorageImage should be detached from
    @param_post{storage_image_id,int} id of the StorageImage to detach
    """
    vm = VM.get(caller_id, vm_id)
    disk = StorageImage.get(caller_id, storage_image_id)

    disk.detach(vm)

    try:
        disk.save()
    except:
        raise CMException('storage_image_attach')
Exemple #52
0
def edit(caller_id, vm_id, name, description):
    """
    Updates VM attributes.

    @cmview_admin_cm
    @param_post{vm_id}
    @param_post{name} (optional) new VM name
    @param_post{description} (optional) new VM description

    @response{src.cm.views.utils.vm.edit()}
    """

    vm = VM.admin_get(vm_id)

    vm.name = name
    vm.description = description
    vm.save()
Exemple #53
0
def hello(remote_ip, **kw):
    """
    REST stub for hello function

    @param_post{remote_ip,string}
    @param_post{kw}
    @returns HTTP response
    """
    vm = VM.get_by_ip(remote_ip)
    log.info(vm.user_id, "vm  called hello")
    Command.hello(remote_ip)

    r = response('ok')
    if int(kw.get('version', 0)) < VERSION:
        f = file(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'actions.py'), 'r')
        r['actions_file'] = f.read()
        f.close()
    return r
Exemple #54
0
def public_keys(request, number=None, key_type=None):
    vm_ip = request.META.get('REMOTE_ADDR')

    vm = VM.get_by_ip( vm_ip )

    if number == "0" and vm.long_dict.get('ssh_key'):
        if key_type == "openssh-key": # HARDCODED VALUE, only one key can be assigned
            return vm.long_dict.get('ssh_key')
        else:
            if key_type:
                pass # todo error
            else:
                return "openssh-key"
    else:
        if number or key_type:
            pass # todo error

    if vm.long_dict.get('ssh_key'):
        return '0=public-key'