From c0d3b8415ed34c6b259e183a047ca37c9598ffd4 Mon Sep 17 00:00:00 2001 From: sateesh Date: Wed, 23 Feb 2011 20:04:53 +0530 Subject: * Took care of localization of strings * Addressed all one liner docstrings * Added Sateesh, Milind to Authors file --- nova/virt/vmwareapi/__init__.py | 5 +- nova/virt/vmwareapi/io_util.py | 44 ++----- nova/virt/vmwareapi/read_write_util.py | 182 +++++++------------------- nova/virt/vmwareapi/vim.py | 74 ++++------- nova/virt/vmwareapi/vim_util.py | 48 ++----- nova/virt/vmwareapi/vm_util.py | 43 ++----- nova/virt/vmwareapi/vmops.py | 226 ++++++++++++++------------------- nova/virt/vmwareapi/vmware_images.py | 74 ++++------- nova/virt/vmwareapi_conn.py | 144 ++++++--------------- 9 files changed, 274 insertions(+), 566 deletions(-) (limited to 'nova') diff --git a/nova/virt/vmwareapi/__init__.py b/nova/virt/vmwareapi/__init__.py index 52e3ddf4d..0cf70150c 100644 --- a/nova/virt/vmwareapi/__init__.py +++ b/nova/virt/vmwareapi/__init__.py @@ -22,10 +22,7 @@ class HelperBase(object): - """ - The base for helper classes. This adds the VMwareAPI class attribute - """ - + """The base for helper classes. This adds the VMwareAPI class attribute""" VMwareAPI = None def __init__(self): diff --git a/nova/virt/vmwareapi/io_util.py b/nova/virt/vmwareapi/io_util.py index 3b3cbee33..6761d894c 100644 --- a/nova/virt/vmwareapi/io_util.py +++ b/nova/virt/vmwareapi/io_util.py @@ -36,39 +36,27 @@ THREAD_SLEEP_TIME = .01 class ThreadSafePipe(Queue): - """ - ThreadSafePipe class queue's the chunk data. - """ + """ThreadSafePipe class queue's the chunk data.""" def __init__(self, max_size=None): - """ - Initializes the queue - """ + """Initializes the queue""" Queue.__init__(self, max_size) self.eof = False def write(self, data): - """ - Writes the chunk data to the queue. - """ + """Writes the chunk data to the queue.""" self.put(data, block=False) def read(self): - """ - Retrieves the chunk data from the queue. - """ + """Retrieves the chunk data from the queue.""" return self.get(block=False) def set_eof(self, eof): - """ - Sets EOF to mark reading of input file finishes. - """ + """Sets EOF to mark reading of input file finishes.""" self.eof = eof def get_eof(self): - """ - Returns whether EOF reached. - """ + """Returns whether EOF reached.""" return self.eof @@ -143,8 +131,8 @@ class IOThread(Thread): if not self.transfer_size is None: if self.read_size < self.transfer_size: - raise IOError("Not enough data (%d of %d bytes)" \ - % (self.read_size, self.transfer_size)) + raise IOError(_("Not enough data (%d of %d bytes)") % \ + (self.read_size, self.transfer_size)) except Exception: self._error = True @@ -152,26 +140,18 @@ class IOThread(Thread): self._done = True def stop_io_transfer(self): - """ - Set the stop flag to true, which causes the thread to stop safely. - """ + """Set stop flag to true, which causes the thread to stop safely.""" self._stop_transfer = True self.join() def get_error(self): - """ - Returns the error string. - """ + """Returns the error string.""" return self._error def get_exception(self): - """ - Returns the traceback exception string. - """ + """Returns the traceback exception string.""" return self._exception def is_done(self): - """ - Checks whether transfer is complete. - """ + """Checks whether transfer is complete.""" return self._done diff --git a/nova/virt/vmwareapi/read_write_util.py b/nova/virt/vmwareapi/read_write_util.py index fcd95308a..45214be04 100644 --- a/nova/virt/vmwareapi/read_write_util.py +++ b/nova/virt/vmwareapi/read_write_util.py @@ -15,7 +15,7 @@ # License for the specific language governing permissions and limitations # under the License. -""" Image file handlers +""" Classes to handle image files Collection of classes to handle image upload/download to/from Image service (like Glance image storage and retrieval service) from/to ESX/ESXi server. @@ -47,79 +47,55 @@ LOG = logging.getLogger("nova.virt.vmwareapi.read_write_util") class ImageServiceFile: - """ - The base image service Class - """ + """The base image service Class""" def __init__(self, file_handle): - """ - Initialize the file handle. - """ + """Initialize the file handle.""" self.eof = False self.file_handle = file_handle def write(self, data): - """ - Write data to the file - """ + """Write data to the file""" raise NotImplementedError def read(self, chunk_size=READ_CHUNKSIZE): - """ - Read a chunk of data from the file - """ + """Read a chunk of data from the file""" raise NotImplementedError def get_size(self): - """ - Get the size of the file whose data is to be read - """ + """Get the size of the file whose data is to be read""" raise NotImplementedError def set_eof(self, eof): - """ - Set the end of file marker. - """ + """Set the end of file marker.""" self.eof = eof def get_eof(self): - """ - Check if the file end has been reached or not. - """ + """Check if the file end has been reached or not.""" return self.eof def close(self): - """ - Close the file handle. - """ + """Close the file handle.""" try: self.file_handle.close() except Exception: pass def get_image_properties(self): - """ - Get the image properties - """ + """Get the image properties""" raise NotImplementedError def __del__(self): - """ - Destructor. Close the file handle if the same has been forgotten. - """ + """Destructor. Close the file handle if the same has been forgotten.""" self.close() class GlanceHTTPWriteFile(ImageServiceFile): - """ - Glance file write handler Class - """ + """Glance file write handler Class""" def __init__(self, host, port, image_id, file_size, os_type, adapter_type, version=1, scheme="http"): - """ - Initialize with the glance host specifics. - """ + """Initialize with the glance host specifics.""" base_url = "%s://%s:%s/images/%s" % (scheme, host, port, image_id) (scheme, netloc, path, params, query, fragment) = \ urlparse.urlparse(base_url) @@ -145,21 +121,15 @@ class GlanceHTTPWriteFile(ImageServiceFile): ImageServiceFile.__init__(self, conn) def write(self, data): - """ - Write data to the file - """ + """Write data to the file""" self.file_handle.send(data) class GlanceHTTPReadFile(ImageServiceFile): - """ - Glance file read handler Class - """ + """Glance file read handler Class""" def __init__(self, host, port, image_id, scheme="http"): - """ - Initialize with the glance host specifics. - """ + """Initialize with the glance host specifics.""" base_url = "%s://%s:%s/images/%s" % (scheme, host, port, urllib.pathname2url(image_id)) headers = {'User-Agent': USER_AGENT} @@ -168,21 +138,15 @@ class GlanceHTTPReadFile(ImageServiceFile): ImageServiceFile.__init__(self, conn) def read(self, chunk_size=READ_CHUNKSIZE): - """ - Read a chunk of data. - """ + """Read a chunk of data.""" return self.file_handle.read(chunk_size) def get_size(self): - """ - Get the size of the file to be read. - """ + """Get the size of the file to be read.""" return self.file_handle.headers.get("X-Image-Meta-Size", -1) def get_image_properties(self): - """ - Get the image properties like say OS Type and the Adapter Type - """ + """Get the image properties like say OS Type and the Adapter Type""" return {"vmware_ostype": self.file_handle.headers.get( "X-Image-Meta-Property-Vmware_ostype"), @@ -195,134 +159,94 @@ class GlanceHTTPReadFile(ImageServiceFile): class FakeFileRead(ImageServiceFile): - """ - Local file read handler class - """ + """Local file read handler class""" def __init__(self, path): - """ - Initialize the file path - """ + """Initialize the file path""" self.path = path file_handle = open(path, "rb") ImageServiceFile.__init__(self, file_handle) def get_size(self): - """ - Get size of the file to be read - """ + """Get size of the file to be read""" return os.path.getsize(os.path.abspath(self.path)) def read(self, chunk_size=READ_CHUNKSIZE): - """ - Read a chunk of data - """ + """Read a chunk of data""" return self.file_handle.read(chunk_size) def get_image_properties(self): - """ - Get the image properties like say OS Type and the Adapter Type - """ + """Get the image properties like say OS Type and the Adapter Type""" return {"vmware_ostype": "otherGuest", "vmware_adaptertype": "lsiLogic", "vmware_image_version": "1"} class FakeFileWrite(ImageServiceFile): - """ - Local file write handler Class - """ + """Local file write handler Class""" def __init__(self, path): - """ - Initialize the file path. - """ + """Initialize the file path.""" file_handle = open(path, "wb") ImageServiceFile.__init__(self, file_handle) def write(self, data): - """ - Write data to the file. - """ + """Write data to the file.""" self.file_handle.write(data) class VMwareHTTPFile(object): - """ - Base Class for HTTP file. - """ + """Base Class for HTTP file.""" def __init__(self, file_handle): - """ - Intialize the file handle. - """ + """Intialize the file handle.""" self.eof = False self.file_handle = file_handle def set_eof(self, eof): - """ - Set the end of file marker. - """ + """Set the end of file marker.""" self.eof = eof def get_eof(self): - """ - Check if the end of file has been reached. - """ + """Check if the end of file has been reached.""" return self.eof def close(self): - """ - Close the file handle. - """ + """Close the file handle.""" try: self.file_handle.close() except Exception: pass def __del__(self): - """ - Destructor. Close the file handle if the same has been forgotten. - """ + """Destructor. Close the file handle if the same has been forgotten.""" self.close() def _build_vim_cookie_headers(self, vim_cookies): - """ - Build ESX host session cookie headers. - """ + """Build ESX host session cookie headers.""" cookie = str(vim_cookies).split(":")[1].strip() cookie = cookie[:cookie.find(';')] return cookie def write(self, data): - """ - Write data to the file. - """ + """Write data to the file.""" raise NotImplementedError def read(self, chunk_size=READ_CHUNKSIZE): - """ - Read a chunk of data. - """ + """Read a chunk of data.""" raise NotImplementedError def get_size(self): - """ - Get size of the file to be read. - """ + """Get size of the file to be read.""" raise NotImplementedError class VMWareHTTPWriteFile(VMwareHTTPFile): - """ - VMWare file write handler Class - """ + """VMWare file write handler Class""" def __init__(self, host, data_center_name, datastore_name, cookies, file_path, file_size, scheme="https"): - """ - Initialize the file specifics. - """ + """Initialize the file specifics.""" base_url = "%s://%s/folder/%s" % (scheme, host, file_path) param_list = {"dcPath": data_center_name, "dsName": datastore_name} base_url = base_url + "?" + urllib.urlencode(param_list) @@ -341,33 +265,25 @@ class VMWareHTTPWriteFile(VMwareHTTPFile): VMwareHTTPFile.__init__(self, conn) def write(self, data): - """ - Write to the file. - """ + """Write to the file.""" self.file_handle.send(data) def close(self): - """ - Get the response and close the connection - """ + """Get the response and close the connection""" try: self.conn.getresponse() except Exception, excep: - LOG.debug("Exception during close of connection in " - "VMWareHTTpWrite. Exception is %s" % excep) + LOG.debug(_("Exception during close of connection in " + "VMWareHTTpWrite. Exception is %s") % excep) super(VMWareHTTPWriteFile, self).close() class VmWareHTTPReadFile(VMwareHTTPFile): - """ - VMWare file read handler Class - """ + """VMWare file read handler Class""" def __init__(self, host, data_center_name, datastore_name, cookies, file_path, scheme="https"): - """ - Initialize the file specifics. - """ + """Initialize the file specifics.""" base_url = "%s://%s/folder/%s" % (scheme, host, urllib.pathname2url(file_path)) param_list = {"dcPath": data_center_name, "dsName": datastore_name} @@ -379,13 +295,9 @@ class VmWareHTTPReadFile(VMwareHTTPFile): VMwareHTTPFile.__init__(self, conn) def read(self, chunk_size=READ_CHUNKSIZE): - """ - Read a chunk of data. - """ + """Read a chunk of data.""" return self.file_handle.read(chunk_size) def get_size(self): - """ - Get size of the file to be read. - """ + """Get size of the file to be read.""" return self.file_handle.headers.get("Content-Length", -1) diff --git a/nova/virt/vmwareapi/vim.py b/nova/virt/vmwareapi/vim.py index 3007535dd..9aca1b7ae 100644 --- a/nova/virt/vmwareapi/vim.py +++ b/nova/virt/vmwareapi/vim.py @@ -32,50 +32,36 @@ ADDRESS_IN_USE_ERROR = 'Address already in use' class VimException(Exception): - """ - The VIM Exception class - """ + """The VIM Exception class""" def __init__(self, exception_summary, excep): - """ - Initializer - """ + """Initializer""" Exception.__init__(self) self.exception_summary = exception_summary self.exception_obj = excep def __str__(self): - """ - The informal string representation of the object - """ + """The informal string representation of the object""" return self.exception_summary + str(self.exception_obj) class SessionOverLoadException(VimException): - """ - Session Overload Exception - """ + """Session Overload Exception""" pass class SessionFaultyException(VimException): - """ - Session Faulty Exception - """ + """Session Faulty Exception""" pass class VimAttributeError(VimException): - """ - Attribute Error - """ + """Attribute Error""" pass class Vim: - """ - The VIM Object - """ + """The VIM Object""" def __init__(self, protocol="https", @@ -106,15 +92,11 @@ class Vim: self.RetrieveServiceContent("ServiceInstance") def get_service_content(self): - """ - Gets the service content object - """ + """Gets the service content object""" return self._service_content def __getattr__(self, attr_name): - """ - Makes the API calls and gets the result - """ + """Makes the API calls and gets the result""" try: return object.__getattr__(self, attr_name) except AttributeError: @@ -141,40 +123,38 @@ class Vim: except AttributeError, excep: return None except AttributeError, excep: - raise VimAttributeError("No such SOAP method '%s'" - " provided by VI SDK" % (attr_name), excep) + raise VimAttributeError(_("No such SOAP method '%s'" + " provided by VI SDK") % (attr_name), excep) except ZSI.FaultException, excep: - raise SessionFaultyException(" in" - " %s:" % (attr_name), excep) + raise SessionFaultyException(_(" in" + " %s:") % (attr_name), excep) except ZSI.EvaluateException, excep: - raise SessionFaultyException(" in" - " %s:" % (attr_name), excep) + raise SessionFaultyException(_(" in" + " %s:") % (attr_name), excep) except (httplib.CannotSendRequest, httplib.ResponseNotReady, httplib.CannotSendHeader), excep: - raise SessionOverLoadException("httplib errror in" - " %s: " % (attr_name), excep) + raise SessionOverLoadException(_("httplib errror in" + " %s: ") % (attr_name), excep) except Exception, excep: # Socket errors which need special handling for they # might be caused by ESX API call overload if (str(excep).find(ADDRESS_IN_USE_ERROR) != -1 or str(excep).find(CONN_ABORT_ERROR)): - raise SessionOverLoadException("Socket error in" - " %s: " % (attr_name), excep) + raise SessionOverLoadException(_("Socket error in" + " %s: ") % (attr_name), excep) # Type error that needs special handling for it might be # caused by ESX host API call overload elif str(excep).find(RESP_NOT_XML_ERROR) != -1: - raise SessionOverLoadException("Type error in " - " %s: " % (attr_name), excep) + raise SessionOverLoadException(_("Type error in " + " %s: ") % (attr_name), excep) else: raise VimException( - "Exception in %s " % (attr_name), excep) + _("Exception in %s ") % (attr_name), excep) return vim_request_handler def _request_message_builder(self, method_name, managed_object, **kwargs): - """ - Builds the Request Message - """ + """Builds the Request Message""" #Request Message Builder request_msg = getattr(VimService_services, \ method_name + "RequestMsg")() @@ -189,13 +169,9 @@ class Vim: return request_msg def __repr__(self): - """ - The official string representation - """ + """The official string representation""" return "VIM Object" def __str__(self): - """ - The informal string representation - """ + """The informal string representation""" return "VIM Object" diff --git a/nova/virt/vmwareapi/vim_util.py b/nova/virt/vmwareapi/vim_util.py index d38d8b949..d07f7c278 100644 --- a/nova/virt/vmwareapi/vim_util.py +++ b/nova/virt/vmwareapi/vim_util.py @@ -26,9 +26,7 @@ MAX_CLONE_RETRIES = 1 def build_recursive_traversal_spec(): - """ - Builds the Traversal Spec - """ + """Builds the Traversal Spec""" #Traversal through "hostFolder" branch visit_folders_select_spec = ns0.SelectionSpec_Def("visitFolders").pyclass() visit_folders_select_spec.set_element_name("visitFolders") @@ -145,9 +143,7 @@ def build_recursive_traversal_spec(): def build_property_spec(type="VirtualMachine", properties_to_collect=["name"], all_properties=False): - """ - Builds the Property Spec - """ + """Builds the Property Spec""" property_spec = ns0.PropertySpec_Def("propertySpec").pyclass() property_spec.set_element_type(type) property_spec.set_element_all(all_properties) @@ -156,9 +152,7 @@ def build_property_spec(type="VirtualMachine", properties_to_collect=["name"], def build_object_spec(root_folder, traversal_specs): - """ - Builds the object Spec - """ + """Builds the object Spec""" object_spec = ns0.ObjectSpec_Def("ObjectSpec").pyclass() object_spec.set_element_obj(root_folder) object_spec.set_element_skip(False) @@ -167,9 +161,7 @@ def build_object_spec(root_folder, traversal_specs): def build_property_filter_spec(property_specs, object_specs): - """ - Builds the Property Filter Spec - """ + """Builds the Property Filter Spec""" property_filter_spec = \ ns0.PropertyFilterSpec_Def("PropertyFilterSpec").pyclass() property_filter_spec.set_element_propSet(property_specs) @@ -178,9 +170,7 @@ def build_property_filter_spec(property_specs, object_specs): def get_object_properties(vim, collector, mobj, type, properties): - """ - Gets the properties of the Managed object specified - """ + """Gets the properties of the Managed object specified""" if mobj is None: return None usecoll = collector @@ -203,9 +193,7 @@ def get_object_properties(vim, collector, mobj, type, properties): def get_dynamic_property(vim, mobj, type, property_name): - """ - Gets a particular property of the Managed Object - """ + """Gets a particular property of the Managed Object""" obj_content = \ get_object_properties(vim, None, mobj, type, [property_name]) property_value = None @@ -217,9 +205,7 @@ def get_dynamic_property(vim, mobj, type, property_name): def get_objects(vim, type, properties_to_collect=["name"], all=False): - """ - Gets the list of objects of the type specified - """ + """Gets the list of objects of the type specified""" object_spec = build_object_spec(vim.get_service_content().RootFolder, [build_recursive_traversal_spec()]) property_spec = build_property_spec(type=type, @@ -232,9 +218,7 @@ def get_objects(vim, type, properties_to_collect=["name"], all=False): def get_traversal_spec(type, path, name="traversalSpec"): - """ - Builds the traversal spec object - """ + """Builds the traversal spec object""" t_spec = ns0.TraversalSpec_Def(name).pyclass() t_spec._name = name t_spec._type = type @@ -244,9 +228,7 @@ def get_traversal_spec(type, path, name="traversalSpec"): def get_prop_spec(type, properties): - """ - Builds the Property Spec Object - """ + """Builds the Property Spec Object""" prop_spec = ns0.PropertySpec_Def("PropertySpec").pyclass() prop_spec._type = type prop_spec._pathSet = properties @@ -254,9 +236,7 @@ def get_prop_spec(type, properties): def get_obj_spec(obj, select_set=None): - """ - Builds the Object Spec object - """ + """Builds the Object Spec object""" obj_spec = ns0.ObjectSpec_Def("ObjectSpec").pyclass() obj_spec._obj = obj obj_spec._skip = False @@ -266,9 +246,7 @@ def get_obj_spec(obj, select_set=None): def get_prop_filter_spec(obj_spec, prop_spec): - """ - Builds the Property Filter Spec Object - """ + """Builds the Property Filter Spec Object""" prop_filter_spec = \ ns0.PropertyFilterSpec_Def("PropertyFilterSpec").pyclass() prop_filter_spec._propSet = prop_spec @@ -279,8 +257,8 @@ def get_prop_filter_spec(obj_spec, prop_spec): def get_properites_for_a_collection_of_objects(vim, type, obj_list, properties): """ - Gets the list of properties for the collection of - objects of the type specified + Gets the list of properties for the collection of objects of the + type specified """ if len(obj_list) == 0: return [] diff --git a/nova/virt/vmwareapi/vm_util.py b/nova/virt/vmwareapi/vm_util.py index b1202f2b1..05e49de83 100644 --- a/nova/virt/vmwareapi/vm_util.py +++ b/nova/virt/vmwareapi/vm_util.py @@ -24,9 +24,7 @@ from nova.virt.vmwareapi.VimService_services_types import ns0 def build_datastore_path(datastore_name, path): - """ - Build the datastore compliant path - """ + """Builds the datastore compliant path.""" return "[%s] %s" % (datastore_name, path) @@ -46,9 +44,7 @@ def split_datastore_path(datastore_path): def get_vm_create_spec(instance, data_store_name, network_name="vmnet0", os_type="otherGuest"): - """ - Builds the VM Create spec - """ + """Builds the VM Create spec.""" config_spec = ns0.VirtualMachineConfigSpec_Def( "VirtualMachineConfigSpec").pyclass() @@ -101,7 +97,8 @@ def create_controller_spec(key): def create_network_spec(network_name, mac_address): """ - Builds a config spec for the addition of a new network adapter to the VM + Builds a config spec for the addition of a new network adapter to + the VM. """ network_spec = \ ns0.VirtualDeviceConfigSpec_Def("VirtualDeviceConfigSpec").pyclass() @@ -137,9 +134,7 @@ def create_network_spec(network_name, mac_address): def get_datastore_search_sepc(pattern=None): - """ - Builds the datastore search spec. - """ + """Builds the datastore search spec.""" host_datastore_browser_search_spec = \ ns0.HostDatastoreBrowserSearchSpec_Def( "HostDatastoreBrowserSearchSpec").pyclass() @@ -155,9 +150,7 @@ def get_datastore_search_sepc(pattern=None): def get_vmdk_attach_config_sepc(disksize, file_path, adapter_type="lsiLogic"): - """ - Builds the vmdk attach config spec. - """ + """Builds the vmdk attach config spec.""" config_spec = ns0.VirtualMachineConfigSpec_Def( "VirtualMachineConfigSpec").pyclass() @@ -182,9 +175,7 @@ def get_vmdk_attach_config_sepc(disksize, file_path, adapter_type="lsiLogic"): def get_vmdk_file_path_and_adapter_type(hardware_devices): - """ - Gets the vmdk file path and the storage adapter type - """ + """Gets the vmdk file path and the storage adapter type.""" if isinstance(hardware_devices.typecode, ns0.ArrayOfVirtualDevice_Def): hardware_devices = hardware_devices.VirtualDevice vmdk_file_path = None @@ -212,9 +203,7 @@ def get_vmdk_file_path_and_adapter_type(hardware_devices): def get_copy_virtual_disk_spec(adapter_type="lsilogic"): - """ - Builds the Virtual Disk copy spec. - """ + """Builds the Virtual Disk copy spec.""" dest_spec = ns0.VirtualDiskSpec_Def("VirtualDiskSpec").pyclass() dest_spec.AdapterType = adapter_type dest_spec.DiskType = "thick" @@ -222,9 +211,7 @@ def get_copy_virtual_disk_spec(adapter_type="lsilogic"): def get_vmdk_create_spec(size_in_kb, adapter_type="lsiLogic"): - """ - Builds the virtual disk create sepc. - """ + """Builds the virtual disk create sepc.""" create_vmdk_spec = \ ns0.FileBackedVirtualDiskSpec_Def("VirtualDiskSpec").pyclass() create_vmdk_spec._adapterType = adapter_type @@ -234,9 +221,7 @@ def get_vmdk_create_spec(size_in_kb, adapter_type="lsiLogic"): def create_virtual_disk_spec(disksize, controller_key, file_path=None): - """ - Creates a Spec for the addition/attaching of a Virtual Disk to the VM - """ + """Creates a Spec for the addition/attaching of a Virtual Disk to the VM""" virtual_device_config = \ ns0.VirtualDeviceConfigSpec_Def("VirtualDeviceConfigSpec").pyclass() virtual_device_config._operation = "add" @@ -277,9 +262,7 @@ def create_virtual_disk_spec(disksize, controller_key, file_path=None): def get_dummy_vm_create_spec(name, data_store_name): - """ - Builds the dummy VM create spec - """ + """Builds the dummy VM create spec.""" config_spec = ns0.VirtualMachineConfigSpec_Def( "VirtualMachineConfigSpec").pyclass() @@ -313,9 +296,7 @@ def get_dummy_vm_create_spec(name, data_store_name): def get_machine_id_change_spec(mac, ip_addr, netmask, gateway): - """ - Builds the machine id change config spec - """ + """Builds the machine id change config spec.""" machine_id_str = "%s;%s;%s;%s" % (mac, ip_addr, netmask, gateway) virtual_machine_config_spec = ns0.VirtualMachineConfigSpec_Def( "VirtualMachineConfigSpec").pyclass() diff --git a/nova/virt/vmwareapi/vmops.py b/nova/virt/vmwareapi/vmops.py index 4eda4ef0e..da22588e3 100644 --- a/nova/virt/vmwareapi/vmops.py +++ b/nova/virt/vmwareapi/vmops.py @@ -40,20 +40,14 @@ VMWARE_POWER_STATES = { class VMWareVMOps(object): - """ - Management class for VM-related tasks - """ + """Management class for VM-related tasks""" def __init__(self, session): - """ - Initializer - """ + """Initializer""" self._session = session def _wait_with_callback(self, instance_id, task, callback): - """ - Waits for the task to finish and does a callback after - """ + """Waits for the task to finish and does a callback after""" ret = None try: ret = self._session._wait_for_task(instance_id, task) @@ -62,10 +56,8 @@ class VMWareVMOps(object): callback(ret) def list_instances(self): - """ - Lists the VM instances that are registered with the ESX host - """ - LOG.debug("Getting list of instances") + """Lists the VM instances that are registered with the ESX host""" + LOG.debug(_("Getting list of instances")) vms = self._session._call_method(vim_util, "get_objects", "VirtualMachine", ["name", "runtime.connectionState"]) @@ -81,7 +73,7 @@ class VMWareVMOps(object): # Ignoring the oprhaned or inaccessible VMs if conn_state not in ["orphaned", "inaccessible"]: lst_vm_names.append(vm_name) - LOG.debug("Got total of %s instances" % str(len(lst_vm_names))) + LOG.debug(_("Got total of %s instances") % str(len(lst_vm_names))) return lst_vm_names def spawn(self, instance): @@ -140,7 +132,7 @@ class VMWareVMOps(object): break if data_store_name is None: - msg = "Couldn't get a local Datastore reference" + msg = _("Couldn't get a local Datastore reference") LOG.exception(msg) raise Exception(msg) @@ -158,7 +150,7 @@ class VMWareVMOps(object): res_pool_mor = self._session._call_method(vim_util, "get_objects", "ResourcePool")[0].Obj - LOG.debug("Creating VM with the name %s on the ESX host" % + LOG.debug(_("Creating VM with the name %s on the ESX host") % \ instance.name) #Create the VM on the ESX host vm_create_task = self._session._call_method(self._session._get_vim(), @@ -166,7 +158,7 @@ class VMWareVMOps(object): config=config_spec, pool=res_pool_mor) self._session._wait_for_task(instance.id, vm_create_task) - LOG.debug("Created VM with the name %s on the ESX host" % + LOG.debug(_("Created VM with the name %s on the ESX host") % \ instance.name) # Set the machine id for the VM for setting the IP @@ -189,8 +181,8 @@ class VMWareVMOps(object): #depend on the size of the disk, thin/thick provisioning and the #storage adapter type. #Here we assume thick provisioning and lsiLogic for the adapter type - LOG.debug("Creating Virtual Disk of size %s KB and adapter type %s on " - "the ESX host local store %s " % + LOG.debug(_("Creating Virtual Disk of size %sKB and adapter type %s on" + " the ESX host local store %s ") % \ (vmdk_file_size_in_kb, adapter_type, data_store_name)) vmdk_create_spec = vm_util.get_vmdk_create_spec(vmdk_file_size_in_kb, adapter_type) @@ -201,21 +193,21 @@ class VMWareVMOps(object): datacenter=self._get_datacenter_name_and_ref()[0], spec=vmdk_create_spec) self._session._wait_for_task(instance.id, vmdk_create_task) - LOG.debug("Created Virtual Disk of size %s KB on the ESX host local" - "store %s " % (vmdk_file_size_in_kb, data_store_name)) + LOG.debug(_("Created Virtual Disk of size %s KB on the ESX host local" + "store %s ") % (vmdk_file_size_in_kb, data_store_name)) - LOG.debug("Deleting the file %s on the ESX host local" - "store %s " % (flat_uploaded_vmdk_path, data_store_name)) + LOG.debug(_("Deleting the file %s on the ESX host local" + "store %s ") % (flat_uploaded_vmdk_path, data_store_name)) #Delete the -flat.vmdk file created. .vmdk file is retained. vmdk_delete_task = self._session._call_method(self._session._get_vim(), "DeleteDatastoreFile_Task", self._session._get_vim().get_service_content().FileManager, name=flat_uploaded_vmdk_path) self._session._wait_for_task(instance.id, vmdk_delete_task) - LOG.debug("Deleted the file %s on the ESX host local" - "store %s " % (flat_uploaded_vmdk_path, data_store_name)) + LOG.debug(_("Deleted the file %s on the ESX host local" + "store %s ") % (flat_uploaded_vmdk_path, data_store_name)) - LOG.debug("Downloading image file data %s to the ESX data store %s " % + LOG.debug(_("Downloading image file %s to the ESX data store %s ") % \ (instance.image_id, data_store_name)) # Upload the -flat.vmdk file whose meta-data file we just created above vmware_images.fetch_image( @@ -226,7 +218,7 @@ class VMWareVMOps(object): datastore_name=data_store_name, cookies=self._session._get_vim().proxy.binding.cookies, file_path=flat_uploaded_vmdk_name) - LOG.debug("Downloaded image file data %s to the ESX data store %s " % + LOG.debug(_("Downloaded image file %s to the ESX data store %s ") % \ (instance.image_id, data_store_name)) #Attach the vmdk uploaded to the VM. VM reconfigure is done to do so. @@ -234,21 +226,21 @@ class VMWareVMOps(object): vmdk_file_size_in_kb, uploaded_vmdk_path, adapter_type) vm_ref = self._get_vm_ref_from_the_name(instance.name) - LOG.debug("Reconfiguring VM instance %s to attach the image " - "disk" % instance.name) + LOG.debug(_("Reconfiguring VM instance %s to attach the image " + "disk") % instance.name) reconfig_task = self._session._call_method(self._session._get_vim(), "ReconfigVM_Task", vm_ref, spec=vmdk_attach_config_spec) self._session._wait_for_task(instance.id, reconfig_task) - LOG.debug("Reconfigured VM instance %s to attach the image " - "disk" % instance.name) + LOG.debug(_("Reconfigured VM instance %s to attach the image " + "disk") % instance.name) - LOG.debug("Powering on the VM instance %s " % instance.name) + LOG.debug(_("Powering on the VM instance %s ") % instance.name) #Power On the VM power_on_task = self._session._call_method(self._session._get_vim(), "PowerOnVM_Task", vm_ref) self._session._wait_for_task(instance.id, power_on_task) - LOG.debug("Powered on the VM instance %s " % instance.name) + LOG.debug(_("Powered on the VM instance %s ") % instance.name) def snapshot(self, instance, snapshot_name): """ @@ -266,7 +258,7 @@ class VMWareVMOps(object): """ vm_ref = self._get_vm_ref_from_the_name(instance.name) if vm_ref is None: - raise Exception("instance - %s not present" % instance.name) + raise Exception(_("instance - %s not present") % instance.name) #Get the vmdk file name that the VM is pointing to hardware_devices = self._session._call_method(vim_util, @@ -279,7 +271,7 @@ class VMWareVMOps(object): "get_dynamic_property", vm_ref, "VirtualMachine", "summary.config.guestId") #Create a snapshot of the VM - LOG.debug("Creating Snapshot of the VM instance %s " % instance.name) + 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, @@ -287,7 +279,7 @@ class VMWareVMOps(object): memory=True, quiesce=True) self._session._wait_for_task(instance.id, snapshot_task) - LOG.debug("Created Snapshot of the VM instance %s " % instance.name) + LOG.debug(_("Created Snapshot of the VM instance %s ") % instance.name) datastore_name = vm_util.split_datastore_path( vmdk_file_path_before_snapshot)[0] @@ -320,8 +312,8 @@ class VMWareVMOps(object): #Copy the contents of the disk ( or disks, if there were snapshots #done earlier) to a temporary vmdk file. - LOG.debug("Copying disk data before snapshot of the VM instance %s " % - instance.name) + 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", self._session._get_vim().get_service_content().VirtualDiskManager, @@ -332,11 +324,11 @@ class VMWareVMOps(object): destSpec=copy_spec, force=False) self._session._wait_for_task(instance.id, copy_disk_task) - LOG.debug("Copied disk data before snapshot of the VM instance %s " % - instance.name) + LOG.debug(_("Copied disk data before snapshot of " + "the VM instance %s") % instance.name) #Upload the contents of -flat.vmdk file which has the disk data. - LOG.debug("Uploading image %s" % snapshot_name) + LOG.debug(_("Uploading image %s") % snapshot_name) vmware_images.upload_image( snapshot_name, instance, @@ -348,25 +340,25 @@ class VMWareVMOps(object): datastore_name=datastore_name, cookies=self._session._get_vim().proxy.binding.cookies, file_path="vmware-tmp/%s-flat.vmdk" % random_name) - LOG.debug("Uploaded image %s" % snapshot_name) + LOG.debug(_("Uploaded image %s") % snapshot_name) #Delete the temporary vmdk created above. - LOG.debug("Deleting temporary vmdk file %s" % dest_vmdk_file_location) + LOG.debug(_("Deleting temporary vmdk file %s") % \ + dest_vmdk_file_location) remove_disk_task = self._session._call_method(self._session._get_vim(), "DeleteVirtualDisk_Task", self._session._get_vim().get_service_content().VirtualDiskManager, name=dest_vmdk_file_location, datacenter=dc_ref) self._session._wait_for_task(instance.id, remove_disk_task) - LOG.debug("Deleted temporary vmdk file %s" % dest_vmdk_file_location) + LOG.debug(_("Deleted temporary vmdk file %s") % \ + dest_vmdk_file_location) def reboot(self, instance): - """ - Reboot a VM instance - """ + """Reboot a VM instance""" vm_ref = self._get_vm_ref_from_the_name(instance.name) if vm_ref is None: - raise Exception("instance - %s not present" % instance.name) + raise Exception(_("instance - %s not present") % instance.name) lst_properties = ["summary.guest.toolsStatus", "runtime.powerState"] props = self._session._call_method(vim_util, "get_object_properties", None, vm_ref, "VirtualMachine", @@ -382,22 +374,22 @@ class VMWareVMOps(object): #Raise an exception if the VM is not powered On. if pwr_state not in ["poweredOn"]: - raise Exception("instance - %s not poweredOn. So can't be " - "rebooted." % instance.name) + raise Exception(_("instance - %s not poweredOn. So can't be " + "rebooted.") % instance.name) #If vmware tools are installed in the VM, then do a guest reboot. #Otherwise do a hard reset. if tools_status not in ['toolsNotInstalled', 'toolsNotRunning']: - LOG.debug("Rebooting guest OS of VM %s" % instance.name) + 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) + LOG.debug(_("Rebooted guest OS of VM %s") % instance.name) else: - LOG.debug("Doing hard reboot of VM %s" % instance.name) + 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.id, reset_task) - LOG.debug("Did hard reboot of VM %s" % instance.name) + LOG.debug(_("Did hard reboot of VM %s") % instance.name) def destroy(self, instance): """ @@ -409,7 +401,7 @@ class VMWareVMOps(object): try: vm_ref = self._get_vm_ref_from_the_name(instance.name) if vm_ref is None: - LOG.debug("instance - %s not present" % instance.name) + LOG.debug(_("instance - %s not present") % instance.name) return lst_properties = ["config.files.vmPathName", "runtime.powerState"] props = self._session._call_method(vim_util, @@ -428,61 +420,55 @@ class VMWareVMOps(object): vm_util.split_datastore_path(vm_config_pathname) #Power off the VM if it is in PoweredOn state. if pwr_state == "poweredOn": - LOG.debug("Powering off the VM %s" % instance.name) + LOG.debug(_("Powering off the VM %s") % instance.name) poweroff_task = self._session._call_method( self._session._get_vim(), "PowerOffVM_Task", vm_ref) self._session._wait_for_task(instance.id, poweroff_task) - LOG.debug("Powered off the VM %s" % instance.name) + LOG.debug(_("Powered off the VM %s") % instance.name) #Un-register the VM try: - LOG.debug("Unregistering the VM %s" % instance.name) + LOG.debug(_("Unregistering the VM %s") % instance.name) self._session._call_method(self._session._get_vim(), "UnregisterVM", vm_ref) - LOG.debug("Unregistered the VM %s" % instance.name) + LOG.debug(_("Unregistered the VM %s") % instance.name) except Exception, excep: - LOG.warn("In vmwareapi:vmops:destroy, got this exception while" - " un-registering the VM: " + str(excep)) + LOG.warn(_("In vmwareapi:vmops:destroy, got this exception " + "while un-registering the VM: ") + str(excep)) #Delete the folder holding the VM related content on the datastore. try: dir_ds_compliant_path = vm_util.build_datastore_path( datastore_name, os.path.dirname(vmx_file_path)) - LOG.debug("Deleting contents of the VM %s from datastore %s " % - (instance.name, datastore_name)) + LOG.debug(_("Deleting contents of the VM %s from " + "datastore %s") % (instance.name, datastore_name)) delete_task = self._session._call_method( self._session._get_vim(), "DeleteDatastoreFile_Task", self._session._get_vim().get_service_content().FileManager, name=dir_ds_compliant_path) self._session._wait_for_task(instance.id, delete_task) - LOG.debug("Deleted contents of the VM %s from datastore %s " % - (instance.name, datastore_name)) + LOG.debug(_("Deleted contents of the VM %s from " + "datastore %s") % (instance.name, datastore_name)) except Exception, excep: - LOG.warn("In vmwareapi:vmops:destroy, " + LOG.warn(_("In vmwareapi:vmops:destroy, " "got this exception while deleting" - " the VM contents from the disk: " + str(excep)) + " the VM contents from the disk: ") + str(excep)) except Exception, e: LOG.exception(e) def pause(self, instance, callback): - """ - Pause a VM instance - """ + """Pause a VM instance""" return "Not Implemented" def unpause(self, instance, callback): - """ - Un-Pause a VM instance - """ + """Un-Pause a VM instance""" return "Not Implemented" def suspend(self, instance, callback): - """ - Suspend the specified instance - """ + """Suspend the specified instance""" vm_ref = self._get_vm_ref_from_the_name(instance.name) if vm_ref is None: raise Exception("instance - %s not present" % instance.name) @@ -492,47 +478,43 @@ class VMWareVMOps(object): "VirtualMachine", "runtime.powerState") #Only PoweredOn VMs can be suspended. if pwr_state == "poweredOn": - LOG.debug("Suspending the VM %s " % instance.name) + LOG.debug(_("Suspending the VM %s ") % instance.name) suspend_task = self._session._call_method(self._session._get_vim(), "SuspendVM_Task", vm_ref) self._wait_with_callback(instance.id, suspend_task, callback) - LOG.debug("Suspended the VM %s " % instance.name) + LOG.debug(_("Suspended the VM %s ") % instance.name) #Raise Exception if VM is poweredOff elif pwr_state == "poweredOff": - raise Exception("instance - %s is poweredOff and hence can't " - "be suspended." % instance.name) - LOG.debug("VM %s was already in suspended state. So returning without " - "doing anything" % instance.name) + raise Exception(_("instance - %s is poweredOff and hence can't " + "be suspended.") % instance.name) + LOG.debug(_("VM %s was already in suspended state. So returning " + "without doing anything") % instance.name) def resume(self, instance, callback): - """ - Resume the specified instance - """ + """Resume the specified instance""" vm_ref = self._get_vm_ref_from_the_name(instance.name) if vm_ref is None: - raise Exception("instance - %s not present" % instance.name) + raise Exception(_("instance - %s not present") % instance.name) 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) + LOG.debug(_("Resuming the VM %s ") % instance.name) suspend_task = self._session._call_method( self._session._get_vim(), "PowerOnVM_Task", vm_ref) self._wait_with_callback(instance.id, suspend_task, callback) - LOG.debug("Resumed the VM %s " % instance.name) + LOG.debug(_("Resumed the VM %s ") % instance.name) else: - raise Exception("instance - %s not in Suspended state and hence " - "can't be Resumed." % instance.name) + raise Exception(_("instance - %s not in Suspended state and hence " + "can't be Resumed.") % instance.name) def get_info(self, instance_name): - """ - Return data about the VM instance - """ + """Return data about the VM instance""" vm_ref = self._get_vm_ref_from_the_name(instance_name) if vm_ref is None: - raise Exception("instance - %s not present" % instance_name) + raise Exception(_("instance - %s not present") % instance_name) lst_properties = ["summary.config.numCpu", "summary.config.memorySizeMB", @@ -560,31 +542,25 @@ class VMWareVMOps(object): 'cpu_time': 0} def get_diagnostics(self, instance): - """ - Return data about VM diagnostics - """ + """Return data about VM diagnostics""" return "Not Implemented" def get_console_output(self, instance): - """ - Return snapshot of console - """ + """Return snapshot of console""" return 'FAKE CONSOLE OUTPUT of instance' def get_ajax_console(self, instance): - """ - Return link to instance's ajax console - """ + """Return link to instance's ajax console""" return 'http://fakeajaxconsole/fake_url' def _set_machine_id(self, instance): """ - Set the machine id of the VM for guest tools to pick up and change the - IP + Set the machine id of the VM for guest tools to pick up + and change the IP """ vm_ref = self._get_vm_ref_from_the_name(instance.name) if vm_ref is None: - raise Exception("instance - %s not present" % instance.name) + raise Exception(_("instance - %s not present") % instance.name) network = db.network_get_by_instance(context.get_admin_context(), instance['id']) mac_addr = instance.mac_address @@ -594,23 +570,21 @@ class VMWareVMOps(object): instance['id']) machine_id_chanfge_spec = vm_util.get_machine_id_change_spec(mac_addr, ip_addr, net_mask, gateway) - LOG.debug("Reconfiguring VM instance %s to set the machine id " - "with ip - %s" % (instance.name, ip_addr)) + LOG.debug(_("Reconfiguring VM instance %s to set the machine id " + "with ip - %s") % (instance.name, ip_addr)) reconfig_task = self._session._call_method(self._session._get_vim(), "ReconfigVM_Task", vm_ref, spec=machine_id_chanfge_spec) self._session._wait_for_task(instance.id, reconfig_task) - LOG.debug("Reconfigured VM instance %s to set the machine id " - "with ip - %s" % (instance.name, ip_addr)) + LOG.debug(_("Reconfigured VM instance %s to set the machine id " + "with ip - %s") % (instance.name, ip_addr)) def _create_dummy_vm_for_test(self, instance): - """ - Create a dummy VM for testing purpose - """ + """Create a dummy VM for testing purpose""" vm_ref = self._get_vm_ref_from_the_name(instance.name) if vm_ref: - raise Exception('Attempted to create a VM with a name %s, ' - 'but that already exists on the host' % instance.name) + raise Exception(_('Attempted to create a VM with a name %s, ' + 'but that already exists on the host') % instance.name) data_stores = self._session._call_method(vim_util, "get_objects", "Datastore", ["summary.type", "summary.name"]) @@ -629,7 +603,7 @@ class VMWareVMOps(object): break if data_store_name is None: - msg = "Couldn't get a local Datastore reference" + msg = _("Couldn't get a local Datastore reference") LOG.exception(msg) raise Exception(msg) @@ -659,9 +633,7 @@ class VMWareVMOps(object): self._session._wait_for_task(instance.id, power_on_task) def _get_network_with_the_name(self, network_name="vmnet0"): - ''' - Gets reference to the network whose name is passed as the argument. - ''' + """Gets reference to network whose name is passed as the argument.""" datacenters = self._session._call_method(vim_util, "get_objects", "Datacenter", ["network"]) vm_networks = datacenters[0].PropSet[0].Val.ManagedObjectReference @@ -674,17 +646,13 @@ class VMWareVMOps(object): return None def _get_datacenter_name_and_ref(self): - """ - Get the datacenter name and the reference. - """ + """Get the datacenter name and the reference.""" dc_obj = self._session._call_method(vim_util, "get_objects", "Datacenter", ["name"]) return dc_obj[0].Obj, dc_obj[0].PropSet[0].Val def _path_exists(self, ds_browser, ds_path): - """ - Check if the path exists on the datastore - """ + """Check if the path exists on the datastore.""" search_task = self._session._call_method(self._session._get_vim(), "SearchDatastore_Task", ds_browser, @@ -709,16 +677,14 @@ class VMWareVMOps(object): directory with this name is formed at the topmost level of the DataStore. """ - LOG.debug("Creating directory with path %s" % ds_path) + LOG.debug(_("Creating directory with path %s") % ds_path) self._session._call_method(self._session._get_vim(), "MakeDirectory", self._session._get_vim().get_service_content().FileManager, name=ds_path, createParentDirectories=False) - LOG.debug("Created directory with path %s" % ds_path) + LOG.debug(_("Created directory with path %s") % ds_path) def _get_vm_ref_from_the_name(self, vm_name): - """ - Get reference to the VM with the name specified. - """ + """Get reference to the VM with the name specified.""" vms = self._session._call_method(vim_util, "get_objects", "VirtualMachine", ["name"]) for vm in vms: diff --git a/nova/virt/vmwareapi/vmware_images.py b/nova/virt/vmwareapi/vmware_images.py index d3b1dc446..78bbb7fec 100644 --- a/nova/virt/vmwareapi/vmware_images.py +++ b/nova/virt/vmwareapi/vmware_images.py @@ -39,9 +39,7 @@ TEST_IMAGE_PATH = "/tmp/vmware-test-images" def start_transfer(read_file_handle, write_file_handle, data_size): - """ - Start the data transfer from the read handle to the write handle. - """ + """Start the data transfer from the read handle to the write handle.""" #The thread safe pipe thread_safe_pipe = io_util.ThreadSafePipe(QUEUE_BUFFER_SIZE) #The read thread @@ -52,7 +50,7 @@ def start_transfer(read_file_handle, write_file_handle, data_size): WRITE_CHUNKSIZE, long(data_size)) read_thread.start() write_thread.start() - LOG.debug("Starting image file transfer") + LOG.debug(_("Starting image file transfer")) #Wait till both the read thread and the write thread are done while not (read_thread.is_done() and write_thread.is_done()): if read_thread.get_error() or write_thread.get_error(): @@ -68,16 +66,14 @@ def start_transfer(read_file_handle, write_file_handle, data_size): LOG.exception(str(write_excep)) raise Exception(write_excep) time.sleep(2) - LOG.debug("Finished image file transfer and closing the file handles") + LOG.debug(_("Finished image file transfer and closing the file handles")) #Close the file handles read_file_handle.close() write_file_handle.close() def fetch_image(image, instance, **kwargs): - """ - Fetch an image for attaching to the newly created VM - """ + """Fetch an image for attaching to the newly created VM.""" #Depending upon the image service, make appropriate image service call if FLAGS.image_service == "nova.image.glance.GlanceImageService": func = _get_glance_image @@ -88,15 +84,13 @@ def fetch_image(image, instance, **kwargs): elif FLAGS.image_service == "nova.FakeImageService": func = _get_fake_image else: - raise NotImplementedError("The Image Service %s is not implemented" + raise NotImplementedError(_("The Image Service %s is not implemented") % FLAGS.image_service) return func(image, instance, **kwargs) def upload_image(image, instance, **kwargs): - """ - Upload the newly snapshotted VM disk file. - """ + """Upload the newly snapshotted VM disk file.""" #Depending upon the image service, make appropriate image service call if FLAGS.image_service == "nova.image.glance.GlanceImageService": func = _put_glance_image @@ -107,16 +101,14 @@ def upload_image(image, instance, **kwargs): elif FLAGS.image_service == "nova.FakeImageService": func = _put_fake_image else: - raise NotImplementedError("The Image Service %s is not implemented" + raise NotImplementedError(_("The Image Service %s is not implemented") % FLAGS.image_service) return func(image, instance, **kwargs) def _get_glance_image(image, instance, **kwargs): - """ - Download image from the glance image server. - """ - LOG.debug("Downloading image %s from glance image server" % image) + """Download image from the glance image server.""" + LOG.debug(_("Downloading image %s from glance image server") % image) read_file_handle = read_write_util.GlanceHTTPReadFile(FLAGS.glance_host, FLAGS.glance_port, image) @@ -129,29 +121,24 @@ def _get_glance_image(image, instance, **kwargs): kwargs.get("file_path"), file_size) start_transfer(read_file_handle, write_file_handle, file_size) - LOG.debug("Downloaded image %s from glance image server" % image) + LOG.debug(_("Downloaded image %s from glance image server") % image) def _get_s3_image(image, instance, **kwargs): - """ - Download image from the S3 image server. - """ + """Download image from the S3 image server.""" raise NotImplementedError def _get_local_image(image, instance, **kwargs): - """ - Download image from the local nova compute node. - """ + """Download image from the local nova compute node.""" raise NotImplementedError def _get_fake_image(image, instance, **kwargs): + """ Download a fake image from the nova local file repository for testing + purposes. """ - Download a fake image from the nova local file repository for testing - purposes - """ - LOG.debug("Downloading image %s from fake image service" % image) + LOG.debug(_("Downloading image %s from fake image service") % image) image = str(image) file_path = os.path.join(TEST_IMAGE_PATH, image, image) file_path = os.path.abspath(file_path) @@ -165,14 +152,12 @@ def _get_fake_image(image, instance, **kwargs): kwargs.get("file_path"), file_size) start_transfer(read_file_handle, write_file_handle, file_size) - LOG.debug("Downloaded image %s from fake image service" % image) + LOG.debug(_("Downloaded image %s from fake image service") % image) def _put_glance_image(image, instance, **kwargs): - """ - Upload the snapshotted vm disk file to Glance image server - """ - LOG.debug("Uploading image %s to the Glance image server" % image) + """Upload the snapshotted vm disk file to Glance image server.""" + LOG.debug(_("Uploading image %s to the Glance image server") % image) read_file_handle = read_write_util.VmWareHTTPReadFile( kwargs.get("host"), kwargs.get("data_center_name"), @@ -189,29 +174,24 @@ def _put_glance_image(image, instance, **kwargs): kwargs.get("adapter_type"), kwargs.get("image_version")) start_transfer(read_file_handle, write_file_handle, file_size) - LOG.debug("Uploaded image %s to the Glance image server" % image) + LOG.debug(_("Uploaded image %s to the Glance image server") % image) def _put_local_image(image, instance, **kwargs): - """ - Upload the snapshotted vm disk file to the local nova compute node. - """ + """Upload the snapshotted vm disk file to the local nova compute node.""" raise NotImplementedError def _put_s3_image(image, instance, **kwargs): - """ - Upload the snapshotted vm disk file to S3 image server. - """ + """Upload the snapshotted vm disk file to S3 image server.""" raise NotImplementedError def _put_fake_image(image, instance, **kwargs): + """ Upload a dummy vmdk from the ESX host to the local file repository of + the nova node for testing purposes. """ - Upload a dummy vmdk from the ESX host to the local file repository of - the nova node for testing purposes - """ - LOG.debug("Uploading image %s to the Fake Image Service" % image) + LOG.debug(_("Uploading image %s to the Fake Image Service") % image) read_file_handle = read_write_util.VmWareHTTPReadFile( kwargs.get("host"), kwargs.get("data_center_name"), @@ -231,7 +211,7 @@ def _put_fake_image(image, instance, **kwargs): file_path = os.path.abspath(file_path) write_file_handle = read_write_util.FakeFileWrite(file_path) start_transfer(read_file_handle, write_file_handle, file_size) - LOG.debug("Uploaded image %s to the Fake Image Service" % image) + LOG.debug(_("Uploaded image %s to the Fake Image Service") % image) def get_vmdk_size_and_properties(image, instance): @@ -240,7 +220,7 @@ def get_vmdk_size_and_properties(image, instance): Need this to create the dummy virtual disk for the meta-data file. The geometry of the disk created depends on the size. """ - LOG.debug("Getting image size for the image %s" % image) + LOG.debug(_("Getting image size for the image %s") % image) if FLAGS.image_service == "nova.image.glance.GlanceImageService": read_file_handle = read_write_util.GlanceHTTPReadFile( FLAGS.glance_host, @@ -258,5 +238,5 @@ def get_vmdk_size_and_properties(image, instance): size = read_file_handle.get_size() properties = read_file_handle.get_image_properties() read_file_handle.close() - LOG.debug("Got image size of %s for the image %s" % (size, image)) + LOG.debug(_("Got image size of %s for the image %s") % (size, image)) return size, properties diff --git a/nova/virt/vmwareapi_conn.py b/nova/virt/vmwareapi_conn.py index 421efe91c..739cb53c7 100644 --- a/nova/virt/vmwareapi_conn.py +++ b/nova/virt/vmwareapi_conn.py @@ -76,11 +76,10 @@ TIME_BETWEEN_API_CALL_RETRIES = 2.0 class TaskState: - """ - Enumeration class for different states of task - 0 - Task completed successfully - 1 - Task is in queued state - 2 - Task is in running state + """Enumeration class for different states of task + 0 - Task completed successfully + 1 - Task is in queued state + 2 - Task is in running state """ TASK_SUCCESS = 0 @@ -89,27 +88,19 @@ class TaskState: class Failure(Exception): - """ - Base Exception class for handling task failures - """ + """Base Exception class for handling task failures""" def __init__(self, details): - """ - Initializer - """ + """Initializer""" self.details = details def __str__(self): - """ - The informal string representation of the object - """ + """The informal string representation of the object""" return str(self.details) def get_connection(_): - """ - Sets up the ESX host connection - """ + """Sets up the ESX host connection""" host_ip = FLAGS.vmwareapi_host_ip host_username = FLAGS.vmwareapi_host_username host_password = FLAGS.vmwareapi_host_password @@ -124,143 +115,98 @@ def get_connection(_): class VMWareESXConnection(object): - """ - The ESX host connection object - """ + """The ESX host connection object""" def __init__(self, host_ip, host_username, host_password, api_retry_count, scheme="https"): - """ - The Initializer - """ + """The Initializer""" session = VMWareAPISession(host_ip, host_username, host_password, api_retry_count, scheme=scheme) self._vmops = VMWareVMOps(session) def init_host(self, host): - """ - Do the initialization that needs to be done - """ + """Do the initialization that needs to be done""" #FIXME(sateesh): implement this pass def list_instances(self): - """ - List VM instances - """ + """List VM instances""" return self._vmops.list_instances() def spawn(self, instance): - """ - Create VM instance - """ + """Create VM instance""" self._vmops.spawn(instance) def snapshot(self, instance, name): - """ - Create snapshot from a running VM instance - """ + """Create snapshot from a running VM instance""" self._vmops.snapshot(instance, name) def reboot(self, instance): - """ - Reboot VM instance - """ + """Reboot VM instance""" self._vmops.reboot(instance) def destroy(self, instance): - """ - Destroy VM instance - """ + """Destroy VM instance""" self._vmops.destroy(instance) def pause(self, instance, callback): - """ - Pause VM instance - """ + """Pause VM instance""" self._vmops.pause(instance, callback) def unpause(self, instance, callback): - """ - Unpause paused VM instance - """ + """Unpause paused VM instance""" self._vmops.unpause(instance, callback) def suspend(self, instance, callback): - """ - Suspend the specified instance - """ + """Suspend the specified instance""" self._vmops.suspend(instance, callback) def resume(self, instance, callback): - """ - Resume the suspended VM instance - """ + """Resume the suspended VM instance""" self._vmops.resume(instance, callback) def get_info(self, instance_id): - """ - Return info about the VM instance - """ + """Return info about the VM instance""" return self._vmops.get_info(instance_id) def get_diagnostics(self, instance): - """ - Return data about VM diagnostics - """ + """Return data about VM diagnostics""" return self._vmops.get_info(instance) def get_console_output(self, instance): - """ - Return snapshot of console - """ + """Return snapshot of console""" return self._vmops.get_console_output(instance) def get_ajax_console(self, instance): - """ - Return link to instance's ajax console - """ + """Return link to instance's ajax console""" return self._vmops.get_ajax_console(instance) def attach_volume(self, instance_name, device_path, mountpoint): - """ - Attach volume storage to VM instance - """ + """Attach volume storage to VM instance""" pass def detach_volume(self, instance_name, mountpoint): - """ - Detach volume storage to VM instance - """ + """Detach volume storage to VM instance""" pass def get_console_pool_info(self, console_type): - """ - Get info about the host on which the VM resides - """ + """Get info about the host on which the VM resides""" esx_url = urlparse.urlparse(FLAGS.vmwareapi_host_ip) return {'address': esx_url.netloc, 'username': FLAGS.vmwareapi_host_password, 'password': FLAGS.vmwareapi_host_password} def _create_dummy_vm_for_test(self, instance): - """ - Creates a dummy 1MB VM with default parameters for testing purpose - """ + """Creates a dummy VM with default parameters for testing purpose""" return self._vmops._create_dummy_vm_for_test(instance) class VMWareAPISession(object): - """ - Sets up a session with the ESX host and handles all the calls made to the - host - """ + """Sets up a session with ESX host and handles all calls made to host""" def __init__(self, host_ip, host_username, host_password, api_retry_count, scheme="https"): - """ - Set the connection credentials - """ + """Set the connection credentials""" self._host_ip = host_ip self._host_username = host_username self._host_password = host_password @@ -271,9 +217,7 @@ class VMWareAPISession(object): self._create_session() def _create_session(self): - """ - Creates a session with the ESX host - """ + """Creates a session with the ESX host""" while True: try: # Login and setup the session with the ESX host for making @@ -296,14 +240,12 @@ class VMWareAPISession(object): self._session_id = session.Key return except Exception, excep: - LOG.critical("In vmwareapi:_create_session, " - "got this exception: %s" % excep) + LOG.info(_("In vmwareapi:_create_session, " + "got this exception: %s") % excep) raise Exception(excep) def __del__(self): - """ - The Destructor. Logs-out the session. - """ + """The Destructor. Logs-out the session.""" # Logout to avoid un-necessary increase in session count at the # ESX host try: @@ -312,9 +254,7 @@ class VMWareAPISession(object): pass def _call_method(self, module, method, *args, **kwargs): - """ - Calls a method within the module specified with args provided - """ + """Calls a method within the module specified with args provided""" args = list(args) retry_count = 0 exc = None @@ -355,14 +295,12 @@ class VMWareAPISession(object): break time.sleep(TIME_BETWEEN_API_CALL_RETRIES) - LOG.critical("In vmwareapi:_call_method, " - "got this exception: " % exc) + LOG.info(_("In vmwareapi:_call_method, " + "got this exception: ") % exc) raise Exception(exc) def _get_vim(self): - """ - Gets the VIM object reference - """ + """Gets the VIM object reference""" if self.vim is None: self._create_session() return self.vim @@ -397,19 +335,19 @@ class VMWareAPISession(object): TaskState.TASK_RUNNING]: return elif task_info.State == TaskState.TASK_SUCCESS: - LOG.info("Task [%s] %s status: success " % ( + LOG.info(_("Task [%s] %s status: success ") % ( task_name, str(task_ref))) done.send(TaskState.TASK_SUCCESS) else: error_info = str(task_info.Error.LocalizedMessage) action["error"] = error_info - LOG.warn("Task [%s] %s status: error [%s]" % ( + LOG.info(_("Task [%s] %s status: error [%s]") % ( task_name, str(task_ref), error_info)) done.send_exception(Exception(error_info)) db.instance_action_create(context.get_admin_context(), action) except Exception, excep: - LOG.warn("In vmwareapi:_poll_task, Got this error %s" % excep) + LOG.info(_("In vmwareapi:_poll_task, Got this error %s") % excep) done.send_exception(excep) -- cgit