Esempio n. 1
0
 def get_instance_nw_info(self, context, instance):
     """Returns all network info related to an instance."""
     args = {
         'instance_id': instance['id'],
         'instance_uuid': instance['uuid'],
         'instance_type_id': instance['instance_type_id'],
         'host': instance['host']
     }
     try:
         return rpc.call(context, FLAGS.network_topic, {
             'method': 'get_instance_nw_info',
             'args': args
         })
     # FIXME(comstud) rpc calls raise RemoteError if the remote raises
     # an exception.  In the case here, because of a race condition,
     # it's possible the remote will raise a InstanceNotFound when
     # someone deletes the instance while this call is in progress.
     #
     # Unfortunately, we don't have access to the original exception
     # class now.. but we do have the exception class's name.  So,
     # we're checking it here and raising a new exception.
     #
     # Ultimately we need RPC to be able to serialize more things like
     # classes.
     except rpc_common.RemoteError as err:
         if err.exc_type == 'InstanceNotFound':
             raise exception.InstanceNotFound(instance_id=instance['id'])
         raise
Esempio n. 2
0
    def get_info(self, instance_name):
        """Return data about the VM instance."""
        vm_ref = self._get_vm_ref_from_the_name(instance_name)
        if vm_ref is None:
            raise exception.InstanceNotFound(instance_id=instance_name)

        lst_properties = [
            "summary.config.numCpu", "summary.config.memorySizeMB",
            "runtime.powerState"
        ]
        vm_props = self._session._call_method(vim_util,
                                              "get_object_properties", None,
                                              vm_ref, "VirtualMachine",
                                              lst_properties)
        max_mem = None
        pwr_state = None
        num_cpu = None
        for elem in vm_props:
            for prop in elem.propSet:
                if prop.name == "summary.config.numCpu":
                    num_cpu = int(prop.val)
                elif prop.name == "summary.config.memorySizeMB":
                    # In MB, but we want in KB
                    max_mem = int(prop.val) * 1024
                elif prop.name == "runtime.powerState":
                    pwr_state = VMWARE_POWER_STATES[prop.val]

        return {
            'state': pwr_state,
            'max_mem': max_mem,
            'mem': max_mem,
            'num_cpu': num_cpu,
            'cpu_time': 0
        }
Esempio n. 3
0
    def get_info(self, instance_name):
        """Get information about the VM"""
        vm = self._lookup(instance_name)
        if vm is None:
            raise exception.InstanceNotFound(instance_id=instance_name)
        vm = self._conn.Msvm_ComputerSystem(ElementName=instance_name)[0]
        vs_man_svc = self._conn.Msvm_VirtualSystemManagementService()[0]
        vmsettings = vm.associators(
            wmi_result_class='Msvm_VirtualSystemSettingData')
        settings_paths = [v.path_() for v in vmsettings]
        #See http://msdn.microsoft.com/en-us/library/cc160706%28VS.85%29.aspx
        summary_info = vs_man_svc.GetSummaryInformation([4, 100, 103, 105],
                                                        settings_paths)[1]
        info = summary_info[0]
        state = str(HYPERV_POWER_STATE[info.EnabledState])
        memusage = str(info.MemoryUsage)
        numprocs = str(info.NumberOfProcessors)
        uptime = str(info.UpTime)

        LOG.debug(
            _("Got Info for vm %(instance_name)s: state=%(state)s,"
              " mem=%(memusage)s, num_cpu=%(numprocs)s,"
              " cpu_time=%(uptime)s") % locals())

        return {
            'state': HYPERV_POWER_STATE[info.EnabledState],
            'max_mem': info.MemoryUsage,
            'mem': info.MemoryUsage,
            'num_cpu': info.NumberOfProcessors,
            'cpu_time': info.UpTime
        }
