code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
resource_details = self._parse_remote_model(context) res = self.command_wrapper.execute_command_with_connection(context, self.snapshots_retriever.get_snapshots, ...
def get_snapshots(self, context)
Returns list of snapshots :param context: resource context of the vCenterShell :type context: models.QualiDriverModels.ResourceCommandContext :return:
9.480129
8.373143
1.132207
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_...
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: SavedRes...
4.541721
4.182028
1.086009
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
def get_vcenter_data_model(self, api, vcenter_name)
:param api: :param str vcenter_name: :rtype: VMwarevCenterResourceModel
3.692564
3.206009
1.151763
try: if not string or not isinstance(string, str): return string return string.replace('\\', '/') except Exception: return string
def back_slash_to_front_converter(string)
Replacing all \ in the str to / :param string: single string to modify :type string: str
3.479441
3.504575
0.992828
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
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
2.995366
3.26314
0.91794
if full_name: parts = full_name.split("/") return ("/".join(parts[0:-1]), parts[-1]) if len(parts) > 1 else ("/", full_name) return None, None
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)
2.492516
2.800532
0.890015
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....
def get_details(self)
:rtype list[VmDataField]
3.299069
3.115344
1.058975
# 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_reso...
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
2.073892
2.068945
1.002391
return self.command_orchestrator.save_snapshot(context, snapshot_name, save_memory)
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...
6.258298
8.212784
0.762019
return self.command_orchestrator.restore_snapshot(context, snapshot_name)
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[s...
9.07338
11.857091
0.765228
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_dat...
def connect_bulk(self, si, logger, vcenter_data_model, request)
:param si: :param logger: :param VMwarevCenterResourceModel vcenter_data_model: :param request: :return:
3.644402
3.579111
1.018242
# 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: # des...
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:
4.373822
4.135867
1.057535
# 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) ...
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:
5.331462
5.390484
0.989051
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: ...
def _disconnect_all_my_connectors(session, resource_name, reservation_id, logger)
:param CloudShellAPISession session: :param str resource_name: :param str reservation_id:
2.344548
2.243307
1.04513
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(delet...
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...
5.649245
5.227946
1.080586
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, cancell...
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:
3.05149
3.204451
0.952266
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_con...
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:
3.150742
3.177344
0.991627
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_...
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 ...
2.944613
2.975138
0.98974
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
def _create_snapshot(logger, snapshot_name, vm, save_vm_memory_to_snapshot)
:type save_vm_memory_to_snapshot: bool
5.55536
5.182626
1.07192
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
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
2.474913
2.541048
0.973974
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) ...
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 net...
3.177957
3.078268
1.032385
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() ...
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 Non...
1.912216
1.95446
0.978386
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, ...
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' tur...
3.889214
3.633335
1.070425
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.VmwareDistributedVirtual...
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_port...
1.636022
1.676928
0.975607
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 retur...
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
1.380087
1.3973
0.987682
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_r...
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_...
3.933591
3.960597
0.993181
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 ...
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
4.413745
4.581073
0.963474
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_mach...
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:
3.144343
3.170637
0.991707
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, pyvm...
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 Netw...
5.043393
4.191407
1.20327
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'): ...
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:
2.568264
2.204024
1.165261
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...
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.VirtualDevi...
1.622883
1.567532
1.035311
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.d...
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'
2.317791
2.268218
1.021855
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.u...
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'
2.613271
2.483578
1.05222
if nicspec: if network_is_portgroup(network): return VNicService.vnic_attach_to_network_distributed(nicspec, network, logger=logger) elif network_is_standard(network): return V...
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'
3.512875
3.562927
0.985952
nicspes = VNicService.vnic_new_attached_to_network(network) task = VNicService.vnic_add_to_vm_task(nicspes, vm, logger) return task
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>
6.390323
6.152475
1.038659
return {device.deviceInfo.label: device for device in vm.config.hardware.device if isinstance(device, vim.vm.device.VirtualEthernetCard)}
def map_vnics(vm)
maps the vnic on the vm by name :param vm: virtual machine :return: dictionary: {'vnic_name': vnic}
4.326568
3.833447
1.128637
nic_spec = VNicService.create_vnic_spec(vnic) VNicService.set_vnic_connectivity_status(nic_spec, to_connect=set_connected) return nic_spec
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
4.779541
5.216678
0.916204
nic_spec = vim.vm.device.VirtualDeviceSpec() nic_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit nic_spec.device = device return nic_spec
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
1.72882
1.914551
0.90299
nic_spec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo() nic_spec.device.connectable.connected = to_connect nic_spec.device.connectable.startConnected = to_connect
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
2.071785
2.752697
0.752638
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_pow...
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 wa...
1.339897
1.38849
0.965003
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 PyProtectedMe...
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
3.435212
3.313652
1.036685
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: ...
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)
2.52891
2.399143
1.054089
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 does...
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:
2.952711
2.923599
1.009958
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.vcen...
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:
3.002323
3.120646
0.962084
template_resource_model = data_holder.template_resource_model return self._deploy_a_clone(si, logger, data_holder.app_name, template_resource_model.vcenter_vm, ...
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:
3.409756
3.580716
0.952255
template_resource_model = data_holder.template_resource_model return self._deploy_a_clone(si, logger, data_holder.app_name, template_resource_model.vcenter_template, ...
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:
3.492389
3.528125
0.989871
# 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_datace...
def _deploy_a_clone(self, si, logger, app_name, template_name, other_params, vcenter_data_model, reservation_id, cancellation_context, snapshot='')
:rtype DeployAppResult:
3.223777
3.093324
1.042172
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...
def _get_deploy_image_params(data_holder, host_info, vm_name)
:type data_holder: models.vCenterVMFromImageResourceModel.vCenterVMFromImageResourceModel
2.361014
2.273675
1.038413
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 ...
def get_details(self)
:rtype list[VmDataField]
3.253311
3.052543
1.065771
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...
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:
2.645956
2.632444
1.005133
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...
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
4.250938
4.219394
1.007476
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)...
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
2.200082
2.302682
0.955443
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)))) ...
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
2.682622
2.829613
0.948053
with open(filename, 'rb') as stream: discard = stream.read(skip) return zlib.crc32(stream.read()) & 0xffffffff
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.
3.347776
3.563209
0.93954
for b in range(0, len(bytes), 2): bytes[b], bytes[b + 1] = bytes[b + 1], bytes[b] return bytes
def endianSwapU16(bytes)
Swaps pairs of bytes (16-bit words) in the given bytearray.
1.925189
1.945349
0.989637
for key, val in defaults.items(): d.setdefault(key, val) return d
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.
3.942927
4.970712
0.793232
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...
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',...
3.316932
3.252609
1.019776
bcd = 0 bits = 0 while True: n, r = divmod(n, 10) bcd |= (r << bits) if n is 0: break bits += 4 return bcd
def toBCD (n)
Converts the number n into Binary Coded Decimal.
3.310107
3.453487
0.958482
value = default try: value = float(str) except ValueError: pass return value
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 o...
3.747239
15.676521
0.239035
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
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 ...
2.301809
3.621642
0.63557
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:...
def toRepr (obj)
toRepr(obj) -> string Converts the Python object to a string representation of the kind often returned by a class __repr__() method.
2.194276
2.18277
1.005271
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) re...
def toStringDuration (duration)
Returns a description of the given duration in the most appropriate units (e.g. seconds, ms, us, or ns).
3.856036
3.616676
1.066182
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)
def expandPath (pathname, prefix=None)
Return pathname as an absolute path, either expanded by the users home directory ("~") or with prefix prepended.
2.370077
2.269759
1.044198
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) ...
def listAllFiles (directory, suffix=None, abspath=False)
Returns the list of all files within the input directory and all subdirectories.
2.207113
2.163506
1.020156
return not os.path.exists(self.cachename) or \ (os.path.getmtime(self.filename) > os.path.getmtime(self.cachename))
def dirty(self)
True if the cache needs to be updated, False otherwise
4.182891
3.596812
1.162944
msg = 'Saving updates from more recent "%s" to "%s"' log.info(msg, self.filename, self.cachename) with open(self.cachename, 'wb') as output: cPickle.dump(self._dict, output, -1)
def cache(self)
Caches the result of loader(filename) to cachename.
6.061164
4.698159
1.290115
if self._dict is None: if self.dirty: self._dict = self._loader(self.filename) self.cache() else: with open(self.cachename, 'rb') as stream: self._dict = cPickle.load(stream) return self._dict
def load(self)
Loads the Python object Loads the Python object, either via loader(filename) or the pickled cache file, whichever was modified most recently.
4.099555
3.620163
1.132423
try: split = input_data[1:-1].split(',', 1) uid, pkt = int(split[0]), split[1] defn = self.packet_dict[uid] decoded = tlm.Packet(defn, data=bytearray(pkt)) self.dbconn.insert(decoded, **kwargs) except Exception as e: log.er...
def process(self, input_data, topic=None, **kwargs)
Splits tuple received from PacketHandler into packet UID and packet message. Decodes packet and inserts into database backend. Logs any exceptions raised. Params: input_data: message received from inbound stream through PacketHandler topic: name of inbound stream ...
7.109387
5.794784
1.22686
utc = datetime.datetime.utcnow() ts_sec = calendar.timegm( utc.timetuple() ) ts_usec = utc.microsecond return ts_sec, ts_usec
def getTimestampUTC()
getTimestampUTC() -> (ts_sec, ts_usec) Returns the current UTC time in seconds and microseconds.
2.864512
2.754554
1.039919
return (datetime.datetime.utcnow() + datetime.timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds)).strftime(DOY_Format)
def getUTCDatetimeDOY(days=0, hours=0, minutes=0, seconds=0)
getUTCDatetimeDOY -> datetime Returns the UTC current datetime with the input timedelta arguments (days, hours, minutes, seconds) added to current date. Returns ISO-8601 datetime format for day of year: YYYY-DDDTHH:mm:ssZ
3.079214
4.290308
0.717714
end = datetime.datetime.now() return totalSeconds( end - TICs.pop() ) if len(TICs) else None
def toc()
toc() -> float | None Returns the total elapsed seconds since the most recent tic(), or None if tic() was not called. Examples: >>> import time >>> tic() >>> time.sleep(1.2) >>> elapsed = toc() >>> assert abs(elapsed - 1.2) <= 1e-2 .. note:: The tic() and toc() functions are si...
16.348034
17.592407
0.929266
if timestamp is None: timestamp = datetime.datetime.utcnow() leap = LeapSeconds.get_GPS_offset_for_date(timestamp) secsInWeek = 604800 delta = totalSeconds(timestamp - GPS_Epoch) + leap seconds = delta % secsInWeek week = int( math.floor(delta / secsInWeek) ) re...
def toGPSWeekAndSecs(timestamp=None)
Converts the given UTC timestamp (defaults to the current time) to a two-tuple, (GPS week number, GPS seconds within the week).
4.246812
4.291832
0.98951
if dt is None or type(dt) is datetime.datetime: jd = toJulian(dt) else: jd = dt tUT1 = (jd - 2451545.0) / 36525.0 gmst = 67310.54841 + (876600 * 3600 + 8640184.812866) * tUT1 gmst += 0.093104 * tUT1**2 gmst -= 6.2e-6 * tUT1**3 # Convert from seconds to degrees, i.e...
def toGMST(dt=None)
Converts the given Python datetime or Julian date (float) to Greenwich Mean Sidereal Time (GMST) (in radians) using the formula from D.A. Vallado (2004). See: D.A. Vallado, Fundamentals of Astrodynamics and Applications, p. 192 http://books.google.com/books?id=PJLlWzMBKjkC&lpg=PA956&vq=192...
2.610631
2.761202
0.945469
if dt is None: dt = datetime.datetime.utcnow() if dt.month < 3: year = dt.year - 1 month = dt.month + 12 else: year = dt.year month = dt.month A = int(year / 100.0) B = 2 - A + int(A / 4.0) C = ( (dt.second / 60.0 + dt.minute) / 60.0 + dt....
def toJulian(dt=None)
Converts a Python datetime to a Julian date, using the formula from Meesus (1991). This formula is reproduced in D.A. Vallado (2004). See: D.A. Vallado, Fundamentals of Astrodynamics and Applications, p. 187 http://books.google.com/books?id=PJLlWzMBKjkC&lpg=PA956&vq=187&pg=PA187
1.905927
1.977956
0.963584
delta = datetime.timedelta(seconds=seconds, microseconds=microseconds) return GPS_Epoch + delta
def toLocalTime(seconds, microseconds=0)
toLocalTime(seconds, microseconds=0) -> datetime Converts the given number of seconds since the GPS Epoch (midnight on January 6th, 1980) to this computer's local time. Returns a Python datetime object. Examples: >>> toLocalTime(0) datetime.datetime(1980, 1, 6, 0, 0) >>> toLocalTime(25 ...
6.233871
11.521828
0.541049
if hasattr(td, "total_seconds"): ts = td.total_seconds() else: ts = (td.microseconds + (td.seconds + td.days * 24 * 3600.0) * 1e6) / 1e6 return ts
def totalSeconds(td)
totalSeconds(td) -> float Return the total number of seconds contained in the given Python datetime.timedelta object. Python 2.6 and earlier do not have timedelta.total_seconds(). Examples: >>> totalSeconds( toLocalTime(86400.123) - toLocalTime(0.003) ) 86400.12
1.937795
2.373408
0.816461
log.info('Attempting to acquire latest leapsecond data') ls_file = ait.config.get( 'leapseconds.filename', os.path.join(ait.config._directory, _DEFAULT_FILE_NAME) ) url = 'https://www.ietf.org/timezones/data/leap-seconds.list' r = requests.get(...
def _update_leap_second_data(self)
Updates the systems leap second information Pulls the latest leap second information from https://www.ietf.org/timezones/data/leap-seconds.list and updates the leapsecond config file. Raises: ValueError: If the connection to IETF does not return 200 IOError: If ...
3.121181
2.743747
1.137562
for greenlet in (self.greenlets + self.servers): log.info("Starting {} greenlet...".format(greenlet)) greenlet.start() gevent.joinall(self.greenlets)
def wait(self)
Starts all greenlets for concurrent processing. Joins over all greenlets that are not servers.
5.400317
3.557728
1.517912
common_err_msg = 'No valid {} stream configurations found. ' specific_err_msg = {'inbound': 'No data will be received (or displayed).', 'outbound': 'No data will be published.'} err_msgs = {} for stream_type in ['inbound', 'outbound']: er...
def _load_streams(self)
Reads, parses and creates streams specified in config.yaml.
2.909721
2.852643
1.020009
if config is None: raise ValueError('No stream config to create stream from.') name = self._get_stream_name(config) stream_handlers = self._get_stream_handlers(config, name) stream_input = config.get('input', None) if stream_input is None: raise(...
def _create_inbound_stream(self, config=None)
Creates an inbound stream from its config. Params: config: stream configuration as read by ait.config Returns: stream: a Stream Raises: ValueError: if any of the required config values are missing
3.104889
2.949901
1.05254
if config is None: raise ValueError('No stream config to create stream from.') name = self._get_stream_name(config) stream_handlers = self._get_stream_handlers(config, name) stream_input = config.get('input', None) stream_output = config.get('output', None) ...
def _create_outbound_stream(self, config=None)
Creates an outbound stream from its config. Params: config: stream configuration as read by ait.config Returns: stream: a Stream Raises: ValueError: if any of the required config values are missing
2.723496
2.72413
0.999768
if config is None: raise ValueError('No handler config to create handler from.') if 'name' not in config: raise ValueError('Handler name is required.') handler_name = config['name'] # try to create handler module_name = handler_name.rsplit('.', ...
def _create_handler(self, config)
Creates a handler from its config. Params: config: handler config Returns: handler instance
2.504231
2.418363
1.035507
plugins = ait.config.get('server.plugins') if plugins is None: log.warn('No plugins specified in config.') else: for index, p in enumerate(plugins): try: plugin = self._create_plugin(p['plugin']) self.plugi...
def _load_plugins(self)
Reads, parses and creates plugins specified in config.yaml.
3.849526
3.660264
1.051707
if config is None: raise ValueError('No plugin config to create plugin from.') name = config.pop('name', None) if name is None: raise(cfg.AitConfigMissing('plugin name')) # TODO I don't think we actually care about this being unique? Left over from ...
def _create_plugin(self, config)
Creates a plugin from its config. Params: config: plugin configuration as read by ait.config Returns: plugin: a Plugin Raises: ValueError: if any of the required config values are missing
4.20942
4.131343
1.018899
if slots is None: slots = list(obj.__slots__) if hasattr(obj, '__slots__') else [ ] for base in obj.__class__.__bases__: if hasattr(base, '__slots__'): slots.extend(base.__slots__) testOmit = hasattr(obj, '__jsonOmit__') and callable(obj.__jsonOmit__) result...
def slotsToJSON(obj, slots=None)
Converts the given Python object to one suitable for Javascript Object Notation (JSON) serialization via :func:`json.dump` or :func:`json.dumps`. This function delegates to :func:`toJSON`. Specifically only attributes in the list of *slots* are converted. If *slots* is not provided, it defaults to the...
2.826108
2.596214
1.08855
if hasattr(obj, 'toJSON') and callable(obj.toJSON): result = obj.toJSON() elif isinstance(obj, (int, long, float, str, unicode)) or obj is None: result = obj elif isinstance(obj, collections.Mapping): result = { toJSON(key): toJSON(obj[key]) for key in obj } elif isinstance(...
def toJSON (obj)
Converts the given Python object to one suitable for Javascript Object Notation (JSON) serialization via :func:`json.dump` or :func:`json.dumps`. If the Python object has a :meth:`toJSON` method, it is always given preference and will be called to peform the conversion. Otherwise, plain mapping an...
1.985588
1.84817
1.074353
'''Loops ait.config._datapaths from AIT_CONFIG and creates a directory. Replaces year and doy with the respective year and day-of-year. If neither are given as arguments, current UTC day and year are used. Args: paths: [optional] list of directory paths you would like to create. ...
def createDirStruct(paths, verbose=True)
Loops ait.config._datapaths from AIT_CONFIG and creates a directory. Replaces year and doy with the respective year and day-of-year. If neither are given as arguments, current UTC day and year are used. Args: paths: [optional] list of directory paths you would like to create. ...
6.773586
1.946791
3.479359
''' Write packet data to the logger's log file. ''' data = self.socket.recv(self._buffer_size) for h in self.capture_handlers: h['reads'] += 1 h['data_read'] += len(data) d = data if 'pre_write_transforms' in h: for data_transform...
def capture_packet(self)
Write packet data to the logger's log file.
5.327438
4.570692
1.165565
''' Clean up the socket and log file handles. ''' self.socket.close() for h in self.capture_handlers: h['logger'].close()
def clean_up(self)
Clean up the socket and log file handles.
11.567408
7.26323
1.592598
''' Monitor the socket and log captured data. ''' try: while True: gevent.socket.wait_read(self.socket.fileno()) self._handle_log_rotations() self.capture_packet() finally: self.clean_up()
def socket_monitor_loop(self)
Monitor the socket and log captured data.
8.155767
6.704681
1.216429
''' Add an additional handler Args: handler: A dictionary of handler configuration for the handler that should be added. See :func:`__init__` for details on valid parameters. ''' handler['logger'] = self._get_logger(handler) ...
def add_handler(self, handler)
Add an additional handler Args: handler: A dictionary of handler configuration for the handler that should be added. See :func:`__init__` for details on valid parameters.
7.28268
3.537246
2.058856
''' Remove a handler given a name Note, if multiple handlers have the same name the last matching instance in the handler list will be removed. Args: name: The name of the handler to remove ''' index = None for i, h in enumerate(self....
def remove_handler(self, name)
Remove a handler given a name Note, if multiple handlers have the same name the last matching instance in the handler list will be removed. Args: name: The name of the handler to remove
3.641441
2.292212
1.588614
''' Return capture handler configuration data. Return a dictionary of capture handler configuration data of the form: .. code-block:: none [{ 'handler': <handler configuration dictionary>, 'log_file_path': <Path to the current log file that the log...
def dump_handler_config_data(self)
Return capture handler configuration data. Return a dictionary of capture handler configuration data of the form: .. code-block:: none [{ 'handler': <handler configuration dictionary>, 'log_file_path': <Path to the current log file that the logger ...
5.847494
1.99967
2.924229
''' Return handler capture statistics Return a dictionary of capture handler statistics of the form: .. code-block:: none [{ 'name': The handler's name, 'reads': The number of packet reads this handler has received 'data_read_lengt...
def dump_all_handler_stats(self)
Return handler capture statistics Return a dictionary of capture handler statistics of the form: .. code-block:: none [{ 'name': The handler's name, 'reads': The number of packet reads this handler has received 'data_read_length': The tota...
3.88625
2.036535
1.908266
''' Rotate each handler's log file if necessary ''' for h in self.capture_handlers: if self._should_rotate_log(h): self._rotate_log(h)
def _handle_log_rotations(self)
Rotate each handler's log file if necessary
7.64778
5.156182
1.483225
''' Determine if a log file rotation is necessary ''' if handler['rotate_log']: rotate_time_index = handler.get('rotate_log_index', 'day') try: rotate_time_index = self._decode_time_rotation_index(rotate_time_index) except ValueError: r...
def _should_rotate_log(self, handler)
Determine if a log file rotation is necessary
3.693536
3.583366
1.030745
''' Return the time struct index to use for log rotation checks ''' time_index_decode_table = { 'year': 0, 'years': 0, 'tm_year': 0, 'month': 1, 'months': 1, 'tm_mon': 1, 'day': 2, 'days': 2, 'tm_mday': 2, 'hour': 3, 'hours': 3, 'tm...
def _decode_time_rotation_index(self, time_rot_index)
Return the time struct index to use for log rotation checks
2.155387
1.809676
1.191035
''' Generate log file path for a given handler Args: handler: The handler configuration dictionary for which a log file path should be generated. ''' if 'file_name_pattern' not in handler: filename = '%Y-%m-%d-%H-%M-%S-{name}.pcap'...
def _get_log_file(self, handler)
Generate log file path for a given handler Args: handler: The handler configuration dictionary for which a log file path should be generated.
2.975618
2.41963
1.229782
''' Initialize a PCAP stream for logging data ''' log_file = self._get_log_file(handler) if not os.path.isdir(os.path.dirname(log_file)): os.makedirs(os.path.dirname(log_file)) handler['log_rot_time'] = time.gmtime() return pcap.open(log_file, mode='a')
def _get_logger(self, handler)
Initialize a PCAP stream for logging data
4.916922
3.623452
1.356971
''' Add a new stream capturer to the manager. Add a new stream capturer to the manager with the provided configuration details. If an existing capturer is monitoring the same address the new handler will be added to it. Args: name: A string defining ...
def add_logger(self, name, address, conn_type, log_dir_path=None, **kwargs)
Add a new stream capturer to the manager. Add a new stream capturer to the manager with the provided configuration details. If an existing capturer is monitoring the same address the new handler will be added to it. Args: name: A string defining the new capt...
2.921776
1.923633
1.518884