sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1 value |
|---|---|---|
def vm_reconfig_task(vm, device_change):
"""
Create Task for VM re-configure
:param vm: <vim.vm obj> VM which will be re-configure
:param device_change:
:return: Task
"""
config_spec = vim.vm.ConfigSpec(deviceChange=device_change)
task = vm.ReconfigVM_Task(config_spec)
return task | Create Task for VM re-configure
:param vm: <vim.vm obj> VM which will be re-configure
:param device_change:
:return: Task | entailment |
def vm_get_network_by_name(vm, network_name):
"""
Try to find Network scanning all attached to VM networks
:param vm: <vim.vm>
:param network_name: <str> name of network
:return: <vim.vm.Network or None>
"""
# return None
for network in vm.network:
if hasattr(network, "name") and network_name == network.name:
return network
return None | Try to find Network scanning all attached to VM networks
:param vm: <vim.vm>
:param network_name: <str> name of network
:return: <vim.vm.Network or None> | entailment |
def get_vm_full_path(self, si, vm):
"""
:param vm: vim.VirtualMachine
:return:
"""
folder_name = None
folder = vm.parent
if folder:
folder_name = folder.name
folder_parent = folder.parent
while folder_parent and folder_parent.name and folder_parent != si.content.rootFolder and not isinstance(folder_parent, vim.Datacenter):
folder_name = folder_parent.name + '/' + folder_name
try:
folder_parent = folder_parent.parent
except Exception:
break
# at this stage we receive a path like this: vm/FOLDER1/FOLDER2;
# we're not interested in the "vm" part, so we throw that away
folder_name = '/'.join(folder_name.split('/')[1:])
# ok, now we're adding the vm name; btw, if there is no folder, that's cool, just return vm.name
return VMLocation.combine([folder_name, vm.name]) if folder_name else vm.name | :param vm: vim.VirtualMachine
:return: | entailment |
def load_vm_uuid_by_name(self, si, vcenter_data_model, vm_name):
"""
Returns the vm uuid
:param si: Service instance to the vcenter
:param vcenter_data_model: vcenter data model
:param vm_name: the vm name
:return: str uuid
"""
path = VMLocation.combine([vcenter_data_model.default_datacenter, vm_name])
paths = path.split('/')
name = paths[len(paths) - 1]
path = VMLocation.combine(paths[:len(paths) - 1])
vm = self.pv_service.find_vm_by_name(si, path, name)
if not vm:
raise ValueError('Could not find the vm in the given path: {0}/{1}'.format(path, name))
if isinstance(vm, vim.VirtualMachine):
return vm.config.uuid
raise ValueError('The given object is not a vm: {0}/{1}'.format(path, name)) | Returns the vm uuid
:param si: Service instance to the vcenter
:param vcenter_data_model: vcenter data model
:param vm_name: the vm name
:return: str uuid | entailment |
def power_off(self, si, logger, session, vcenter_data_model, vm_uuid, resource_fullname):
"""
Power off of a vm
:param vcenter_data_model: vcenter model
:param si: Service Instance
:param logger:
:param session:
:param vcenter_data_model: vcenter_data_model
:param vm_uuid: the uuid of the vm
:param resource_fullname: the full name of the deployed app resource
:return:
"""
logger.info('retrieving vm by uuid: {0}'.format(vm_uuid))
vm = self.pv_service.find_by_uuid(si, vm_uuid)
if vm.summary.runtime.powerState == 'poweredOff':
logger.info('vm already powered off')
task_result = 'Already powered off'
else:
# hard power off
logger.info('{0} powering of vm'.format(vcenter_data_model.shutdown_method))
if vcenter_data_model.shutdown_method.lower() != 'soft':
task = vm.PowerOff()
task_result = self.synchronous_task_waiter.wait_for_task(task=task,
logger=logger,
action_name='Power Off')
else:
if vm.guest.toolsStatus == 'toolsNotInstalled':
logger.warning('VMWare Tools status on virtual machine \'{0}\' are not installed'.format(vm.name))
raise ValueError('Cannot power off the vm softly because VMWare Tools are not installed')
if vm.guest.toolsStatus == 'toolsNotRunning':
logger.warning('VMWare Tools status on virtual machine \'{0}\' are not running'.format(vm.name))
raise ValueError('Cannot power off the vm softly because VMWare Tools are not running')
vm.ShutdownGuest()
task_result = 'vm powered off'
return task_result | Power off of a vm
:param vcenter_data_model: vcenter model
:param si: Service Instance
:param logger:
:param session:
:param vcenter_data_model: vcenter_data_model
:param vm_uuid: the uuid of the vm
:param resource_fullname: the full name of the deployed app resource
:return: | entailment |
def power_on(self, si, logger, session, vm_uuid, resource_fullname):
"""
power on the specified vm
:param si:
:param logger:
:param session:
:param vm_uuid: the uuid of the vm
:param resource_fullname: the full name of the deployed app resource
:return:
"""
logger.info('retrieving vm by uuid: {0}'.format(vm_uuid))
vm = self.pv_service.find_by_uuid(si, vm_uuid)
if vm.summary.runtime.powerState == 'poweredOn':
logger.info('vm already powered on')
task_result = 'Already powered on'
else:
logger.info('powering on vm')
task = vm.PowerOn()
task_result = self.synchronous_task_waiter.wait_for_task(task=task,
logger=logger,
action_name='Power On')
return task_result | power on the specified vm
:param si:
:param logger:
:param session:
:param vm_uuid: the uuid of the vm
:param resource_fullname: the full name of the deployed app resource
:return: | entailment |
def create_logger_for_context(self, logger_name, context):
"""
Create QS Logger for command context AutoLoadCommandContext or ResourceCommandContext
:param logger_name:
:type logger_name: str
:param context:
:return:
"""
if self._is_instance_of(context, 'AutoLoadCommandContext'):
reservation_id = 'Autoload'
handler_name = context.resource.name
elif self._is_instance_of(context, 'UnreservedResourceCommandContext'):
reservation_id = 'DeleteArtifacts'
handler_name = context.resource.name
else:
reservation_id = self._get_reservation_id(context)
if self._is_instance_of(context, 'ResourceCommandContext'):
handler_name = context.resource.name
elif self._is_instance_of(context, 'ResourceRemoteCommandContext'):
handler_name = context.remote_endpoints[0].name
else:
raise Exception(ContextBasedLoggerFactory.UNSUPPORTED_CONTEXT_PROVIDED, context)
logger = get_qs_logger(log_file_prefix=handler_name,
log_group=reservation_id,
log_category=logger_name)
return logger | Create QS Logger for command context AutoLoadCommandContext or ResourceCommandContext
:param logger_name:
:type logger_name: str
:param context:
:return: | entailment |
def connect_to_networks(self, si, logger, vm_uuid, vm_network_mappings, default_network_name,
reserved_networks, dv_switch_name, promiscuous_mode):
"""
Connect VM to Network
:param si: VmWare Service Instance - defined connection to vCenter
:param logger:
:param vm_uuid: <str> UUID for VM
:param vm_network_mappings: <collection of 'VmNetworkMapping'>
:param default_network_name: <str> Full Network name - likes 'DataCenterName/NetworkName'
:param reserved_networks:
:param dv_switch_name: <str> Default dvSwitch name
:param promiscuous_mode <str> 'True' or 'False' turn on/off promiscuous mode for the port group
:return: None
"""
vm = self.pv_service.find_by_uuid(si, vm_uuid)
if not vm:
raise ValueError('VM having UUID {0} not found'.format(vm_uuid))
default_network_instance = self.pv_service.get_network_by_full_name(si, default_network_name)
if not default_network_instance:
raise ValueError('Default Network {0} not found'.format(default_network_name))
if vm_has_no_vnics(vm):
raise ValueError('Trying to connect VM (uuid: {0}) but it has no vNics'.format(vm_uuid))
mappings = self._prepare_mappings(dv_switch_name=dv_switch_name, vm_network_mappings=vm_network_mappings)
updated_mappings = self.virtual_switch_to_machine_connector.connect_by_mapping(
si, vm, mappings, default_network_instance, reserved_networks, logger, promiscuous_mode)
connection_results = []
for updated_mapping in updated_mappings:
connection_result = ConnectionResult(mac_address=updated_mapping.vnic.macAddress,
vnic_name=updated_mapping.vnic.deviceInfo.label,
requested_vnic=updated_mapping.requested_vnic,
vm_uuid=vm_uuid,
network_name=updated_mapping.network.name,
network_key=updated_mapping.network.key)
connection_results.append(connection_result)
return connection_results | Connect VM to Network
:param si: VmWare Service Instance - defined connection to vCenter
:param logger:
:param vm_uuid: <str> UUID for VM
:param vm_network_mappings: <collection of 'VmNetworkMapping'>
:param default_network_name: <str> Full Network name - likes 'DataCenterName/NetworkName'
:param reserved_networks:
:param dv_switch_name: <str> Default dvSwitch name
:param promiscuous_mode <str> 'True' or 'False' turn on/off promiscuous mode for the port group
:return: None | entailment |
def map_request_to_vnics(self, requests, vnics, existing_network, default_network, reserved_networks):
"""
gets the requests for connecting netwoks and maps it the suitable vnic of specific is not specified
:param reserved_networks: array of reserved networks
:param requests:
:param vnics:
:param existing_network:
:param default_network:
:return:
"""
mapping = dict()
reserved_networks = reserved_networks if reserved_networks else []
vnics_to_network_mapping = self._map_vnic_to_network(vnics, existing_network, default_network, reserved_networks)
for request in requests:
if request.vnic_name:
if request.vnic_name not in vnics_to_network_mapping:
raise ValueError('No vNIC by that name "{0}" exist'.format(request.vnic_name))
net_at_requsted_vnic = vnics_to_network_mapping[request.vnic_name]
if self.quali_name_generator.is_generated_name(net_at_requsted_vnic):
raise ValueError('The vNIC: "{0}" is already set with: "{1}"'.format(request.vnic_name,
net_at_requsted_vnic))
mapping[request.vnic_name] = (request.network, request.vnic_name)
vnics_to_network_mapping.pop(request.vnic_name)
else:
vnic_name = self._find_available_vnic(vnics_to_network_mapping, default_network)
mapping[vnic_name] = (request.network, request.vnic_name)
vnics_to_network_mapping.pop(vnic_name)
return mapping | gets the requests for connecting netwoks and maps it the suitable vnic of specific is not specified
:param reserved_networks: array of reserved networks
:param requests:
:param vnics:
:param existing_network:
:param default_network:
:return: | entailment |
def deploy_image(self, vcenter_data_model, image_params, logger):
"""
Receives ovf image parameters and deploy it on the designated vcenter
:param VMwarevCenterResourceModel vcenter_data_model:
:type image_params: vCenterShell.vm.ovf_image_params.OvfImageParams
:param logger:
"""
ovf_tool_exe_path = vcenter_data_model.ovf_tool_path
self._validate_url_exists(ovf_tool_exe_path, 'OVF Tool', logger)
args = self._get_args(ovf_tool_exe_path, image_params, logger)
logger.debug('opening ovf tool process with the params: {0}'.format(','.join(args)))
process = subprocess.Popen(args, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
logger.debug('communicating with ovf tool')
result = process.communicate()
process.stdin.close()
if result:
res = '\n\r'.join(result)
else:
if image_params.user_arguments.find('--quiet') == -1:
raise Exception('no result has return from the ovftool')
res = COMPLETED_SUCCESSFULLY
logger.info('communication with ovf tool results: {0}'.format(res))
if res.find(COMPLETED_SUCCESSFULLY) > -1:
return True
image_params.connectivity.password = '******'
args_for_error = ' '.join(self._get_args(ovf_tool_exe_path, image_params, logger))
logger.error('error deploying image with the args: {0}, error: {1}'.format(args_for_error, res))
raise Exception('error deploying image with the args: {0}, error: {1}'.format(args_for_error, res)) | Receives ovf image parameters and deploy it on the designated vcenter
:param VMwarevCenterResourceModel vcenter_data_model:
:type image_params: vCenterShell.vm.ovf_image_params.OvfImageParams
:param logger: | entailment |
def _get_args(self, ovf_tool_exe_path, image_params, logger):
"""
:type image_params: vCenterShell.vm.ovf_image_params.OvfImageParams
"""
# create vm name
vm_name_param = VM_NAME_PARAM.format(image_params.vm_name)
# datastore name
datastore_param = DATA_STORE_PARAM.format(image_params.datastore)
# power state
# power_state = POWER_ON_PARAM if image_params.power_on else POWER_OFF_PARAM
# due to hotfix 1 for release 1.0,
# after deployment the vm must be powered off and will be powered on if needed by orchestration driver
power_state = POWER_OFF_PARAM
# build basic args
args = [ovf_tool_exe_path,
NO_SSL_PARAM,
ACCEPT_ALL_PARAM,
power_state,
vm_name_param,
datastore_param]
# append user folder
if hasattr(image_params, 'vm_folder') and image_params.vm_folder:
vm_folder_str = VM_FOLDER_PARAM.format(image_params.vm_folder)
args.append(vm_folder_str)
# append args that are user inputs
if hasattr(image_params, 'user_arguments') and image_params.user_arguments:
args += [key.strip()
for key in image_params.user_arguments.split(',')]
# get ovf destination
ovf_destination = self._get_ovf_destenation(image_params)
image_url = image_params.image_url
self._validate_image_exists(image_url, logger)
# set location and destination
args += [image_url,
ovf_destination]
return args | :type image_params: vCenterShell.vm.ovf_image_params.OvfImageParams | entailment |
def execute_command_with_connection(self, context, command, *args):
"""
Note: session & vcenter_data_model & reservation id objects will be injected dynamically to the command
:param command:
:param context: instance of ResourceCommandContext or AutoLoadCommandContext
:type context: cloudshell.shell.core.context.ResourceCommandContext
:param args:
"""
logger = self.context_based_logger_factory.create_logger_for_context(
logger_name='vCenterShell',
context=context)
if not command:
logger.error(COMMAND_CANNOT_BE_NONE)
raise Exception(COMMAND_CANNOT_BE_NONE)
try:
command_name = command.__name__
logger.info(LOG_FORMAT.format(START, command_name))
command_args = []
si = None
session = None
connection_details = None
vcenter_data_model = None
# get connection details
if context:
with CloudShellSessionContext(context) as cloudshell_session:
session = cloudshell_session
vcenter_data_model = self.resource_model_parser.convert_to_vcenter_model(context.resource)
connection_details = ResourceConnectionDetailsRetriever.get_connection_details(session=session,
vcenter_resource_model=vcenter_data_model,
resource_context=context.resource)
if connection_details:
logger.info(INFO_CONNECTING_TO_VCENTER.format(connection_details.host))
logger.debug(
DEBUG_CONNECTION_INFO.format(connection_details.host,
connection_details.username,
connection_details.port))
si = self.get_py_service_connection(connection_details, logger)
if si:
logger.info(CONNECTED_TO_CENTER.format(connection_details.host))
command_args.append(si)
self._try_inject_arg(command=command,
command_args=command_args,
arg_object=session,
arg_name='session')
self._try_inject_arg(command=command,
command_args=command_args,
arg_object=vcenter_data_model,
arg_name='vcenter_data_model')
self._try_inject_arg(command=command,
command_args=command_args,
arg_object=self._get_reservation_id(context),
arg_name='reservation_id')
self._try_inject_arg(command=command,
command_args=command_args,
arg_object=logger,
arg_name='logger')
command_args.extend(args)
logger.info(EXECUTING_COMMAND.format(command_name))
logger.debug(DEBUG_COMMAND_PARAMS.format(COMMA.join([str(x) for x in command_args])))
results = command(*tuple(command_args))
logger.info(FINISHED_EXECUTING_COMMAND.format(command_name))
logger.debug(DEBUG_COMMAND_RESULT.format(str(results)))
return results
except Exception as ex:
logger.exception(COMMAND_ERROR.format(command_name))
logger.exception(str(type(ex)) + ': ' + str(ex))
raise
finally:
logger.info(LOG_FORMAT.format(END, command_name)) | Note: session & vcenter_data_model & reservation id objects will be injected dynamically to the command
:param command:
:param context: instance of ResourceCommandContext or AutoLoadCommandContext
:type context: cloudshell.shell.core.context.ResourceCommandContext
:param args: | entailment |
def has_connection_details_changed(self, req_connection_details):
"""
:param cloudshell.cp.vcenter.models.VCenterConnectionDetails.VCenterConnectionDetails req_connection_details:
:return:
"""
if self.connection_details is None and req_connection_details is None:
return False
if self.connection_details is None or req_connection_details is None:
return True
return not all([self.connection_details.host == req_connection_details.host,
self.connection_details.username == req_connection_details.username,
self.connection_details.password == req_connection_details.password,
self.connection_details.port == req_connection_details.port]) | :param cloudshell.cp.vcenter.models.VCenterConnectionDetails.VCenterConnectionDetails req_connection_details:
:return: | entailment |
def restore_snapshot(self, si, logger, session, vm_uuid, resource_fullname, snapshot_name):
"""
Restores a virtual machine to a snapshot
:param vim.ServiceInstance si: py_vmomi service instance
:param logger: Logger
:param session: CloudShellAPISession
:type session: cloudshell_api.CloudShellAPISession
:param vm_uuid: uuid of the virtual machine
:param resource_fullname:
:type: resource_fullname: str
:param str snapshot_name: Snapshot name to save the snapshot to
"""
vm = self.pyvmomi_service.find_by_uuid(si, vm_uuid)
logger.info("Revert snapshot")
snapshot = SnapshotRestoreCommand._get_snapshot(vm=vm, snapshot_name=snapshot_name)
session.SetResourceLiveStatus(resource_fullname, "Offline", "Powered Off")
task = snapshot.RevertToSnapshot_Task()
return self.task_waiter.wait_for_task(task=task, logger=logger, action_name='Revert Snapshot') | Restores a virtual machine to a snapshot
:param vim.ServiceInstance si: py_vmomi service instance
:param logger: Logger
:param session: CloudShellAPISession
:type session: cloudshell_api.CloudShellAPISession
:param vm_uuid: uuid of the virtual machine
:param resource_fullname:
:type: resource_fullname: str
:param str snapshot_name: Snapshot name to save the snapshot to | entailment |
def _get_snapshot(vm, snapshot_name):
"""
Returns snapshot object by its name
:param vm:
:param snapshot_name:
:type snapshot_name: str
:return: Snapshot by its name
:rtype vim.vm.Snapshot
"""
snapshots = SnapshotRetriever.get_vm_snapshots(vm)
if snapshot_name not in snapshots:
raise SnapshotNotFoundException('Snapshot {0} was not found'.format(snapshot_name))
return snapshots[snapshot_name] | Returns snapshot object by its name
:param vm:
:param snapshot_name:
:type snapshot_name: str
:return: Snapshot by its name
:rtype vim.vm.Snapshot | entailment |
def save_app(self, si, logger, vcenter_data_model, reservation_id, save_app_actions, cancellation_context):
"""
Cretaes an artifact of an app, that can later be restored
:param vcenter_data_model: VMwarevCenterResourceModel
:param vim.ServiceInstance si: py_vmomi service instance
:type si: vim.ServiceInstance
:param logger: Logger
:type logger: cloudshell.core.logger.qs_logger.get_qs_logger
:param list[SaveApp] save_app_actions:
:param cancellation_context:
"""
results = []
logger.info('Save Sandbox command starting on ' + vcenter_data_model.default_datacenter)
if not save_app_actions:
raise Exception('Failed to save app, missing data in request.')
actions_grouped_by_save_types = groupby(save_app_actions, lambda x: x.actionParams.saveDeploymentModel)
# artifactSaver or artifactHandler are different ways to save artifacts. For example, currently
# we clone a vm, thenk take a snapshot. restore will be to deploy from linked snapshot
# a future artifact handler we might develop is save vm to OVF file and restore from file.
artifactSaversToActions = {ArtifactHandler.factory(k,
self.pyvmomi_service,
vcenter_data_model,
si,
logger,
self.deployer,
reservation_id,
self.resource_model_parser,
self.snapshot_saver,
self.task_waiter,
self.folder_manager,
self.port_group_configurer,
self.cs)
: list(g)
for k, g in actions_grouped_by_save_types}
self.validate_requested_save_types_supported(artifactSaversToActions,
logger,
results)
error_results = [r for r in results if not r.success]
if not error_results:
logger.info('Handling Save App requests')
results = self._execute_save_actions_using_pool(artifactSaversToActions,
cancellation_context,
logger,
results)
logger.info('Completed Save Sandbox command')
else:
logger.error('Some save app requests were not valid, Save Sandbox command failed.')
return results | Cretaes an artifact of an app, that can later be restored
:param vcenter_data_model: VMwarevCenterResourceModel
:param vim.ServiceInstance si: py_vmomi service instance
:type si: vim.ServiceInstance
:param logger: Logger
:type logger: cloudshell.core.logger.qs_logger.get_qs_logger
:param list[SaveApp] save_app_actions:
:param cancellation_context: | entailment |
def formula_1980(household, period, parameters):
'''
To compute this allowance, the 'rent' value must be provided for the same month, but 'housing_occupancy_status' is not necessary.
'''
return household('rent', period) * parameters(period).benefits.housing_allowance | To compute this allowance, the 'rent' value must be provided for the same month, but 'housing_occupancy_status' is not necessary. | entailment |
def formula(person, period, parameters):
'''
A person's pension depends on their birth date.
In French: retraite selon l'âge.
In Arabic: تقاعد.
'''
age_condition = person('age', period) >= parameters(period).general.age_of_retirement
return age_condition | A person's pension depends on their birth date.
In French: retraite selon l'âge.
In Arabic: تقاعد. | entailment |
def set_command_result(result, unpicklable=False):
"""
Serializes output as JSON and writes it to console output wrapped with special prefix and suffix
:param result: Result to return
:param unpicklable: If True adds JSON can be deserialized as real object.
When False will be deserialized as dictionary
"""
# we do not need to serialize an empty response from the vCenter
if result is None:
return
if isinstance(result, basestring):
return result
json = jsonpickle.encode(result, unpicklable=unpicklable)
result_for_output = str(json)
return result_for_output | Serializes output as JSON and writes it to console output wrapped with special prefix and suffix
:param result: Result to return
:param unpicklable: If True adds JSON can be deserialized as real object.
When False will be deserialized as dictionary | entailment |
def validate_and_discover(self, context):
"""
:type context: models.QualiDriverModels.AutoLoadCommandContext
"""
logger = self._get_logger(context)
logger.info('Autodiscovery started')
si = None
resource = None
with CloudShellSessionContext(context) as cloudshell_session:
self._check_if_attribute_not_empty(context.resource, ADDRESS)
resource = context.resource
si = self._check_if_vcenter_user_pass_valid(context, cloudshell_session, resource.attributes)
resource.attributes = VCenterAutoModelDiscovery._make_attributes_slash_backslash_agnostic(resource.attributes)
auto_attr = []
if not si:
error_message = 'Could not connect to the vCenter: {0}, with given credentials'\
.format(context.resource.address)
logger.error(error_message)
raise ValueError(error_message)
try:
all_dc = self.pv_service.get_all_items_in_vcenter(si, vim.Datacenter)
dc = self._validate_datacenter(si, all_dc, auto_attr, resource.attributes)
all_items_in_dc = self.pv_service.get_all_items_in_vcenter(si, None, dc)
dc_name = dc.name
for key, value in resource.attributes.items():
if key in [USER, PASSWORD, DEFAULT_DATACENTER, VM_CLUSTER]:
continue
validation_method = self._get_validation_method(key)
validation_method(si, all_items_in_dc, auto_attr, dc_name, resource.attributes, key)
except vim.fault.NoPermission:
logger.exception('Autodiscovery failed due to permissions error:')
raise Exception("vCenter permissions for configured resource(s) are invalid")
logger.info('Autodiscovery completed')
return AutoLoadDetails([], auto_attr) | :type context: models.QualiDriverModels.AutoLoadCommandContext | entailment |
def _make_attributes_slash_backslash_agnostic(attributes_with_slash_or_backslash):
"""
:param attributes_with_slash_or_backslash: resource attributes from
cloudshell.cp.vcenter.models.QualiDriverModels.ResourceContextDetails
:type attributes_with_slash_or_backslash: dict[str,str]
:return: attributes_with_slash
:rtype attributes_with_slash: dict[str,str]
"""
attributes_with_slash = dict()
for key, value in attributes_with_slash_or_backslash.items():
if key in ATTRIBUTE_NAMES_THAT_ARE_SLASH_BACKSLASH_AGNOSTIC:
value = back_slash_to_front_converter(value)
attributes_with_slash[key] = value
return attributes_with_slash | :param attributes_with_slash_or_backslash: resource attributes from
cloudshell.cp.vcenter.models.QualiDriverModels.ResourceContextDetails
:type attributes_with_slash_or_backslash: dict[str,str]
:return: attributes_with_slash
:rtype attributes_with_slash: dict[str,str] | entailment |
def save_sandbox(self, context, save_actions, cancellation_context):
"""
Save sandbox command, persists an artifact of existing VMs, from which new vms can be restored
:param ResourceCommandContext context:
:param list[SaveApp] save_actions:
:param CancellationContext cancellation_context:
:return: list[SaveAppResult] save_app_results
"""
connection = self.command_wrapper.execute_command_with_connection(context, self.save_app_command.save_app,
save_actions, cancellation_context, )
save_app_results = connection
return save_app_results | Save sandbox command, persists an artifact of existing VMs, from which new vms can be restored
:param ResourceCommandContext context:
:param list[SaveApp] save_actions:
:param CancellationContext cancellation_context:
:return: list[SaveAppResult] save_app_results | entailment |
def delete_saved_sandbox(self, context, delete_saved_apps, cancellation_context):
"""
Delete a saved sandbox, along with any vms associated with it
:param ResourceCommandContext context:
:param list[DeleteSavedApp] delete_saved_apps:
:param CancellationContext cancellation_context:
:return: list[SaveAppResult] save_app_results
"""
connection = self.command_wrapper.execute_command_with_connection(context,
self.delete_saved_sandbox_command.delete_sandbox,
delete_saved_apps, cancellation_context)
delete_saved_apps_results = connection
return delete_saved_apps_results | Delete a saved sandbox, along with any vms associated with it
:param ResourceCommandContext context:
:param list[DeleteSavedApp] delete_saved_apps:
:param CancellationContext cancellation_context:
:return: list[SaveAppResult] save_app_results | entailment |
def deploy_from_template(self, context, deploy_action, cancellation_context):
"""
Deploy From Template Command, will deploy vm from template
:param CancellationContext cancellation_context:
:param ResourceCommandContext context: the context of the command
:param DeployApp deploy_action:
:return DeployAppResult deploy results
"""
deploy_from_template_model = self.resource_model_parser.convert_to_resource_model(
attributes=deploy_action.actionParams.deployment.attributes,
resource_model_type=vCenterVMFromTemplateResourceModel)
data_holder = DeployFromTemplateDetails(deploy_from_template_model, deploy_action.actionParams.appName)
deploy_result_action = self.command_wrapper.execute_command_with_connection(
context,
self.deploy_command.execute_deploy_from_template,
data_holder,
cancellation_context,
self.folder_manager)
deploy_result_action.actionId = deploy_action.actionId
return deploy_result_action | Deploy From Template Command, will deploy vm from template
:param CancellationContext cancellation_context:
:param ResourceCommandContext context: the context of the command
:param DeployApp deploy_action:
:return DeployAppResult deploy results | entailment |
def deploy_clone_from_vm(self, context, deploy_action, cancellation_context):
"""
Deploy Cloned VM From VM Command, will deploy vm from template
:param CancellationContext cancellation_context:
:param ResourceCommandContext context: the context of the command
:param DeployApp deploy_action:
:return DeployAppResult deploy results
"""
deploy_from_vm_model = self.resource_model_parser.convert_to_resource_model(
attributes=deploy_action.actionParams.deployment.attributes,
resource_model_type=vCenterCloneVMFromVMResourceModel)
data_holder = DeployFromTemplateDetails(deploy_from_vm_model, deploy_action.actionParams.appName)
deploy_result_action = self.command_wrapper.execute_command_with_connection(
context,
self.deploy_command.execute_deploy_clone_from_vm,
data_holder,
cancellation_context,
self.folder_manager)
deploy_result_action.actionId = deploy_action.actionId
return deploy_result_action | Deploy Cloned VM From VM Command, will deploy vm from template
:param CancellationContext cancellation_context:
:param ResourceCommandContext context: the context of the command
:param DeployApp deploy_action:
:return DeployAppResult deploy results | entailment |
def deploy_from_linked_clone(self, context, deploy_action, cancellation_context):
"""
Deploy Cloned VM From VM Command, will deploy vm from template
:param CancellationContext cancellation_context:
:param ResourceCommandContext context: the context of the command
:param DeployApp deploy_action:
:return DeployAppResult deploy results
"""
linked_clone_from_vm_model = self.resource_model_parser.convert_to_resource_model(
attributes=deploy_action.actionParams.deployment.attributes,
resource_model_type=VCenterDeployVMFromLinkedCloneResourceModel)
data_holder = DeployFromTemplateDetails(linked_clone_from_vm_model, deploy_action.actionParams.appName)
if not linked_clone_from_vm_model.vcenter_vm_snapshot:
raise ValueError('Please insert snapshot to deploy an app from a linked clone')
deploy_result_action = self.command_wrapper.execute_command_with_connection(
context,
self.deploy_command.execute_deploy_from_linked_clone,
data_holder,
cancellation_context,
self.folder_manager)
deploy_result_action.actionId = deploy_action.actionId
return deploy_result_action | Deploy Cloned VM From VM Command, will deploy vm from template
:param CancellationContext cancellation_context:
:param ResourceCommandContext context: the context of the command
:param DeployApp deploy_action:
:return DeployAppResult deploy results | entailment |
def deploy_from_image(self, context, deploy_action, cancellation_context):
"""
Deploy From Image Command, will deploy vm from ovf image
:param CancellationContext cancellation_context:
:param ResourceCommandContext context: the context of the command
:param DeployApp deploy_action:
:return str deploy results
"""
deploy_action.actionParams.deployment.attributes['vCenter Name'] = context.resource.name
deploy_from_image_model = self.resource_model_parser.convert_to_resource_model(
attributes=deploy_action.actionParams.deployment.attributes,
resource_model_type=vCenterVMFromImageResourceModel)
data_holder = DeployFromImageDetails(deploy_from_image_model, deploy_action.actionParams.appName)
# execute command
deploy_result_action = self.command_wrapper.execute_command_with_connection(
context,
self.deploy_command.execute_deploy_from_image,
data_holder,
context.resource,
cancellation_context,
self.folder_manager)
deploy_result_action.actionId = deploy_action.actionId
return deploy_result_action | Deploy From Image Command, will deploy vm from ovf image
:param CancellationContext cancellation_context:
:param ResourceCommandContext context: the context of the command
:param DeployApp deploy_action:
:return str deploy results | entailment |
def disconnect_all(self, context, ports):
"""
Disconnect All Command, will the assign all the vnics on the vm to the default network,
which is sign to be disconnected
:param models.QualiDriverModels.ResourceRemoteCommandContext context: the context the command runs on
:param list[string] ports: the ports of the connection between the remote resource and the local resource, NOT IN USE!!!
"""
resource_details = self._parse_remote_model(context)
# execute command
res = self.command_wrapper.execute_command_with_connection(
context,
self.virtual_switch_disconnect_command.disconnect_all,
resource_details.vm_uuid)
return set_command_result(result=res, unpicklable=False) | Disconnect All Command, will the assign all the vnics on the vm to the default network,
which is sign to be disconnected
:param models.QualiDriverModels.ResourceRemoteCommandContext context: the context the command runs on
:param list[string] ports: the ports of the connection between the remote resource and the local resource, NOT IN USE!!! | entailment |
def DeleteInstance(self, context, ports):
"""
Destroy Vm Command, will only destroy the vm and will not remove the resource
:param models.QualiDriverModels.ResourceRemoteCommandContext context: the context the command runs on
:param list[string] ports: the ports of the connection between the remote resource and the local resource, NOT IN USE!!!
"""
resource_details = self._parse_remote_model(context)
# execute command
res = self.command_wrapper.execute_command_with_connection(
context,
self.destroy_virtual_machine_command.DeleteInstance,
resource_details.vm_uuid,
resource_details.fullname)
return set_command_result(result=res, unpicklable=False) | Destroy Vm Command, will only destroy the vm and will not remove the resource
:param models.QualiDriverModels.ResourceRemoteCommandContext context: the context the command runs on
:param list[string] ports: the ports of the connection between the remote resource and the local resource, NOT IN USE!!! | entailment |
def refresh_ip(self, context, cancellation_context, ports):
"""
Refresh IP Command, will refresh the ip of the vm and will update it on the resource
:param ResourceRemoteCommandContext context: the context the command runs on
:param cancellation_context:
:param list[string] ports: the ports of the connection between the remote resource and the local resource, NOT IN USE!!!
"""
resource_details = self._parse_remote_model(context)
# execute command
res = self.command_wrapper.execute_command_with_connection(context,
self.refresh_ip_command.refresh_ip,
resource_details,
cancellation_context,
context.remote_endpoints[
0].app_context.app_request_json)
return set_command_result(result=res, unpicklable=False) | Refresh IP Command, will refresh the ip of the vm and will update it on the resource
:param ResourceRemoteCommandContext context: the context the command runs on
:param cancellation_context:
:param list[string] ports: the ports of the connection between the remote resource and the local resource, NOT IN USE!!! | entailment |
def power_off(self, context, ports):
"""
Powers off the remote vm
:param models.QualiDriverModels.ResourceRemoteCommandContext context: the context the command runs on
:param list[string] ports: the ports of the connection between the remote resource and the local resource, NOT IN USE!!!
"""
return self._power_command(context, ports, self.vm_power_management_command.power_off) | Powers off the remote vm
:param models.QualiDriverModels.ResourceRemoteCommandContext context: the context the command runs on
:param list[string] ports: the ports of the connection between the remote resource and the local resource, NOT IN USE!!! | entailment |
def power_on(self, context, ports):
"""
Powers on the remote vm
:param models.QualiDriverModels.ResourceRemoteCommandContext context: the context the command runs on
:param list[string] ports: the ports of the connection between the remote resource and the local resource, NOT IN USE!!!
"""
return self._power_command(context, ports, self.vm_power_management_command.power_on) | Powers on the remote vm
:param models.QualiDriverModels.ResourceRemoteCommandContext context: the context the command runs on
:param list[string] ports: the ports of the connection between the remote resource and the local resource, NOT IN USE!!! | entailment |
def power_cycle(self, context, ports, delay):
"""
preforms a restart to the vm
:param models.QualiDriverModels.ResourceRemoteCommandContext context: the context the command runs on
:param list[string] ports: the ports of the connection between the remote resource and the local resource, NOT IN USE!!!
:param number delay: the time to wait between the power on and off
"""
self.power_off(context, ports)
time.sleep(float(delay))
return self.power_on(context, ports) | preforms a restart to the vm
:param models.QualiDriverModels.ResourceRemoteCommandContext context: the context the command runs on
:param list[string] ports: the ports of the connection between the remote resource and the local resource, NOT IN USE!!!
:param number delay: the time to wait between the power on and off | entailment |
def _parse_remote_model(self, context):
"""
parse the remote resource model and adds its full name
:type context: models.QualiDriverModels.ResourceRemoteCommandContext
"""
if not context.remote_endpoints:
raise Exception('no remote resources found in context: {0}', jsonpickle.encode(context, unpicklable=False))
resource = context.remote_endpoints[0]
dictionary = jsonpickle.decode(resource.app_context.deployed_app_json)
holder = DeployDataHolder(dictionary)
app_resource_detail = GenericDeployedAppResourceModel()
app_resource_detail.vm_uuid = holder.vmdetails.uid
app_resource_detail.cloud_provider = context.resource.fullname
app_resource_detail.fullname = resource.fullname
if hasattr(holder.vmdetails, 'vmCustomParams'):
app_resource_detail.vm_custom_params = holder.vmdetails.vmCustomParams
return app_resource_detail | parse the remote resource model and adds its full name
:type context: models.QualiDriverModels.ResourceRemoteCommandContext | entailment |
def save_snapshot(self, context, snapshot_name, save_memory='No'):
"""
Saves virtual machine to a snapshot
:param context: resource context of the vCenterShell
:type context: models.QualiDriverModels.ResourceCommandContext
:param snapshot_name: snapshot name to save to
:type snapshot_name: str
:param save_memory: Snapshot the virtual machine's memory. Lookup, Yes / No
:type save_memory: str
:return:
"""
resource_details = self._parse_remote_model(context)
created_snapshot_path = self.command_wrapper.execute_command_with_connection(context,
self.snapshot_saver.save_snapshot,
resource_details.vm_uuid,
snapshot_name,
save_memory)
return set_command_result(created_snapshot_path) | Saves virtual machine to a snapshot
:param context: resource context of the vCenterShell
:type context: models.QualiDriverModels.ResourceCommandContext
:param snapshot_name: snapshot name to save to
:type snapshot_name: str
:param save_memory: Snapshot the virtual machine's memory. Lookup, Yes / No
:type save_memory: str
:return: | entailment |
def restore_snapshot(self, context, snapshot_name):
"""
Restores virtual machine from a snapshot
:param context: resource context of the vCenterShell
:type context: models.QualiDriverModels.ResourceCommandContext
:param snapshot_name: snapshot name to save to
:type snapshot_name: str
:return:
"""
resource_details = self._parse_remote_model(context)
self.command_wrapper.execute_command_with_connection(context,
self.snapshot_restorer.restore_snapshot,
resource_details.vm_uuid,
resource_details.fullname,
snapshot_name) | Restores virtual machine from a snapshot
:param context: resource context of the vCenterShell
:type context: models.QualiDriverModels.ResourceCommandContext
:param snapshot_name: snapshot name to save to
:type snapshot_name: str
:return: | entailment |
def get_snapshots(self, context):
"""
Returns list of snapshots
:param context: resource context of the vCenterShell
:type context: models.QualiDriverModels.ResourceCommandContext
:return:
"""
resource_details = self._parse_remote_model(context)
res = self.command_wrapper.execute_command_with_connection(context,
self.snapshots_retriever.get_snapshots,
resource_details.vm_uuid)
return set_command_result(result=res, unpicklable=False) | Returns list of snapshots
:param context: resource context of the vCenterShell
:type context: models.QualiDriverModels.ResourceCommandContext
:return: | entailment |
def orchestration_save(self, context, mode="shallow", custom_params=None):
"""
Creates a snapshot with a unique name and returns SavedResults as JSON
:param context: resource context of the vCenterShell
:param mode: Snapshot save mode, default shallow. Currently not it use
:param custom_params: Set of custom parameter to be supported in the future
:return: SavedResults serialized as JSON
:rtype: SavedResults
"""
resource_details = self._parse_remote_model(context)
created_date = datetime.now()
snapshot_name = created_date.strftime('%y_%m_%d %H_%M_%S_%f')
created_snapshot_path = self.save_snapshot(context=context, snapshot_name=snapshot_name)
created_snapshot_path = self._strip_double_quotes(created_snapshot_path)
orchestration_saved_artifact = OrchestrationSavedArtifact()
orchestration_saved_artifact.artifact_type = 'vcenter_snapshot'
orchestration_saved_artifact.identifier = created_snapshot_path
saved_artifacts_info = OrchestrationSavedArtifactsInfo(
resource_name=resource_details.cloud_provider,
created_date=created_date,
restore_rules={'requires_same_resource': True},
saved_artifact=orchestration_saved_artifact)
orchestration_save_result = OrchestrationSaveResult(saved_artifacts_info)
return set_command_result(result=orchestration_save_result, unpicklable=False) | Creates a snapshot with a unique name and returns SavedResults as JSON
:param context: resource context of the vCenterShell
:param mode: Snapshot save mode, default shallow. Currently not it use
:param custom_params: Set of custom parameter to be supported in the future
:return: SavedResults serialized as JSON
:rtype: SavedResults | entailment |
def get_vcenter_data_model(self, api, vcenter_name):
"""
:param api:
:param str vcenter_name:
:rtype: VMwarevCenterResourceModel
"""
if not vcenter_name:
raise ValueError('VMWare vCenter name is empty')
vcenter_instance = api.GetResourceDetails(vcenter_name)
vcenter_resource_model = self.resource_model_parser.convert_to_vcenter_model(vcenter_instance)
return vcenter_resource_model | :param api:
:param str vcenter_name:
:rtype: VMwarevCenterResourceModel | entailment |
def back_slash_to_front_converter(string):
"""
Replacing all \ in the str to /
:param string: single string to modify
:type string: str
"""
try:
if not string or not isinstance(string, str):
return string
return string.replace('\\', '/')
except Exception:
return string | Replacing all \ in the str to /
:param string: single string to modify
:type string: str | entailment |
def get_object_as_string(obj):
"""
Converts any object to JSON-like readable format, ready to be printed for debugging purposes
:param obj: Any object
:return: string
"""
if isinstance(obj, str):
return obj
if isinstance(obj, list):
return '\r\n\;'.join([get_object_as_string(item) for item in obj])
attrs = vars(obj)
as_string = ', '.join("%s: %s" % item for item in attrs.items())
return as_string | Converts any object to JSON-like readable format, ready to be printed for debugging purposes
:param obj: Any object
:return: string | entailment |
def get_path_and_name(full_name):
"""
Split Whole Patch onto 'Patch' and 'Name'
:param full_name: <str> Full Resource Name - likes 'Root/Folder/Folder2/Name'
:return: tuple (Patch, Name)
"""
if full_name:
parts = full_name.split("/")
return ("/".join(parts[0:-1]), parts[-1]) if len(parts) > 1 else ("/", full_name)
return None, None | Split Whole Patch onto 'Patch' and 'Name'
:param full_name: <str> Full Resource Name - likes 'Root/Folder/Folder2/Name'
:return: tuple (Patch, Name) | entailment |
def get_details(self):
"""
:rtype list[VmDataField]
"""
data = []
if self.deployment == 'vCenter Clone VM From VM':
data.append(VmDetailsProperty(key='Cloned VM Name',value= self.dep_attributes.get('vCenter VM','')))
if self.deployment == 'VCenter Deploy VM From Linked Clone':
template = self.dep_attributes.get('vCenter VM','')
snapshot = self.dep_attributes.get('vCenter VM Snapshot','')
data.append(VmDetailsProperty(key='Cloned VM Name',value= '{0} (snapshot: {1})'.format(template, snapshot)))
if self.deployment == 'vCenter VM From Image':
data.append(VmDetailsProperty(key='Base Image Name',value= self.dep_attributes.get('vCenter Image','').split('/')[-1]))
if self.deployment == 'vCenter VM From Template':
data.append(VmDetailsProperty(key='Template Name',value= self.dep_attributes.get('vCenter Template','')))
return data | :rtype list[VmDataField] | entailment |
def set_deplyment_vcenter_params(vcenter_resource_model, deploy_params):
"""
Sets the vcenter parameters if not already set at the deployment option
:param deploy_params: vCenterVMFromTemplateResourceModel or vCenterVMFromImageResourceModel
:type vcenter_resource_model: VMwarevCenterResourceModel
"""
# Override attributes
deploy_params.vm_cluster = deploy_params.vm_cluster or vcenter_resource_model.vm_cluster
deploy_params.vm_storage = deploy_params.vm_storage or vcenter_resource_model.vm_storage
deploy_params.vm_resource_pool = deploy_params.vm_resource_pool or vcenter_resource_model.vm_resource_pool
deploy_params.vm_location = deploy_params.vm_location or vcenter_resource_model.vm_location
deploy_params.default_datacenter = vcenter_resource_model.default_datacenter
if not deploy_params.vm_cluster:
raise ValueError('VM Cluster is empty')
if not deploy_params.vm_storage:
raise ValueError('VM Storage is empty')
if not deploy_params.vm_location:
raise ValueError('VM Location is empty')
if not deploy_params.default_datacenter:
raise ValueError('Default Datacenter attribute on VMWare vCenter is empty')
deploy_params.vm_location = VMLocation.combine([deploy_params.default_datacenter, deploy_params.vm_location]) | Sets the vcenter parameters if not already set at the deployment option
:param deploy_params: vCenterVMFromTemplateResourceModel or vCenterVMFromImageResourceModel
:type vcenter_resource_model: VMwarevCenterResourceModel | entailment |
def remote_save_snapshot(self, context, ports, snapshot_name, save_memory):
"""
Saves virtual machine to a snapshot
:param context: resource context of the vCenterShell
:type context: models.QualiDriverModels.ResourceCommandContext
:param ports:list[string] ports: the ports of the connection between the remote resource and the local resource
:type ports: list[string]
:param snapshot_name: snapshot name to save to
:type snapshot_name: str
:param save_memory: Snapshot the virtual machine's memory. Lookup, Yes / No
:type save_memory: str
:return:
"""
return self.command_orchestrator.save_snapshot(context, snapshot_name, save_memory) | Saves virtual machine to a snapshot
:param context: resource context of the vCenterShell
:type context: models.QualiDriverModels.ResourceCommandContext
:param ports:list[string] ports: the ports of the connection between the remote resource and the local resource
:type ports: list[string]
:param snapshot_name: snapshot name to save to
:type snapshot_name: str
:param save_memory: Snapshot the virtual machine's memory. Lookup, Yes / No
:type save_memory: str
:return: | entailment |
def remote_restore_snapshot(self, context, ports, snapshot_name):
"""
Restores virtual machine from a snapshot
:param context: resource context of the vCenterShell
:type context: models.QualiDriverModels.ResourceCommandContext
:param ports:list[string] ports: the ports of the connection between the remote resource and the local resource
:type ports: list[string]
:param snapshot_name: Snapshot name to restore from
:type snapshot_name: str
:return:
"""
return self.command_orchestrator.restore_snapshot(context, snapshot_name) | Restores virtual machine from a snapshot
:param context: resource context of the vCenterShell
:type context: models.QualiDriverModels.ResourceCommandContext
:param ports:list[string] ports: the ports of the connection between the remote resource and the local resource
:type ports: list[string]
:param snapshot_name: Snapshot name to restore from
:type snapshot_name: str
:return: | entailment |
def connect_bulk(self, si, logger, vcenter_data_model, request):
"""
:param si:
:param logger:
:param VMwarevCenterResourceModel vcenter_data_model:
:param request:
:return:
"""
self.logger = logger
self.logger.info('Apply connectivity changes has started')
self.logger.debug('Apply connectivity changes has started with the requet: {0}'.format(request))
holder = DeployDataHolder(jsonpickle.decode(request))
self.vcenter_data_model = vcenter_data_model
if vcenter_data_model.reserved_networks:
self.reserved_networks = [name.strip() for name in vcenter_data_model.reserved_networks.split(',')]
if not vcenter_data_model.default_dvswitch:
return self._handle_no_dvswitch_error(holder)
dvswitch_location = VMLocation.create_from_full_path(vcenter_data_model.default_dvswitch)
self.dv_switch_path = VMLocation.combine([vcenter_data_model.default_datacenter, dvswitch_location.path])
self.dv_switch_name = dvswitch_location.name
self.default_network = VMLocation.combine(
[vcenter_data_model.default_datacenter, vcenter_data_model.holding_network])
mappings = self._map_requsets(holder.driverRequest.actions)
self.logger.debug('Connectivity actions mappings: {0}'.format(jsonpickle.encode(mappings, unpicklable=False)))
pool = ThreadPool()
async_results = self._run_async_connection_actions(si, mappings, pool, logger)
results = self._get_async_results(async_results, pool)
self.logger.info('Apply connectivity changes done')
self.logger.debug('Apply connectivity has finished with the results: {0}'.format(jsonpickle.encode(results,
unpicklable=False)))
return results | :param si:
:param logger:
:param VMwarevCenterResourceModel vcenter_data_model:
:param request:
:return: | entailment |
def destroy(self, si, logger, session, vcenter_data_model, vm_uuid, vm_name, reservation_id):
"""
:param si:
:param logger:
:param CloudShellAPISession session:
:param vcenter_data_model:
:param vm_uuid:
:param str vm_name: This is the resource name
:param reservation_id:
:return:
"""
# disconnect
self._disconnect_all_my_connectors(session=session, resource_name=vm_name, reservation_id=reservation_id,
logger=logger)
# find vm
vm = self.pv_service.find_by_uuid(si, vm_uuid)
if vm is not None:
# destroy vm
result = self.pv_service.destroy_vm(vm=vm, logger=logger)
else:
logger.info("Could not find the VM {0},will remove the resource.".format(vm_name))
result = True
# delete resources
self.resource_remover.remove_resource(session=session, resource_full_name=vm_name)
return result | :param si:
:param logger:
:param CloudShellAPISession session:
:param vcenter_data_model:
:param vm_uuid:
:param str vm_name: This is the resource name
:param reservation_id:
:return: | entailment |
def DeleteInstance(self, si, logger, session, vcenter_data_model, vm_uuid, vm_name):
"""
:param logger:
:param CloudShellAPISession session:
:param str vm_name: This is the resource name
:return:
"""
# find vm
vm = self.pv_service.find_by_uuid(si, vm_uuid)
if vm is not None:
# destroy vm
result = self.pv_service.destroy_vm(vm=vm, logger=logger)
else:
resource___format = "Could not find the VM {0},will remove the resource.".format(vm_name)
logger.info(resource___format)
result = resource___format
return result | :param logger:
:param CloudShellAPISession session:
:param str vm_name: This is the resource name
:return: | entailment |
def _disconnect_all_my_connectors(session, resource_name, reservation_id, logger):
"""
:param CloudShellAPISession session:
:param str resource_name:
:param str reservation_id:
"""
reservation_details = session.GetReservationDetails(reservation_id)
connectors = reservation_details.ReservationDescription.Connectors
endpoints = []
for endpoint in connectors:
if endpoint.Target == resource_name or endpoint.Source == resource_name:
endpoints.append(endpoint.Target)
endpoints.append(endpoint.Source)
if len(endpoints) == 0:
logger.info("No routes to disconnect for resource {0} in reservation {1}"
.format(resource_name, reservation_id))
return
logger.info("Executing disconnect routes for resource {0} in reservation {1}"
.format(resource_name, reservation_id))
try:
session.DisconnectRoutesInReservation(reservation_id, endpoints)
except Exception as exc:
logger.exception("Error disconnecting routes for resource {0} in reservation {1}. Error: {2}"
.format(resource_name, reservation_id, get_error_message_from_exception(exc))) | :param CloudShellAPISession session:
:param str resource_name:
:param str reservation_id: | entailment |
def delete_sandbox(self, si, logger, vcenter_data_model, delete_sandbox_actions, cancellation_context):
"""
Deletes a saved sandbox's artifacts
:param vcenter_data_model: VMwarevCenterResourceModel
:param vim.ServiceInstance si: py_vmomi service instance
:type si: vim.ServiceInstance
:param logger: Logger
:type logger: cloudshell.core.logger.qs_logger.get_qs_logger
:param list[SaveApp] delete_sandbox_actions:
:param cancellation_context:
"""
results = []
logger.info('Deleting saved sandbox command starting on ' + vcenter_data_model.default_datacenter)
if not delete_sandbox_actions:
raise Exception('Failed to delete saved sandbox, missing data in request.')
actions_grouped_by_save_types = groupby(delete_sandbox_actions, lambda x: x.actionParams.saveDeploymentModel)
artifactHandlersToActions = {ArtifactHandler.factory(k,
self.pyvmomi_service,
vcenter_data_model,
si,
logger,
self.deployer,
None,
self.resource_model_parser,
self.snapshot_saver,
self.task_waiter,
self.folder_manager,
self.pg,
self.cs): list(g)
for k, g in actions_grouped_by_save_types}
self._validate_save_deployment_models(artifactHandlersToActions, delete_sandbox_actions, results)
error_results = [r for r in results if not r.success]
if not error_results:
results = self._execute_delete_saved_sandbox(artifactHandlersToActions,
cancellation_context,
logger,
results)
return results | Deletes a saved sandbox's artifacts
:param vcenter_data_model: VMwarevCenterResourceModel
:param vim.ServiceInstance si: py_vmomi service instance
:type si: vim.ServiceInstance
:param logger: Logger
:type logger: cloudshell.core.logger.qs_logger.get_qs_logger
:param list[SaveApp] delete_sandbox_actions:
:param cancellation_context: | entailment |
def execute_deploy_from_linked_clone(self, si, logger, vcenter_data_model, reservation_id, deployment_params, cancellation_context, folder_manager):
"""
Calls the deployer to deploy vm from snapshot
:param cancellation_context:
:param str reservation_id:
:param si:
:param logger:
:type deployment_params: DeployFromLinkedClone
:param vcenter_data_model:
:return:
"""
self._prepare_deployed_apps_folder(deployment_params, si, logger, folder_manager, vcenter_data_model)
deploy_result = self.deployer.deploy_from_linked_clone(si, logger, deployment_params, vcenter_data_model,
reservation_id, cancellation_context)
return deploy_result | Calls the deployer to deploy vm from snapshot
:param cancellation_context:
:param str reservation_id:
:param si:
:param logger:
:type deployment_params: DeployFromLinkedClone
:param vcenter_data_model:
:return: | entailment |
def execute_deploy_clone_from_vm(self, si, logger, vcenter_data_model, reservation_id, deployment_params, cancellation_context, folder_manager):
"""
Calls the deployer to deploy vm from another vm
:param cancellation_context:
:param str reservation_id:
:param si:
:param logger:
:type deployment_params: DeployFromTemplateDetails
:param vcenter_data_model:
:return:
"""
self._prepare_deployed_apps_folder(deployment_params, si, logger, folder_manager, vcenter_data_model)
deploy_result = self.deployer.deploy_clone_from_vm(si, logger, deployment_params, vcenter_data_model,
reservation_id, cancellation_context)
return deploy_result | Calls the deployer to deploy vm from another vm
:param cancellation_context:
:param str reservation_id:
:param si:
:param logger:
:type deployment_params: DeployFromTemplateDetails
:param vcenter_data_model:
:return: | entailment |
def save_snapshot(self, si, logger, vm_uuid, snapshot_name, save_memory):
"""
Creates a snapshot of the current state of the virtual machine
:param vim.ServiceInstance si: py_vmomi service instance
:type si: vim.ServiceInstance
:param logger: Logger
:type logger: cloudshell.core.logger.qs_logger.get_qs_logger
:param vm_uuid: UUID of the virtual machine
:type vm_uuid: str
:param snapshot_name: Snapshot name to save the snapshot to
:type snapshot_name: str
:param save_memory: Snapshot the virtual machine's memory. Lookup, Yes / No
:type save_memory: str
"""
vm = self.pyvmomi_service.find_by_uuid(si, vm_uuid)
snapshot_path_to_be_created = SaveSnapshotCommand._get_snapshot_name_to_be_created(snapshot_name, vm)
save_vm_memory_to_snapshot = SaveSnapshotCommand._get_save_vm_memory_to_snapshot(save_memory)
SaveSnapshotCommand._verify_snapshot_uniquness(snapshot_path_to_be_created, vm)
task = self._create_snapshot(logger, snapshot_name, vm, save_vm_memory_to_snapshot)
self.task_waiter.wait_for_task(task=task, logger=logger, action_name='Create Snapshot')
return snapshot_path_to_be_created | Creates a snapshot of the current state of the virtual machine
:param vim.ServiceInstance si: py_vmomi service instance
:type si: vim.ServiceInstance
:param logger: Logger
:type logger: cloudshell.core.logger.qs_logger.get_qs_logger
:param vm_uuid: UUID of the virtual machine
:type vm_uuid: str
:param snapshot_name: Snapshot name to save the snapshot to
:type snapshot_name: str
:param save_memory: Snapshot the virtual machine's memory. Lookup, Yes / No
:type save_memory: str | entailment |
def _create_snapshot(logger, snapshot_name, vm, save_vm_memory_to_snapshot):
"""
:type save_vm_memory_to_snapshot: bool
"""
logger.info("Create virtual machine snapshot")
dump_memory = save_vm_memory_to_snapshot
quiesce = True
task = vm.CreateSnapshot(snapshot_name, 'Created by CloudShell vCenterShell', dump_memory, quiesce)
return task | :type save_vm_memory_to_snapshot: bool | entailment |
def generate_unique_name(name_prefix, reservation_id=None):
"""
Generate a unique name.
Method generate a guid and adds the first 8 characteres of the new guid to 'name_prefix'.
If reservation id is provided than the first 4 chars of the generated guid are taken and the last 4
of the reservation id
"""
if reservation_id and isinstance(reservation_id, str) and len(reservation_id) >= 4:
unique_id = str(uuid.uuid4())[:4] + "-" + reservation_id[-4:]
else:
unique_id = str(uuid.uuid4())[:8]
return name_prefix + "_" + unique_id | Generate a unique name.
Method generate a guid and adds the first 8 characteres of the new guid to 'name_prefix'.
If reservation id is provided than the first 4 chars of the generated guid are taken and the last 4
of the reservation id | entailment |
def disconnect(self, si, logger, vcenter_data_model, vm_uuid, network_name=None, vm=None):
"""
disconnect network adapter of the vm. If 'network_name' = None - disconnect ALL interfaces
:param <str> si:
:param logger:
:param VMwarevCenterResourceModel vcenter_data_model:
:param <str> vm_uuid: the uuid of the vm
:param <str | None> network_name: the name of the specific network to disconnect
:param <pyvmomi vm object> vm: If the vm obj is None will use vm_uuid to fetch the object
:return: Started Task
"""
logger.debug("Disconnect Interface VM: '{0}' Network: '{1}' ...".format(vm_uuid, network_name or "ALL"))
if vm is None:
vm = self.pyvmomi_service.find_by_uuid(si, vm_uuid)
if not vm:
return "Warning: failed to locate vm {0} in vCenter".format(vm_uuid)
if network_name:
network = self.pyvmomi_service.vm_get_network_by_name(vm, network_name)
if network is None:
raise KeyError('Network not found ({0})'.format(network_name))
else:
network = None
network_full_name = VMLocation.combine(
[vcenter_data_model.default_datacenter, vcenter_data_model.holding_network])
default_network = self.pyvmomi_service.get_network_by_full_name(si, network_full_name)
if network:
return self.port_group_configurer.disconnect_network(vm, network, default_network,
vcenter_data_model.reserved_networks,
logger=logger)
else:
return self.port_group_configurer.disconnect_all_networks(vm, default_network,
vcenter_data_model.reserved_networks,
logger=logger) | disconnect network adapter of the vm. If 'network_name' = None - disconnect ALL interfaces
:param <str> si:
:param logger:
:param VMwarevCenterResourceModel vcenter_data_model:
:param <str> vm_uuid: the uuid of the vm
:param <str | None> network_name: the name of the specific network to disconnect
:param <pyvmomi vm object> vm: If the vm obj is None will use vm_uuid to fetch the object
:return: Started Task | entailment |
def remove_interfaces_from_vm_task(self, virtual_machine, filter_function=None):
"""
Remove interface from VM
@see https://www.vmware.com/support/developer/vc-sdk/visdk41pubs/ApiReference/vim.VirtualMachine.html#reconfigure
:param virtual_machine: <vim.vm object>
:param filter_function: function that gets the device and decide if it should be deleted
:return: Task or None
"""
device_change = []
for device in virtual_machine.config.hardware.device:
if isinstance(device, vim.vm.device.VirtualEthernetCard) and \
(filter_function is None or filter_function(device)):
nicspec = vim.vm.device.VirtualDeviceSpec()
nicspec.operation = vim.vm.device.VirtualDeviceSpec.Operation.remove
nicspec.device = device
device_change.append(nicspec)
if len(device_change) > 0:
return self.pyvmomi_service.vm_reconfig_task(virtual_machine, device_change)
return None | Remove interface from VM
@see https://www.vmware.com/support/developer/vc-sdk/visdk41pubs/ApiReference/vim.VirtualMachine.html#reconfigure
:param virtual_machine: <vim.vm object>
:param filter_function: function that gets the device and decide if it should be deleted
:return: Task or None | entailment |
def connect_by_mapping(self, si, vm, mapping, default_network, reserved_networks, logger, promiscuous_mode):
"""
gets the mapping to the vnics and connects it to the vm
:param default_network:
:param si: ServiceInstance
:param vm: vim.VirtualMachine
:param mapping: [VmNetworkMapping]
:param reserved_networks:
:param logger:
:param promiscuous_mode <str> 'True' or 'False' turn on/off promiscuous mode for the port group
"""
request_mapping = []
logger.debug(
'about to map to the vm: {0}, the following networks'.format(vm.name if vm.name else vm.config.uuid))
for network_map in mapping:
network = self.dv_port_group_creator.get_or_create_network(si,
vm,
network_map.dv_port_name,
network_map.dv_switch_name,
network_map.dv_switch_path,
network_map.vlan_id,
network_map.vlan_spec,
logger,
promiscuous_mode)
request_mapping.append(ConnectRequest(network_map.vnic_name, network))
logger.debug(str(request_mapping))
return self.virtual_machine_port_group_configurer.connect_vnic_to_networks(vm,
request_mapping,
default_network,
reserved_networks,
logger) | gets the mapping to the vnics and connects it to the vm
:param default_network:
:param si: ServiceInstance
:param vm: vim.VirtualMachine
:param mapping: [VmNetworkMapping]
:param reserved_networks:
:param logger:
:param promiscuous_mode <str> 'True' or 'False' turn on/off promiscuous mode for the port group | entailment |
def dv_port_group_create_task(dv_port_name, dv_switch, spec, vlan_id, logger, promiscuous_mode, num_ports=32):
"""
Create ' Distributed Virtual Portgroup' Task
:param dv_port_name: <str> Distributed Virtual Portgroup Name
:param dv_switch: <vim.dvs.VmwareDistributedVirtualSwitch> Switch this Portgroup will be belong to
:param spec:
:param vlan_id: <int>
:param logger:
:param num_ports: <int> number of ports in this Group
:param promiscuous_mode <str> 'True' or 'False' turn on/off promiscuous mode for the port group
:return: <vim.Task> Task which really provides update
"""
dv_pg_spec = vim.dvs.DistributedVirtualPortgroup.ConfigSpec()
dv_pg_spec.name = dv_port_name
dv_pg_spec.numPorts = num_ports
dv_pg_spec.type = vim.dvs.DistributedVirtualPortgroup.PortgroupType.earlyBinding
dv_pg_spec.defaultPortConfig = vim.dvs.VmwareDistributedVirtualSwitch.VmwarePortConfigPolicy()
dv_pg_spec.defaultPortConfig.securityPolicy = vim.dvs.VmwareDistributedVirtualSwitch.SecurityPolicy()
dv_pg_spec.defaultPortConfig.vlan = spec
dv_pg_spec.defaultPortConfig.vlan.vlanId = vlan_id
promiscuous_mode = promiscuous_mode.lower() == 'true'
dv_pg_spec.defaultPortConfig.securityPolicy.allowPromiscuous = vim.BoolPolicy(value=promiscuous_mode)
dv_pg_spec.defaultPortConfig.securityPolicy.forgedTransmits = vim.BoolPolicy(value=True)
dv_pg_spec.defaultPortConfig.vlan.inherited = False
dv_pg_spec.defaultPortConfig.securityPolicy.macChanges = vim.BoolPolicy(value=False)
dv_pg_spec.defaultPortConfig.securityPolicy.inherited = False
task = dv_switch.AddDVPortgroup_Task([dv_pg_spec])
logger.info(u"DV Port Group '{}' CREATE Task ...".format(dv_port_name))
return task | Create ' Distributed Virtual Portgroup' Task
:param dv_port_name: <str> Distributed Virtual Portgroup Name
:param dv_switch: <vim.dvs.VmwareDistributedVirtualSwitch> Switch this Portgroup will be belong to
:param spec:
:param vlan_id: <int>
:param logger:
:param num_ports: <int> number of ports in this Group
:param promiscuous_mode <str> 'True' or 'False' turn on/off promiscuous mode for the port group
:return: <vim.Task> Task which really provides update | entailment |
def create_deployment_details(vcenter_resource_model, vm_cluster, vm_storage, vm_resource_pool, vm_location):
"""
:type vcenter_resource_model: VMwarevCenterResourceModel
:type vm_cluster: str
:type vm_storage: str
:type vm_resource_pool: str
:type vm_location: str
:rtype: DeploymentDetails
"""
vm_cluster = vm_cluster or vcenter_resource_model.vm_cluster
vm_storage = vm_storage or vcenter_resource_model.vm_storage
vm_resource_pool = vm_resource_pool or vcenter_resource_model.vm_resource_pool
vm_location = vm_location or vcenter_resource_model.vm_location
return DeploymentDetails(
vm_cluster=vm_cluster,
vm_storage=vm_storage,
vm_resource_pool=vm_resource_pool,
vm_location=vm_location
) | :type vcenter_resource_model: VMwarevCenterResourceModel
:type vm_cluster: str
:type vm_storage: str
:type vm_resource_pool: str
:type vm_location: str
:rtype: DeploymentDetails | entailment |
def refresh_ip(self, si, logger, session, vcenter_data_model, resource_model, cancellation_context,
app_request_json):
"""
Refreshes IP address of virtual machine and updates Address property on the resource
:param vim.ServiceInstance si: py_vmomi service instance
:param logger:
:param vCenterShell.driver.SecureCloudShellApiSession session: cloudshell session
:param GenericDeployedAppResourceModel resource_model: UUID of Virtual Machine
:param VMwarevCenterResourceModel vcenter_data_model: the vcenter data model attributes
:param cancellation_context:
"""
self._do_not_run_on_static_vm(app_request_json=app_request_json)
default_network = VMLocation.combine(
[vcenter_data_model.default_datacenter, vcenter_data_model.holding_network])
match_function = self.ip_manager.get_ip_match_function(
self._get_ip_refresh_ip_regex(resource_model.vm_custom_params))
timeout = self._get_ip_refresh_timeout(resource_model.vm_custom_params)
vm = self.pyvmomi_service.find_by_uuid(si, resource_model.vm_uuid)
ip_res = self.ip_manager.get_ip(vm, default_network, match_function, cancellation_context, timeout, logger)
if ip_res.reason == IpReason.Timeout:
raise ValueError('IP address of VM \'{0}\' could not be obtained during {1} seconds'
.format(resource_model.fullname, timeout))
if ip_res.reason == IpReason.Success:
self._update_resource_address_with_retry(session=session,
resource_name=resource_model.fullname,
ip_address=ip_res.ip_address)
return ip_res.ip_address | Refreshes IP address of virtual machine and updates Address property on the resource
:param vim.ServiceInstance si: py_vmomi service instance
:param logger:
:param vCenterShell.driver.SecureCloudShellApiSession session: cloudshell session
:param GenericDeployedAppResourceModel resource_model: UUID of Virtual Machine
:param VMwarevCenterResourceModel vcenter_data_model: the vcenter data model attributes
:param cancellation_context: | entailment |
def get_connection_details(session, vcenter_resource_model, resource_context):
"""
Methods retrieves the connection details from the vcenter resource model attributes.
:param CloudShellAPISession session:
:param VMwarevCenterResourceModel vcenter_resource_model: Instance of VMwarevCenterResourceModel
:param ResourceContextDetails resource_context: the context of the command
"""
session = session
resource_context = resource_context
# get vCenter connection details from vCenter resource
user = vcenter_resource_model.user
vcenter_url = resource_context.address
password = session.DecryptPassword(vcenter_resource_model.password).Value
return VCenterConnectionDetails(vcenter_url, user, password) | Methods retrieves the connection details from the vcenter resource model attributes.
:param CloudShellAPISession session:
:param VMwarevCenterResourceModel vcenter_resource_model: Instance of VMwarevCenterResourceModel
:param ResourceContextDetails resource_context: the context of the command | entailment |
def vnic_add_to_vm_task(nicspec, virtual_machine, logger):
"""
Add new vNIC to VM
:param nicspec: <vim.vm.device.VirtualDeviceSpec>
:param virtual_machine:
:param logger:
:return:
"""
if issubclass(type(nicspec), vim.vm.device.VirtualDeviceSpec):
nicspec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
VNicService.vnic_set_connectivity_status(nicspec, True)
logger.debug(u"Attaching new vNIC '{}' to VM '{}'...".format(nicspec, virtual_machine))
task = pyVmomiService.vm_reconfig_task(virtual_machine, [nicspec])
return task
else:
logger.warn(u"Cannot attach new vNIC '{}' to VM '{}'".format(nicspec, virtual_machine))
return None | Add new vNIC to VM
:param nicspec: <vim.vm.device.VirtualDeviceSpec>
:param virtual_machine:
:param logger:
:return: | entailment |
def get_network_by_device(vm, device, pyvmomi_service, logger):
"""
Get a Network connected to a particular Device (vNIC)
@see https://github.com/vmware/pyvmomi/blob/master/docs/vim/dvs/PortConnection.rst
:param vm:
:param device: <vim.vm.device.VirtualVmxnet3> instance of adapter
:param pyvmomi_service:
:param logger:
:return: <vim Network Obj or None>
"""
try:
backing = device.backing
if hasattr(backing, 'network'):
return backing.network
elif hasattr(backing, 'port') and hasattr(backing.port, 'portgroupKey'):
return VNicService._network_get_network_by_connection(vm, backing.port, pyvmomi_service)
except:
logger.debug(u"Cannot determinate which Network connected to device {}".format(device))
return None | Get a Network connected to a particular Device (vNIC)
@see https://github.com/vmware/pyvmomi/blob/master/docs/vim/dvs/PortConnection.rst
:param vm:
:param device: <vim.vm.device.VirtualVmxnet3> instance of adapter
:param pyvmomi_service:
:param logger:
:return: <vim Network Obj or None> | entailment |
def device_is_attached_to_network(device, network_name):
"""
Checks if the device has a backing with of the right network name
:param <vim.vm.Device> device: instance of adapter
:param <str> network_name: network name
:return:
"""
try:
backing = device.backing
except:
return False
if hasattr(backing, 'network') and hasattr(backing.network, 'name'):
return network_name == backing.network.name
elif hasattr(backing, 'port') and hasattr(backing.port, 'portgroupKey'):
return network_name == backing.port.portgroupKey
return False | Checks if the device has a backing with of the right network name
:param <vim.vm.Device> device: instance of adapter
:param <str> network_name: network name
:return: | entailment |
def vnic_compose_empty(device=None):
"""
Compose empty vNIC for next attaching to a network
:param device: <vim.vm.device.VirtualVmxnet3 or None> Device for this this 'spec' will be composed.
If 'None' a new device will be composed.
'Operation' - edit/add' depends on if device existed
:return: <vim.vm.device.VirtualDeviceSpec>
"""
nicspec = vim.vm.device.VirtualDeviceSpec()
if device:
nicspec.device = device
nicspec.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit
else:
nicspec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
nicspec.device = vim.vm.device.VirtualVmxnet3()
nicspec.device.wakeOnLanEnabled = True
nicspec.device.deviceInfo = vim.Description()
nicspec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
nicspec.device.connectable.startConnected = True
nicspec.device.connectable.allowGuestControl = True
return nicspec | Compose empty vNIC for next attaching to a network
:param device: <vim.vm.device.VirtualVmxnet3 or None> Device for this this 'spec' will be composed.
If 'None' a new device will be composed.
'Operation' - edit/add' depends on if device existed
:return: <vim.vm.device.VirtualDeviceSpec> | entailment |
def vnic_attach_to_network_standard(nicspec, network, logger):
"""
Attach vNIC to a 'usual' network
:param nicspec: <vim.vm.device.VirtualDeviceSpec>
:param network: <vim.Network>
:param logger:
:return: updated 'nicspec'
"""
if nicspec and network_is_standard(network):
network_name = network.name
nicspec.device.backing = vim.vm.device.VirtualEthernetCard.NetworkBackingInfo()
nicspec.device.backing.network = network
nicspec.device.wakeOnLanEnabled = True
nicspec.device.deviceInfo = vim.Description()
nicspec.device.backing.deviceName = network_name
nicspec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
nicspec.device.connectable.startConnected = True
nicspec.device.connectable.allowGuestControl = True
logger.debug(u"Assigning network '{}' for vNIC".format(network_name))
else:
# logger.warn(u"Cannot assigning network '{}' for vNIC {}".format(network, nicspec))
logger.warn(u"Cannot assigning network for vNIC ".format(network, nicspec))
return nicspec | Attach vNIC to a 'usual' network
:param nicspec: <vim.vm.device.VirtualDeviceSpec>
:param network: <vim.Network>
:param logger:
:return: updated 'nicspec' | entailment |
def vnic_attach_to_network_distributed(nicspec, port_group, logger):
"""
Attach vNIC to a Distributed Port Group network
:param nicspec: <vim.vm.device.VirtualDeviceSpec>
:param port_group: <vim.dvs.DistributedVirtualPortgroup>
:param logger:
:return: updated 'nicspec'
"""
if nicspec and network_is_portgroup(port_group):
network_name = port_group.name
dvs_port_connection = vim.dvs.PortConnection()
dvs_port_connection.portgroupKey = port_group.key
dvs_port_connection.switchUuid = port_group.config.distributedVirtualSwitch.uuid
nicspec.device.backing = vim.vm.device.VirtualEthernetCard.DistributedVirtualPortBackingInfo()
nicspec.device.backing.port = dvs_port_connection
logger.debug(u"Assigning portgroup '{}' for vNIC".format(network_name))
else:
logger.warn(u"Cannot assigning portgroup for vNIC")
return nicspec | Attach vNIC to a Distributed Port Group network
:param nicspec: <vim.vm.device.VirtualDeviceSpec>
:param port_group: <vim.dvs.DistributedVirtualPortgroup>
:param logger:
:return: updated 'nicspec' | entailment |
def vnic_attached_to_network(nicspec, network, logger):
"""
Attach vNIC to Network.
:param nicspec: <vim.vm.device.VirtualDeviceSpec>
:param network: <vim network obj>
:return: updated 'nicspec'
"""
if nicspec:
if network_is_portgroup(network):
return VNicService.vnic_attach_to_network_distributed(nicspec, network,
logger=logger)
elif network_is_standard(network):
return VNicService.vnic_attach_to_network_standard(nicspec, network,
logger=logger)
return None | Attach vNIC to Network.
:param nicspec: <vim.vm.device.VirtualDeviceSpec>
:param network: <vim network obj>
:return: updated 'nicspec' | entailment |
def vnic_add_new_to_vm_task(vm, network, logger):
"""
Compose new vNIC and attach it to VM & connect to Network
:param nicspec: <vim.vm.VM>
:param network: <vim network obj>
:return: <Task>
"""
nicspes = VNicService.vnic_new_attached_to_network(network)
task = VNicService.vnic_add_to_vm_task(nicspes, vm, logger)
return task | Compose new vNIC and attach it to VM & connect to Network
:param nicspec: <vim.vm.VM>
:param network: <vim network obj>
:return: <Task> | entailment |
def map_vnics(vm):
"""
maps the vnic on the vm by name
:param vm: virtual machine
:return: dictionary: {'vnic_name': vnic}
"""
return {device.deviceInfo.label: device
for device in vm.config.hardware.device
if isinstance(device, vim.vm.device.VirtualEthernetCard)} | maps the vnic on the vm by name
:param vm: virtual machine
:return: dictionary: {'vnic_name': vnic} | entailment |
def get_device_spec(vnic, set_connected):
"""
this function creates the device change spec,
:param vnic: vnic
:param set_connected: bool, set as connected or not, default: True
:rtype: device_spec
"""
nic_spec = VNicService.create_vnic_spec(vnic)
VNicService.set_vnic_connectivity_status(nic_spec, to_connect=set_connected)
return nic_spec | this function creates the device change spec,
:param vnic: vnic
:param set_connected: bool, set as connected or not, default: True
:rtype: device_spec | entailment |
def create_vnic_spec(device):
"""
create device spec for existing device and the mode of edit for the vcenter to update
:param device:
:rtype: device spec
"""
nic_spec = vim.vm.device.VirtualDeviceSpec()
nic_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit
nic_spec.device = device
return nic_spec | create device spec for existing device and the mode of edit for the vcenter to update
:param device:
:rtype: device spec | entailment |
def set_vnic_connectivity_status(nic_spec, to_connect):
"""
sets the device spec as connected or disconnected
:param nic_spec: the specification
:param to_connect: bool
"""
nic_spec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
nic_spec.device.connectable.connected = to_connect
nic_spec.device.connectable.startConnected = to_connect | sets the device spec as connected or disconnected
:param nic_spec: the specification
:param to_connect: bool | entailment |
def create_from_params(cls, template_model, datastore_name, vm_cluster_model, ip_regex, refresh_ip_timeout,
auto_power_on, auto_power_off, wait_for_ip, auto_delete):
"""
:param VCenterTemplateModel template_model:
:param str datastore_name:
:param VMClusterModel vm_cluster_model:
:param str ip_regex: Custom regex to filter IP addresses
:param refresh_ip_timeout:
:param bool auto_power_on:
:param bool auto_power_off:
:param bool wait_for_ip:
:param bool auto_delete:
"""
dic = {
'template_model': template_model,
'datastore_name': datastore_name,
'vm_cluster_model': vm_cluster_model,
'ip_regex': ip_regex,
'refresh_ip_timeout': refresh_ip_timeout,
'auto_power_on': auto_power_on,
'auto_power_off': auto_power_off,
'wait_for_ip': wait_for_ip,
'auto_delete': auto_delete
}
return cls(dic) | :param VCenterTemplateModel template_model:
:param str datastore_name:
:param VMClusterModel vm_cluster_model:
:param str ip_regex: Custom regex to filter IP addresses
:param refresh_ip_timeout:
:param bool auto_power_on:
:param bool auto_power_off:
:param bool wait_for_ip:
:param bool auto_delete: | entailment |
def get_current_snapshot_name(vm):
"""
Returns the name of the current snapshot
:param vm: Virtual machine to find current snapshot name
:return: Snapshot name
:rtype str
"""
all_snapshots = SnapshotRetriever.get_vm_snapshots(vm)
# noinspection PyProtectedMember
if not vm.snapshot:
return None
current_snapshot_id = vm.snapshot.currentSnapshot._moId
for snapshot_name in all_snapshots.keys():
# noinspection PyProtectedMember
if all_snapshots[snapshot_name]._moId == current_snapshot_id:
return snapshot_name
return None | Returns the name of the current snapshot
:param vm: Virtual machine to find current snapshot name
:return: Snapshot name
:rtype str | entailment |
def _get_snapshots_recursively(snapshots, snapshot_location):
"""
Recursively traverses child snapshots and returns dictinary of snapshots
:param snapshots: list of snapshots to examine
:param snapshot_location: current path of snapshots
:return: dictinary of snapshot path and snapshot instances
:rtype: dict(str,vim.vm.Snapshot)
"""
snapshot_paths = collections.OrderedDict()
if not snapshots:
return snapshot_paths
for snapshot in snapshots:
if snapshot_location:
current_snapshot_path = SnapshotRetriever.combine(snapshot_location, snapshot.name)
else:
current_snapshot_path = snapshot.name
snapshot_paths[current_snapshot_path] = snapshot.snapshot
child_snapshots = SnapshotRetriever._get_snapshots_recursively(snapshot.childSnapshotList,
current_snapshot_path)
snapshot_paths.update(child_snapshots)
return snapshot_paths | Recursively traverses child snapshots and returns dictinary of snapshots
:param snapshots: list of snapshots to examine
:param snapshot_location: current path of snapshots
:return: dictinary of snapshot path and snapshot instances
:rtype: dict(str,vim.vm.Snapshot) | entailment |
def wait_for_task(self, task, logger, action_name='job', hide_result=False, cancellation_context=None):
"""
Waits and provides updates on a vSphere task
:param cancellation_context: package.cloudshell.cp.vcenter.models.QualiDriverModels.CancellationContext
:param task:
:param action_name:
:param hide_result:
:param logger:
"""
while task.info.state in [vim.TaskInfo.State.running, vim.TaskInfo.State.queued]:
time.sleep(2)
if cancellation_context is not None and task.info.cancelable and cancellation_context.is_cancelled and not task.info.cancelled:
# some times the cancel operation doesn't really cancel the task
# so consider an additional handling of the canceling
task.CancelTask()
logger.info("SynchronousTaskWaiter: task.CancelTask() " + str(task.info.name.info.name))
logger.info("SynchronousTaskWaiter: task.info.cancelled " + str(task.info.cancelled))
logger.info("SynchronousTaskWaiter: task.info.state " + str(task.info.state))
if task.info.state == vim.TaskInfo.State.success:
if task.info.result is not None and not hide_result:
out = '%s completed successfully, result: %s' % (action_name, task.info.result)
logger.info(out)
else:
out = '%s completed successfully.' % action_name
logger.info(out)
else: # error state
multi_msg = ''
if task.info.error.faultMessage:
multi_msg = ', '.join([err.message for err in task.info.error.faultMessage])
elif task.info.error.msg:
multi_msg = task.info.error.msg
logger.info("task execution failed due to: {}".format(multi_msg))
logger.info("task info dump: {0}".format(task.info))
raise TaskFaultException(multi_msg)
return task.info.result | Waits and provides updates on a vSphere task
:param cancellation_context: package.cloudshell.cp.vcenter.models.QualiDriverModels.CancellationContext
:param task:
:param action_name:
:param hide_result:
:param logger: | entailment |
def deploy_from_linked_clone(self, si, logger, data_holder, vcenter_data_model, reservation_id,
cancellation_context):
"""
deploy Cloned VM From VM Command, will deploy vm from a snapshot
:param cancellation_context:
:param si:
:param logger:
:param data_holder:
:param vcenter_data_model:
:param str reservation_id:
:rtype DeployAppResult:
:return:
"""
template_resource_model = data_holder.template_resource_model
return self._deploy_a_clone(si=si,
logger=logger,
app_name=data_holder.app_name,
template_name=template_resource_model.vcenter_vm,
other_params=template_resource_model,
vcenter_data_model=vcenter_data_model,
reservation_id=reservation_id,
cancellation_context=cancellation_context,
snapshot=template_resource_model.vcenter_vm_snapshot) | deploy Cloned VM From VM Command, will deploy vm from a snapshot
:param cancellation_context:
:param si:
:param logger:
:param data_holder:
:param vcenter_data_model:
:param str reservation_id:
:rtype DeployAppResult:
:return: | entailment |
def deploy_clone_from_vm(self, si, logger, data_holder, vcenter_data_model, reservation_id, cancellation_context):
"""
deploy Cloned VM From VM Command, will deploy vm from another vm
:param cancellation_context:
:param reservation_id:
:param si:
:param logger:
:type data_holder:
:type vcenter_data_model:
:rtype DeployAppResult:
:return:
"""
template_resource_model = data_holder.template_resource_model
return self._deploy_a_clone(si,
logger,
data_holder.app_name,
template_resource_model.vcenter_vm,
template_resource_model,
vcenter_data_model,
reservation_id,
cancellation_context) | deploy Cloned VM From VM Command, will deploy vm from another vm
:param cancellation_context:
:param reservation_id:
:param si:
:param logger:
:type data_holder:
:type vcenter_data_model:
:rtype DeployAppResult:
:return: | entailment |
def deploy_from_template(self, si, logger, data_holder, vcenter_data_model, reservation_id, cancellation_context):
"""
:param cancellation_context:
:param reservation_id:
:param si:
:param logger:
:type data_holder: DeployFromTemplateDetails
:type vcenter_data_model
:rtype DeployAppResult:
:return:
"""
template_resource_model = data_holder.template_resource_model
return self._deploy_a_clone(si,
logger,
data_holder.app_name,
template_resource_model.vcenter_template,
template_resource_model,
vcenter_data_model,
reservation_id,
cancellation_context) | :param cancellation_context:
:param reservation_id:
:param si:
:param logger:
:type data_holder: DeployFromTemplateDetails
:type vcenter_data_model
:rtype DeployAppResult:
:return: | entailment |
def _deploy_a_clone(self, si, logger, app_name, template_name, other_params, vcenter_data_model, reservation_id,
cancellation_context,
snapshot=''):
"""
:rtype DeployAppResult:
"""
# generate unique name
vm_name = self.name_generator(app_name, reservation_id)
VCenterDetailsFactory.set_deplyment_vcenter_params(
vcenter_resource_model=vcenter_data_model, deploy_params=other_params)
template_name = VMLocation.combine([other_params.default_datacenter,
template_name])
params = self.pv_service.CloneVmParameters(si=si,
template_name=template_name,
vm_name=vm_name,
vm_folder=other_params.vm_location,
datastore_name=other_params.vm_storage,
cluster_name=other_params.vm_cluster,
resource_pool=other_params.vm_resource_pool,
power_on=False,
snapshot=snapshot)
if cancellation_context.is_cancelled:
raise Exception("Action 'Clone VM' was cancelled.")
clone_vm_result = self.pv_service.clone_vm(clone_params=params, logger=logger,
cancellation_context=cancellation_context)
if clone_vm_result.error:
raise Exception(clone_vm_result.error)
# remove a new created vm due to cancellation
if cancellation_context.is_cancelled:
self.pv_service.destroy_vm(vm=clone_vm_result.vm, logger=logger)
raise Exception("Action 'Clone VM' was cancelled.")
vm_details_data = self._safely_get_vm_details(clone_vm_result.vm, vm_name, vcenter_data_model, other_params,
logger)
return DeployAppResult(vmName=vm_name,
vmUuid=clone_vm_result.vm.summary.config.uuid,
vmDetailsData=vm_details_data,
deployedAppAdditionalData={'ip_regex': other_params.ip_regex,
'refresh_ip_timeout': other_params.refresh_ip_timeout,
'auto_power_off': convert_to_bool(other_params.auto_power_off),
'auto_delete': convert_to_bool(other_params.auto_delete)}) | :rtype DeployAppResult: | entailment |
def _get_deploy_image_params(data_holder, host_info, vm_name):
"""
:type data_holder: models.vCenterVMFromImageResourceModel.vCenterVMFromImageResourceModel
"""
image_params = OvfImageParams()
if hasattr(data_holder, 'vcenter_image_arguments') and data_holder.vcenter_image_arguments:
image_params.user_arguments = data_holder.vcenter_image_arguments
if hasattr(data_holder, 'vm_location') and data_holder.vm_location:
image_params.vm_folder = data_holder.vm_location.replace(data_holder.default_datacenter + '/', '')
image_params.cluster = data_holder.vm_cluster
image_params.resource_pool = data_holder.vm_resource_pool
image_params.connectivity = host_info
image_params.vm_name = vm_name
image_params.datastore = data_holder.vm_storage
image_params.datacenter = data_holder.default_datacenter
image_params.image_url = data_holder.vcenter_image
image_params.power_on = False
image_params.vcenter_name = data_holder.vcenter_name
return image_params | :type data_holder: models.vCenterVMFromImageResourceModel.vCenterVMFromImageResourceModel | entailment |
def get_details(self):
"""
:rtype list[VmDataField]
"""
data = []
if isinstance(self.model, vCenterCloneVMFromVMResourceModel):
data.append(VmDetailsProperty(key='Cloned VM Name', value=self.model.vcenter_vm))
if isinstance(self.model, VCenterDeployVMFromLinkedCloneResourceModel):
template = self.model.vcenter_vm
snapshot = self.model.vcenter_vm_snapshot
data.append(VmDetailsProperty(key='Cloned VM Name',value= '{0} (snapshot: {1})'.format(template, snapshot)))
if isinstance(self.model, vCenterVMFromImageResourceModel):
data.append(VmDetailsProperty(key='Base Image Name', value=self.model.vcenter_image.split('/')[-1]))
if isinstance(self.model, vCenterVMFromTemplateResourceModel):
data.append(VmDetailsProperty(key='Template Name', value=self.model.vcenter_template))
return data | :rtype list[VmDataField] | entailment |
def convert_to_resource_model(self, attributes, resource_model_type):
"""
Converts an instance of resource with dictionary of attributes
to a class instance according to family and assigns its properties
:type attributes: dict
:param resource_model_type: Resource Model type to create
:return:
"""
if resource_model_type:
if not callable(resource_model_type):
raise ValueError('resource_model_type {0} cannot be instantiated'.format(resource_model_type))
instance = resource_model_type()
else:
raise ValueError('resource_model_type must have a value')
props = ResourceModelParser.get_public_properties(instance)
for attrib in attributes:
property_name = ResourceModelParser.get_property_name_from_attribute_name(attrib)
property_name_for_attribute_name = ResourceModelParser.get_property_name_with_attribute_name_postfix(attrib)
if props.__contains__(property_name):
value = attributes[attrib]
setattr(instance, property_name, value)
if hasattr(instance, property_name_for_attribute_name):
setattr(instance, property_name_for_attribute_name, attrib)
props.remove(property_name_for_attribute_name)
props.remove(property_name)
if props:
raise ValueError('Property(ies) {0} not found on resource with attributes {1}'
.format(','.join(props),
','.join(attributes)))
if hasattr(instance, 'vcenter_vm'):
instance.vcenter_vm = back_slash_to_front_converter(instance.vcenter_vm)
if hasattr(instance, 'vcenter_vm_snapshot'):
instance.vcenter_vm_snapshot = back_slash_to_front_converter(instance.vcenter_vm_snapshot)
return instance | Converts an instance of resource with dictionary of attributes
to a class instance according to family and assigns its properties
:type attributes: dict
:param resource_model_type: Resource Model type to create
:return: | entailment |
def create_resource_model_instance(resource_instance):
"""
Create an instance of class named *ResourceModel
from models folder according to ResourceModelName of a resource
:param resource_instance: Resource with ResourceModelName property
:return: instance of ResourceModel class
"""
resource_model = ResourceModelParser.get_resource_model(resource_instance)
resource_class_name = ResourceModelParser.get_resource_model_class_name(
resource_model)
# print 'Family name is ' + resource_class_name
instance = ResourceModelParser.get_class('cloudshell.cp.vcenter.models.' + resource_class_name)
return instance | Create an instance of class named *ResourceModel
from models folder according to ResourceModelName of a resource
:param resource_instance: Resource with ResourceModelName property
:return: instance of ResourceModel class | entailment |
def get_class(class_path):
"""
Returns an instance of a class by its class_path.
:param class_path: contains modules and class name with dot delimited
:return: Any
"""
module_path, class_name = class_path.rsplit(".", 1)
try:
module = __import__(class_path, fromlist=[class_name])
except ImportError:
raise ValueError('Class {0} could not be imported'.format(class_path))
try:
cls = getattr(module, class_name)
except AttributeError:
raise ValueError("Module '%s' has no class '%s'" % (module_path, class_name,))
try:
instance = cls()
except TypeError as type_error:
raise ValueError('Failed to instantiate class {0}. Error: {1}'.format(class_name, type_error.message))
return instance | Returns an instance of a class by its class_path.
:param class_path: contains modules and class name with dot delimited
:return: Any | entailment |
def get_property_name_from_attribute_name(attribute):
"""
Returns property name from attribute name
:param attribute: Attribute name, may contain upper and lower case and spaces
:return: string
"""
if isinstance(attribute, str) or isinstance(attribute, unicode):
attribute_name = attribute
elif hasattr(attribute, 'Name'):
attribute_name = attribute.Name
else:
raise Exception('Attribute type {0} is not supported'.format(str(type(attribute))))
return attribute_name.lower().replace(' ', '_') | Returns property name from attribute name
:param attribute: Attribute name, may contain upper and lower case and spaces
:return: string | entailment |
def crc32File(filename, skip=0):
"""Computes the CRC-32 of the contents of filename, optionally
skipping a certain number of bytes at the beginning of the file.
"""
with open(filename, 'rb') as stream:
discard = stream.read(skip)
return zlib.crc32(stream.read()) & 0xffffffff | Computes the CRC-32 of the contents of filename, optionally
skipping a certain number of bytes at the beginning of the file. | entailment |
def endianSwapU16(bytes):
"""Swaps pairs of bytes (16-bit words) in the given bytearray."""
for b in range(0, len(bytes), 2):
bytes[b], bytes[b + 1] = bytes[b + 1], bytes[b]
return bytes | Swaps pairs of bytes (16-bit words) in the given bytearray. | entailment |
def setDictDefaults (d, defaults):
"""Sets all defaults for the given dictionary to those contained in a
second defaults dictionary. This convenience method calls:
d.setdefault(key, value)
for each key and value in the given defaults dictionary.
"""
for key, val in defaults.items():
d.setdefault(key, val)
return d | Sets all defaults for the given dictionary to those contained in a
second defaults dictionary. This convenience method calls:
d.setdefault(key, value)
for each key and value in the given defaults dictionary. | entailment |
def getDefaultDict(modname, config_key, loader, reload=False, filename=None):
"""Returns default AIT dictonary for modname
This helper function encapulates the core logic necessary to
(re)load, cache (via util.ObjectCache), and return the default
dictionary. For example, in ait.core.cmd:
def getDefaultDict(reload=False):
return ait.util.getDefaultDict(__name__, 'cmddict', CmdDict, reload)
"""
module = sys.modules[modname]
default = getattr(module, 'DefaultDict', None)
if filename is None:
filename = ait.config.get('%s.filename' % config_key, None)
if filename is not None and (default is None or reload is True):
try:
default = ObjectCache(filename, loader).load()
setattr(module, 'DefaultDict', default)
except IOError, e:
msg = 'Could not load default %s "%s": %s'
log.error(msg, config_key, filename, str(e))
return default or loader() | Returns default AIT dictonary for modname
This helper function encapulates the core logic necessary to
(re)load, cache (via util.ObjectCache), and return the default
dictionary. For example, in ait.core.cmd:
def getDefaultDict(reload=False):
return ait.util.getDefaultDict(__name__, 'cmddict', CmdDict, reload) | entailment |
def toBCD (n):
"""Converts the number n into Binary Coded Decimal."""
bcd = 0
bits = 0
while True:
n, r = divmod(n, 10)
bcd |= (r << bits)
if n is 0:
break
bits += 4
return bcd | Converts the number n into Binary Coded Decimal. | entailment |
def toFloat (str, default=None):
"""toFloat(str[, default]) -> float | default
Converts the given string to a floating-point value. If the
string could not be converted, default (None) is returned.
NOTE: This method is *significantly* more effecient than
toNumber() as it only attempts to parse floating-point numbers,
not integers or hexadecimal numbers.
Examples:
>>> f = toFloat("4.2")
>>> assert type(f) is float and f == 4.2
>>> f = toFloat("UNDEFINED", 999.9)
>>> assert type(f) is float and f == 999.9
>>> f = toFloat("Foo")
>>> assert f is None
"""
value = default
try:
value = float(str)
except ValueError:
pass
return value | toFloat(str[, default]) -> float | default
Converts the given string to a floating-point value. If the
string could not be converted, default (None) is returned.
NOTE: This method is *significantly* more effecient than
toNumber() as it only attempts to parse floating-point numbers,
not integers or hexadecimal numbers.
Examples:
>>> f = toFloat("4.2")
>>> assert type(f) is float and f == 4.2
>>> f = toFloat("UNDEFINED", 999.9)
>>> assert type(f) is float and f == 999.9
>>> f = toFloat("Foo")
>>> assert f is None | entailment |
def toNumber (str, default=None):
"""toNumber(str[, default]) -> integer | float | default
Converts the given string to a numeric value. The string may be a
hexadecimal, integer, or floating number. If string could not be
converted, default (None) is returned.
Examples:
>>> n = toNumber("0x2A")
>>> assert type(n) is int and n == 42
>>> n = toNumber("42")
>>> assert type(n) is int and n == 42
>>> n = toNumber("42.0")
>>> assert type(n) is float and n == 42.0
>>> n = toNumber("Foo", 42)
>>> assert type(n) is int and n == 42
>>> n = toNumber("Foo")
>>> assert n is None
"""
value = default
try:
if str.startswith("0x"):
value = int(str, 16)
else:
try:
value = int(str)
except ValueError:
value = float(str)
except ValueError:
pass
return value | toNumber(str[, default]) -> integer | float | default
Converts the given string to a numeric value. The string may be a
hexadecimal, integer, or floating number. If string could not be
converted, default (None) is returned.
Examples:
>>> n = toNumber("0x2A")
>>> assert type(n) is int and n == 42
>>> n = toNumber("42")
>>> assert type(n) is int and n == 42
>>> n = toNumber("42.0")
>>> assert type(n) is float and n == 42.0
>>> n = toNumber("Foo", 42)
>>> assert type(n) is int and n == 42
>>> n = toNumber("Foo")
>>> assert n is None | entailment |
def toRepr (obj):
"""toRepr(obj) -> string
Converts the Python object to a string representation of the kind
often returned by a class __repr__() method.
"""
args = [ ]
names = [ ]
if hasattr(obj, "__dict__"):
names += getattr(obj, "__dict__").keys()
if hasattr(obj, "__slots__"):
names += getattr(obj, "__slots__")
for name in names:
value = getattr(obj, name)
if value is not None:
if type(value) is str:
if len(value) > 32:
value = value[0:32] + "..."
value = "'" + value + "'"
args.append("%s=%s" % (name, str(value)))
return "%s(%s)" % (obj.__class__.__name__, ", ".join(args)) | toRepr(obj) -> string
Converts the Python object to a string representation of the kind
often returned by a class __repr__() method. | entailment |
def toStringDuration (duration):
"""Returns a description of the given duration in the most appropriate
units (e.g. seconds, ms, us, or ns).
"""
table = (
('%dms' , 1e-3, 1e3),
(u'%d\u03BCs', 1e-6, 1e6),
('%dns' , 1e-9, 1e9)
)
if duration > 1:
return '%fs' % duration
for format, threshold, factor in table:
if duration > threshold:
return format % int(duration * factor)
return '%fs' % duration | Returns a description of the given duration in the most appropriate
units (e.g. seconds, ms, us, or ns). | entailment |
def expandPath (pathname, prefix=None):
"""Return pathname as an absolute path, either expanded by the users
home directory ("~") or with prefix prepended.
"""
if prefix is None:
prefix = ''
expanded = pathname
if pathname[0] == '~':
expanded = os.path.expanduser(pathname)
elif pathname[0] != '/':
expanded = os.path.join(prefix, pathname)
return os.path.abspath(expanded) | Return pathname as an absolute path, either expanded by the users
home directory ("~") or with prefix prepended. | entailment |
def listAllFiles (directory, suffix=None, abspath=False):
"""Returns the list of all files within the input directory and
all subdirectories.
"""
files = []
directory = expandPath(directory)
for dirpath, dirnames, filenames in os.walk(directory, followlinks=True):
if suffix:
filenames = [f for f in filenames if f.endswith(suffix)]
for filename in filenames:
filepath = os.path.join(dirpath, filename)
if not abspath:
filepath = os.path.relpath(filepath, start=directory)
# os.path.join(path, filename)
files.append(filepath)
return files | Returns the list of all files within the input directory and
all subdirectories. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.