Esempio n. 4
0
    def generate_password(self, vim_session, pool, instance_name):
        """Returns a VMRC Session.

        Return string is of the form '<VM MOID>:<VMRC Ticket>'.

        """
        vms = vim_session._call_method(vim_util, 'get_objects',
                                       'VirtualMachine', ['name'])
        vm_ref = None
        for vm in vms:
            if vm.propSet[0].val == instance_name:
                vm_ref = vm.obj
        if vm_ref is None:
            raise exception.InstanceNotFound(instance_id=instance_name)
        virtual_machine_ticket = \
                        vim_session._call_method(
            vim_session._get_vim(),
            'AcquireCloneTicket',
            vim_session._get_vim().get_service_content().sessionManager)
        json_data = json.dumps({
            'vm_id': str(vm_ref.value),
            'username': virtual_machine_ticket,
            'password': virtual_machine_ticket
        })
        return base64.b64encode(json_data)
Esempio n. 5
0
    def generate_password(self, vim_session, pool, instance_name):
        """Returns VMRC Connection credentials.

        Return string is of the form '<VM PATH>:<ESX Username>@<ESX Password>'.

        """
        username, password = pool['username'], pool['password']
        vms = vim_session._call_method(vim_util, 'get_objects',
                                       'VirtualMachine',
                                       ['name', 'config.files.vmPathName'])
        vm_ds_path_name = None
        vm_ref = None
        for vm in vms:
            vm_name = None
            ds_path_name = None
            for prop in vm.propSet:
                if prop.name == 'name':
                    vm_name = prop.val
                elif prop.name == 'config.files.vmPathName':
                    ds_path_name = prop.val
            if vm_name == instance_name:
                vm_ref = vm.obj
                vm_ds_path_name = ds_path_name
                break
        if vm_ref is None:
            raise exception.InstanceNotFound(instance_id=instance_name)
        json_data = json.dumps({
            'vm_id': vm_ds_path_name,
            'username': username,
            'password': password
        })
        return base64.b64encode(json_data)
Esempio n. 6
0
    def suspend(self, instance):
        """Suspend the specified instance."""
        vm_ref = self._get_vm_ref_from_the_name(instance.name)
        if vm_ref is None:
            raise exception.InstanceNotFound(instance_id=instance.id)

        pwr_state = self._session._call_method(vim_util,
                                               "get_dynamic_property", vm_ref,
                                               "VirtualMachine",
                                               "runtime.powerState")
        # Only PoweredOn VMs can be suspended.
        if pwr_state == "poweredOn":
            LOG.debug(_("Suspending the VM %s ") % instance.name)
            suspend_task = self._session._call_method(self._session._get_vim(),
                                                      "SuspendVM_Task", vm_ref)
            self._session._wait_for_task(instance['uuid'], suspend_task)
            LOG.debug(_("Suspended the VM %s ") % instance.name)
        # Raise Exception if VM is poweredOff
        elif pwr_state == "poweredOff":
            reason = _("instance is powered off and can not be suspended.")
            raise exception.InstanceSuspendFailure(reason=reason)

        LOG.debug(
            _("VM %s was already in suspended state. So returning "
              "without doing anything") % instance.name)
Esempio n. 7
0
 def get_info(self, instance_name):
     if instance_name not in self.instances:
         raise exception.InstanceNotFound(instance_id=instance_name)
     i = self.instances[instance_name]
     return {'state': i.state,
             'max_mem': 0,
             'mem': 0,
             'num_cpu': 2,
             'cpu_time': 0}
Esempio n. 8
0
    def _route_to_child_zones(self, context, collection, item_uuid):
        if not FLAGS.enable_zone_routing:
            raise exception.InstanceNotFound(instance_id=item_uuid)

        self.item_uuid = item_uuid

        zones = db.zone_get_all(context)
        if not zones:
            raise exception.InstanceNotFound(instance_id=item_uuid)

        # Ask the children to provide an answer ...
        LOG.debug(_("Asking child zones ..."))
        result = self._call_child_zones(
            context, zones,
            wrap_engineclient_function(_issue_engineclient_command, collection,
                                       self.method_name, item_uuid))
        # Scrub the results and raise another exception
        # so the API layers can bail out gracefully ...
        raise RedirectResult(self.unmarshall_result(result))
Esempio n. 9
0
    def _set_machine_id(self, client_factory, instance, network_info):
        """
        Set the machine id of the VM for guest tools to pick up and reconfigure
        the network interfaces.
        """
        vm_ref = self._get_vm_ref_from_the_name(instance.name)
        if vm_ref is None:
            raise exception.InstanceNotFound(instance_id=instance.id)

        machine_id_str = ''
        for (network, info) in network_info:
            # TODO(vish): add support for dns2
            # TODO(sateesh): add support for injection of ipv6 configuration
            ip_v4 = ip_v6 = None
            if 'ips' in info and len(info['ips']) > 0:
                ip_v4 = info['ips'][0]
            if 'ip6s' in info and len(info['ip6s']) > 0:
                ip_v6 = info['ip6s'][0]
            if len(info['dns']) > 0:
                dns = info['dns'][0]
            else:
                dns = ''

            interface_str = "%s;%s;%s;%s;%s;%s" % \
                                            (info['mac'],
                                             ip_v4 and ip_v4['ip'] or '',
                                             ip_v4 and ip_v4['netmask'] or '',
                                             info['gateway'],
                                             info['broadcast'],
                                             dns)
            machine_id_str = machine_id_str + interface_str + '#'

        machine_id_change_spec = \
            vm_util.get_machine_id_change_spec(client_factory, machine_id_str)

        LOG.debug(
            _("Reconfiguring VM instance %(name)s to set the machine id "
              "with ip - %(ip_addr)s") % ({
                  'name': instance.name,
                  'ip_addr': ip_v4['ip']
              }))
        reconfig_task = self._session._call_method(self._session._get_vim(),
                                                   "ReconfigVM_Task",
                                                   vm_ref,
                                                   spec=machine_id_change_spec)
        self._session._wait_for_task(instance['uuid'], reconfig_task)
        LOG.debug(
            _("Reconfigured VM instance %(name)s to set the machine id "
              "with ip - %(ip_addr)s") % ({
                  'name': instance.name,
                  'ip_addr': ip_v4['ip']
              }))
Esempio n. 10
0
 def detach_volume(self, connection_info, instance_name, mountpoint):
     """Detach volume storage to VM instance"""
     # Before we start, check that the VM exists
     vm_ref = VMHelper.lookup(self._session, instance_name)
     if vm_ref is None:
         raise exception.InstanceNotFound(instance_id=instance_name)
     # Detach VBD from VM
     LOG.debug(
         _("Detach_volume: %(instance_name)s, %(mountpoint)s") % locals())
     device_number = VolumeHelper.mountpoint_to_number(mountpoint)
     try:
         vbd_ref = VMHelper.find_vbd_by_number(self._session, vm_ref,
                                               device_number)
     except StorageError, exc:
         LOG.exception(exc)
         raise Exception(_('Unable to locate volume %s') % mountpoint)
Esempio n. 11
0
    def attach_volume(self, connection_info, instance_name, mountpoint):
        """Attach volume storage to VM instance"""
        # Before we start, check that the VM exists
        vm_ref = VMHelper.lookup(self._session, instance_name)
        if vm_ref is None:
            raise exception.InstanceNotFound(instance_id=instance_name)
        # NOTE: No Resource Pool concept so far
        LOG.debug(
            _("Attach_volume: %(connection_info)s, %(instance_name)s,"
              " %(mountpoint)s") % locals())
        driver_type = connection_info['driver_volume_type']
        if driver_type not in ['iscsi', 'xensm']:
            raise exception.VolumeDriverNotFound(driver_type=driver_type)

        data = connection_info['data']
        if 'name_label' not in data:
            label = 'tempSR-%s' % data['volume_id']
        else:
            label = data['name_label']
            del data['name_label']

        if 'name_description' not in data:
            desc = 'Disk-for:%s' % instance_name
        else:
            desc = data['name_description']

        LOG.debug(connection_info)
        sr_params = {}
        if u'sr_uuid' not in data:
            sr_params = VolumeHelper.parse_volume_info(connection_info,
                                                       mountpoint)
            uuid = "FA15E-D15C-" + str(sr_params['id'])
            sr_params['sr_type'] = 'iscsi'
        else:
            uuid = data['sr_uuid']
            for k in data['introduce_sr_keys']:
                sr_params[k] = data[k]

        sr_params['name_description'] = desc

        # Introduce SR
        try:
            sr_ref = self.introduce_sr(uuid, label, sr_params)
            LOG.debug(_('Introduced %(label)s as %(sr_ref)s.') % locals())
        except self.XenAPI.Failure, exc:
            LOG.exception(exc)
            raise StorageError(_('Unable to introduce Storage Repository'))
Esempio n. 12
0
    def reboot(self, instance, network_info):
        """Reboot a VM instance."""
        vm_ref = self._get_vm_ref_from_the_name(instance.name)
        if vm_ref is None:
            raise exception.InstanceNotFound(instance_id=instance.id)

        self.plug_vifs(instance, network_info)

        lst_properties = [
            "summary.guest.toolsStatus", "runtime.powerState",
            "summary.guest.toolsRunningStatus"
        ]
        props = self._session._call_method(vim_util, "get_object_properties",
                                           None, vm_ref, "VirtualMachine",
                                           lst_properties)
        pwr_state = None
        tools_status = None
        tools_running_status = False
        for elem in props:
            for prop in elem.propSet:
                if prop.name == "runtime.powerState":
                    pwr_state = prop.val
                elif prop.name == "summary.guest.toolsStatus":
                    tools_status = prop.val
                elif prop.name == "summary.guest.toolsRunningStatus":
                    tools_running_status = prop.val

        # Raise an exception if the VM is not powered On.
        if pwr_state not in ["poweredOn"]:
            reason = _("instance is not powered on")
            raise exception.InstanceRebootFailure(reason=reason)

        # If latest vmware tools are installed in the VM, and that the tools
        # are running, then only do a guest reboot. Otherwise do a hard reset.
        if (tools_status == "toolsOk"
                and tools_running_status == "guestToolsRunning"):
            LOG.debug(_("Rebooting guest OS of VM %s") % instance.name)
            self._session._call_method(self._session._get_vim(), "RebootGuest",
                                       vm_ref)
            LOG.debug(_("Rebooted guest OS of VM %s") % instance.name)
        else:
            LOG.debug(_("Doing hard reboot of VM %s") % instance.name)
            reset_task = self._session._call_method(self._session._get_vim(),
                                                    "ResetVM_Task", vm_ref)
            self._session._wait_for_task(instance['uuid'], reset_task)
            LOG.debug(_("Did hard reboot of VM %s") % instance.name)
Esempio n. 13
0
 def get_console_output(self, instance):
     """Return snapshot of console."""
     vm_ref = self._get_vm_ref_from_the_name(instance.name)
     if vm_ref is None:
         raise exception.InstanceNotFound(instance_id=instance.id)
     param_list = {"id": str(vm_ref)}
     base_url = "%s://%s/screen?%s" % (self._session._scheme,
                                       self._session._host_ip,
                                       urllib.urlencode(param_list))
     request = urllib2.Request(base_url)
     base64string = base64.encodestring(
         '%s:%s' % (self._session._host_username,
                    self._session._host_password)).replace('\n', '')
     request.add_header("Authorization", "Basic %s" % base64string)
     result = urllib2.urlopen(request)
     if result.code == 200:
         return result.read()
     else:
         return ""
Esempio n. 14
0
    def resume(self, instance):
        """Resume the specified instance."""
        vm_ref = self._get_vm_ref_from_the_name(instance.name)
        if vm_ref is None:
            raise exception.InstanceNotFound(instance_id=instance.id)

        pwr_state = self._session._call_method(vim_util,
                                               "get_dynamic_property", vm_ref,
                                               "VirtualMachine",
                                               "runtime.powerState")
        if pwr_state.lower() == "suspended":
            LOG.debug(_("Resuming the VM %s") % instance.name)
            suspend_task = self._session._call_method(self._session._get_vim(),
                                                      "PowerOnVM_Task", vm_ref)
            self._session._wait_for_task(instance['uuid'], suspend_task)
            LOG.debug(_("Resumed the VM %s ") % instance.name)
        else:
            reason = _("instance is not in a suspended state")
            raise exception.InstanceResumeFailure(reason=reason)
Esempio n. 15
0
 def detach_volume(self, connection_info, instance_name, mountpoint):
     vm = self._lookup(instance_name)
     if vm is None:
         raise exception.InstanceNotFound(instance_id=instance_name)
Esempio n. 16
0
def return_server_nonexistant(context, server_id):
    raise exception.InstanceNotFound()
Esempio n. 17
0
 def reboot(self, instance, network_info, reboot_type):
     """Reboot the specified instance."""
     vm = self._lookup(instance.name)
     if vm is None:
         raise exception.InstanceNotFound(instance_id=instance.id)
     self._set_vm_state(instance.name, 'Reboot')
Esempio n. 18
0
 def server_not_found(self, instance_id):
     raise exception.InstanceNotFound(instance_id=instance_id)
Esempio n. 19
0
    def snapshot(self, context, instance, snapshot_name):
        """
        Create snapshot from a running VM instance.
        Steps followed are:
        1. Get the name of the vmdk file which the VM points to right now.
            Can be a chain of snapshots, so we need to know the last in the
            chain.
        2. Create the snapshot. A new vmdk is created which the VM points to
            now. The earlier vmdk becomes read-only.
        3. Call CopyVirtualDisk which coalesces the disk chain to form a single
            vmdk, rather a .vmdk metadata file and a -flat.vmdk disk data file.
        4. Now upload the -flat.vmdk file to the image store.
        5. Delete the coalesced .vmdk and -flat.vmdk created.
        """
        vm_ref = self._get_vm_ref_from_the_name(instance.name)
        if vm_ref is None:
            raise exception.InstanceNotFound(instance_id=instance.id)

        client_factory = self._session._get_vim().client.factory
        service_content = self._session._get_vim().get_service_content()

        def _get_vm_and_vmdk_attribs():
            # Get the vmdk file name that the VM is pointing to
            hardware_devices = self._session._call_method(
                vim_util, "get_dynamic_property", vm_ref, "VirtualMachine",
                "config.hardware.device")
            vmdk_file_path_before_snapshot, adapter_type = \
                vm_util.get_vmdk_file_path_and_adapter_type(client_factory,
                                                            hardware_devices)
            datastore_name = vm_util.split_datastore_path(
                vmdk_file_path_before_snapshot)[0]
            os_type = self._session._call_method(vim_util,
                                                 "get_dynamic_property",
                                                 vm_ref, "VirtualMachine",
                                                 "summary.config.guestId")
            return (vmdk_file_path_before_snapshot, adapter_type,
                    datastore_name, os_type)

        vmdk_file_path_before_snapshot, adapter_type, datastore_name,\
            os_type = _get_vm_and_vmdk_attribs()

        def _create_vm_snapshot():
            # Create a snapshot of the VM
            LOG.debug(
                _("Creating Snapshot of the VM instance %s ") % instance.name)
            snapshot_task = self._session._call_method(
                self._session._get_vim(),
                "CreateSnapshot_Task",
                vm_ref,
                name="%s-snapshot" % instance.name,
                description="Taking Snapshot of the VM",
                memory=True,
                quiesce=True)
            self._session._wait_for_task(instance['uuid'], snapshot_task)
            LOG.debug(
                _("Created Snapshot of the VM instance %s ") % instance.name)

        _create_vm_snapshot()

        def _check_if_tmp_folder_exists():
            # Copy the contents of the VM that were there just before the
            # snapshot was taken
            ds_ref_ret = vim_util.get_dynamic_property(
                self._session._get_vim(), vm_ref, "VirtualMachine",
                "datastore")
            if not ds_ref_ret:
                raise exception.DatastoreNotFound()
            ds_ref = ds_ref_ret.ManagedObjectReference[0]
            ds_browser = vim_util.get_dynamic_property(
                self._session._get_vim(), ds_ref, "Datastore", "browser")
            # Check if the vmware-tmp folder exists or not. If not, create one
            tmp_folder_path = vm_util.build_datastore_path(
                datastore_name, "vmware-tmp")
            if not self._path_exists(ds_browser, tmp_folder_path):
                self._mkdir(
                    vm_util.build_datastore_path(datastore_name, "vmware-tmp"))

        _check_if_tmp_folder_exists()

        # Generate a random vmdk file name to which the coalesced vmdk content
        # will be copied to. A random name is chosen so that we don't have
        # name clashes.
        random_name = str(uuid.uuid4())
        dest_vmdk_file_location = vm_util.build_datastore_path(
            datastore_name, "vmware-tmp/%s.vmdk" % random_name)
        dc_ref = self._get_datacenter_name_and_ref()[0]

        def _copy_vmdk_content():
            # Copy the contents of the disk ( or disks, if there were snapshots
            # done earlier) to a temporary vmdk file.
            copy_spec = vm_util.get_copy_virtual_disk_spec(
                client_factory, adapter_type)
            LOG.debug(
                _("Copying disk data before snapshot of the VM "
                  " instance %s") % instance.name)
            copy_disk_task = self._session._call_method(
                self._session._get_vim(),
                "CopyVirtualDisk_Task",
                service_content.virtualDiskManager,
                sourceName=vmdk_file_path_before_snapshot,
                sourceDatacenter=dc_ref,
                destName=dest_vmdk_file_location,
                destDatacenter=dc_ref,
                destSpec=copy_spec,
                force=False)
            self._session._wait_for_task(instance['uuid'], copy_disk_task)
            LOG.debug(
                _("Copied disk data before snapshot of the VM "
                  "instance %s") % instance.name)

        _copy_vmdk_content()

        cookies = self._session._get_vim().client.options.transport.cookiejar

        def _upload_vmdk_to_image_repository():
            # Upload the contents of -flat.vmdk file which has the disk data.
            LOG.debug(_("Uploading image %s") % snapshot_name)
            vmware_images.upload_image(
                context,
                snapshot_name,
                instance,
                os_type=os_type,
                adapter_type=adapter_type,
                image_version=1,
                host=self._session._host_ip,
                data_center_name=self._get_datacenter_name_and_ref()[1],
                datastore_name=datastore_name,
                cookies=cookies,
                file_path="vmware-tmp/%s-flat.vmdk" % random_name)
            LOG.debug(_("Uploaded image %s") % snapshot_name)

        _upload_vmdk_to_image_repository()

        def _clean_temp_data():
            """
            Delete temporary vmdk files generated in image handling
            operations.
            """
            # Delete the temporary vmdk created above.
            LOG.debug(
                _("Deleting temporary vmdk file %s") % dest_vmdk_file_location)
            remove_disk_task = self._session._call_method(
                self._session._get_vim(),
                "DeleteVirtualDisk_Task",
                service_content.virtualDiskManager,
                name=dest_vmdk_file_location,
                datacenter=dc_ref)
            self._session._wait_for_task(instance['uuid'], remove_disk_task)
            LOG.debug(
                _("Deleted temporary vmdk file %s") % dest_vmdk_file_location)

        _clean_temp_data()
Esempio n. 20
0
 def fake_compute_get(*args, **kwargs):
     raise exception.InstanceNotFound()
Esempio n. 21
0
 def fake_delete_console(cons_self, context, instance_id, console_id):
     raise exception.InstanceNotFound(instance_id=instance_id)
Esempio n. 22
0
 def not_found(context):
     raise exception.InstanceNotFound(instance_id=5)