repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1 value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
saltstack/salt | salt/cloud/clouds/vmware.py | list_nodes | def list_nodes(kwargs=None, call=None):
'''
Return a list of all VMs and templates that are on the specified provider, with basic fields
CLI Example:
.. code-block:: bash
salt-cloud -f list_nodes my-vmware-config
To return a list of all VMs and templates present on ALL configured providers, with basic
fields:
CLI Example:
.. code-block:: bash
salt-cloud -Q
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called '
'with -f or --function.'
)
ret = {}
vm_properties = [
"name",
"guest.ipAddress",
"config.guestFullName",
"config.hardware.numCPU",
"config.hardware.memoryMB",
"summary.runtime.powerState"
]
vm_list = salt.utils.vmware.get_mors_with_properties(_get_si(), vim.VirtualMachine, vm_properties)
for vm in vm_list:
cpu = vm["config.hardware.numCPU"] if "config.hardware.numCPU" in vm else "N/A"
ram = "{0} MB".format(vm["config.hardware.memoryMB"]) if "config.hardware.memoryMB" in vm else "N/A"
vm_info = {
'id': vm["name"],
'image': "{0} (Detected)".format(vm["config.guestFullName"]) if "config.guestFullName" in vm else "N/A",
'size': "cpu: {0}\nram: {1}".format(cpu, ram),
'size_dict': {
'cpu': cpu,
'memory': ram,
},
'state': six.text_type(vm["summary.runtime.powerState"]) if "summary.runtime.powerState" in vm else "N/A",
'private_ips': [vm["guest.ipAddress"]] if "guest.ipAddress" in vm else [],
'public_ips': []
}
ret[vm_info['id']] = vm_info
return ret | python | def list_nodes(kwargs=None, call=None):
'''
Return a list of all VMs and templates that are on the specified provider, with basic fields
CLI Example:
.. code-block:: bash
salt-cloud -f list_nodes my-vmware-config
To return a list of all VMs and templates present on ALL configured providers, with basic
fields:
CLI Example:
.. code-block:: bash
salt-cloud -Q
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called '
'with -f or --function.'
)
ret = {}
vm_properties = [
"name",
"guest.ipAddress",
"config.guestFullName",
"config.hardware.numCPU",
"config.hardware.memoryMB",
"summary.runtime.powerState"
]
vm_list = salt.utils.vmware.get_mors_with_properties(_get_si(), vim.VirtualMachine, vm_properties)
for vm in vm_list:
cpu = vm["config.hardware.numCPU"] if "config.hardware.numCPU" in vm else "N/A"
ram = "{0} MB".format(vm["config.hardware.memoryMB"]) if "config.hardware.memoryMB" in vm else "N/A"
vm_info = {
'id': vm["name"],
'image': "{0} (Detected)".format(vm["config.guestFullName"]) if "config.guestFullName" in vm else "N/A",
'size': "cpu: {0}\nram: {1}".format(cpu, ram),
'size_dict': {
'cpu': cpu,
'memory': ram,
},
'state': six.text_type(vm["summary.runtime.powerState"]) if "summary.runtime.powerState" in vm else "N/A",
'private_ips': [vm["guest.ipAddress"]] if "guest.ipAddress" in vm else [],
'public_ips': []
}
ret[vm_info['id']] = vm_info
return ret | [
"def",
"list_nodes",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_nodes function must be called '",
"'with -f or --function.'",
")",
"ret",
"=",
"{",
"}",
"vm... | Return a list of all VMs and templates that are on the specified provider, with basic fields
CLI Example:
.. code-block:: bash
salt-cloud -f list_nodes my-vmware-config
To return a list of all VMs and templates present on ALL configured providers, with basic
fields:
CLI Example:
.. code-block:: bash
salt-cloud -Q | [
"Return",
"a",
"list",
"of",
"all",
"VMs",
"and",
"templates",
"that",
"are",
"on",
"the",
"specified",
"provider",
"with",
"basic",
"fields"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L1775-L1829 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | list_nodes_select | def list_nodes_select(call=None):
'''
Return a list of all VMs and templates that are on the specified provider, with fields
specified under ``query.selection`` in ``/etc/salt/cloud``
CLI Example:
.. code-block:: bash
salt-cloud -f list_nodes_select my-vmware-config
To return a list of all VMs and templates present on ALL configured providers, with
fields specified under ``query.selection`` in ``/etc/salt/cloud``:
CLI Example:
.. code-block:: bash
salt-cloud -S
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_select function must be called '
'with -f or --function.'
)
ret = {}
vm_properties = []
selection = __opts__.get('query.selection')
if not selection:
raise SaltCloudSystemExit(
'query.selection not found in /etc/salt/cloud'
)
if 'id' in selection:
vm_properties.append("name")
if 'image' in selection:
vm_properties.append("config.guestFullName")
if 'size' in selection:
vm_properties.extend(["config.hardware.numCPU", "config.hardware.memoryMB"])
if 'state' in selection:
vm_properties.append("summary.runtime.powerState")
if 'private_ips' in selection or 'networks' in selection:
vm_properties.append("guest.net")
if 'devices' in selection or 'mac_address' in selection or 'mac_addresses' in selection:
vm_properties.append("config.hardware.device")
if 'storage' in selection:
vm_properties.extend([
"config.hardware.device",
"summary.storage.committed",
"summary.storage.uncommitted",
"summary.storage.unshared"
])
if 'files' in selection:
vm_properties.append("layoutEx.file")
if 'guest_id' in selection:
vm_properties.append("config.guestId")
if 'hostname' in selection:
vm_properties.append("guest.hostName")
if 'path' in selection:
vm_properties.append("config.files.vmPathName")
if 'tools_status' in selection:
vm_properties.append("guest.toolsStatus")
if not vm_properties:
return {}
elif 'name' not in vm_properties:
vm_properties.append("name")
vm_list = salt.utils.vmware.get_mors_with_properties(_get_si(), vim.VirtualMachine, vm_properties)
for vm in vm_list:
ret[vm["name"]] = _format_instance_info_select(vm, selection)
return ret | python | def list_nodes_select(call=None):
'''
Return a list of all VMs and templates that are on the specified provider, with fields
specified under ``query.selection`` in ``/etc/salt/cloud``
CLI Example:
.. code-block:: bash
salt-cloud -f list_nodes_select my-vmware-config
To return a list of all VMs and templates present on ALL configured providers, with
fields specified under ``query.selection`` in ``/etc/salt/cloud``:
CLI Example:
.. code-block:: bash
salt-cloud -S
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_select function must be called '
'with -f or --function.'
)
ret = {}
vm_properties = []
selection = __opts__.get('query.selection')
if not selection:
raise SaltCloudSystemExit(
'query.selection not found in /etc/salt/cloud'
)
if 'id' in selection:
vm_properties.append("name")
if 'image' in selection:
vm_properties.append("config.guestFullName")
if 'size' in selection:
vm_properties.extend(["config.hardware.numCPU", "config.hardware.memoryMB"])
if 'state' in selection:
vm_properties.append("summary.runtime.powerState")
if 'private_ips' in selection or 'networks' in selection:
vm_properties.append("guest.net")
if 'devices' in selection or 'mac_address' in selection or 'mac_addresses' in selection:
vm_properties.append("config.hardware.device")
if 'storage' in selection:
vm_properties.extend([
"config.hardware.device",
"summary.storage.committed",
"summary.storage.uncommitted",
"summary.storage.unshared"
])
if 'files' in selection:
vm_properties.append("layoutEx.file")
if 'guest_id' in selection:
vm_properties.append("config.guestId")
if 'hostname' in selection:
vm_properties.append("guest.hostName")
if 'path' in selection:
vm_properties.append("config.files.vmPathName")
if 'tools_status' in selection:
vm_properties.append("guest.toolsStatus")
if not vm_properties:
return {}
elif 'name' not in vm_properties:
vm_properties.append("name")
vm_list = salt.utils.vmware.get_mors_with_properties(_get_si(), vim.VirtualMachine, vm_properties)
for vm in vm_list:
ret[vm["name"]] = _format_instance_info_select(vm, selection)
return ret | [
"def",
"list_nodes_select",
"(",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_nodes_select function must be called '",
"'with -f or --function.'",
")",
"ret",
"=",
"{",
"}",
"vm_properties",
"=",
... | Return a list of all VMs and templates that are on the specified provider, with fields
specified under ``query.selection`` in ``/etc/salt/cloud``
CLI Example:
.. code-block:: bash
salt-cloud -f list_nodes_select my-vmware-config
To return a list of all VMs and templates present on ALL configured providers, with
fields specified under ``query.selection`` in ``/etc/salt/cloud``:
CLI Example:
.. code-block:: bash
salt-cloud -S | [
"Return",
"a",
"list",
"of",
"all",
"VMs",
"and",
"templates",
"that",
"are",
"on",
"the",
"specified",
"provider",
"with",
"fields",
"specified",
"under",
"query",
".",
"selection",
"in",
"/",
"etc",
"/",
"salt",
"/",
"cloud"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L1883-L1968 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | show_instance | def show_instance(name, call=None):
'''
List all available details of the specified VM
CLI Example:
.. code-block:: bash
salt-cloud -a show_instance vmname
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with '
'-a or --action.'
)
vm_properties = [
"config.hardware.device",
"summary.storage.committed",
"summary.storage.uncommitted",
"summary.storage.unshared",
"layoutEx.file",
"config.guestFullName",
"config.guestId",
"guest.net",
"config.hardware.memoryMB",
"name",
"config.hardware.numCPU",
"config.files.vmPathName",
"summary.runtime.powerState",
"guest.toolsStatus"
]
vm_list = salt.utils.vmware.get_mors_with_properties(_get_si(), vim.VirtualMachine, vm_properties)
for vm in vm_list:
if vm['name'] == name:
return _format_instance_info(vm)
return {} | python | def show_instance(name, call=None):
'''
List all available details of the specified VM
CLI Example:
.. code-block:: bash
salt-cloud -a show_instance vmname
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with '
'-a or --action.'
)
vm_properties = [
"config.hardware.device",
"summary.storage.committed",
"summary.storage.uncommitted",
"summary.storage.unshared",
"layoutEx.file",
"config.guestFullName",
"config.guestId",
"guest.net",
"config.hardware.memoryMB",
"name",
"config.hardware.numCPU",
"config.files.vmPathName",
"summary.runtime.powerState",
"guest.toolsStatus"
]
vm_list = salt.utils.vmware.get_mors_with_properties(_get_si(), vim.VirtualMachine, vm_properties)
for vm in vm_list:
if vm['name'] == name:
return _format_instance_info(vm)
return {} | [
"def",
"show_instance",
"(",
"name",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The show_instance action must be called with '",
"'-a or --action.'",
")",
"vm_properties",
"=",
"[",
"\"config.hardwar... | List all available details of the specified VM
CLI Example:
.. code-block:: bash
salt-cloud -a show_instance vmname | [
"List",
"all",
"available",
"details",
"of",
"the",
"specified",
"VM"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L1971-L2010 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | avail_images | def avail_images(call=None):
'''
Return a list of all the templates present in this VMware environment with basic
details
CLI Example:
.. code-block:: bash
salt-cloud --list-images my-vmware-config
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option.'
)
templates = {}
vm_properties = [
"name",
"config.template",
"config.guestFullName",
"config.hardware.numCPU",
"config.hardware.memoryMB"
]
vm_list = salt.utils.vmware.get_mors_with_properties(_get_si(), vim.VirtualMachine, vm_properties)
for vm in vm_list:
if "config.template" in vm and vm["config.template"]:
templates[vm["name"]] = {
'name': vm["name"],
'guest_fullname': vm["config.guestFullName"] if "config.guestFullName" in vm else "N/A",
'cpus': vm["config.hardware.numCPU"] if "config.hardware.numCPU" in vm else "N/A",
'ram': vm["config.hardware.memoryMB"] if "config.hardware.memoryMB" in vm else "N/A"
}
return templates | python | def avail_images(call=None):
'''
Return a list of all the templates present in this VMware environment with basic
details
CLI Example:
.. code-block:: bash
salt-cloud --list-images my-vmware-config
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option.'
)
templates = {}
vm_properties = [
"name",
"config.template",
"config.guestFullName",
"config.hardware.numCPU",
"config.hardware.memoryMB"
]
vm_list = salt.utils.vmware.get_mors_with_properties(_get_si(), vim.VirtualMachine, vm_properties)
for vm in vm_list:
if "config.template" in vm and vm["config.template"]:
templates[vm["name"]] = {
'name': vm["name"],
'guest_fullname': vm["config.guestFullName"] if "config.guestFullName" in vm else "N/A",
'cpus': vm["config.hardware.numCPU"] if "config.hardware.numCPU" in vm else "N/A",
'ram': vm["config.hardware.memoryMB"] if "config.hardware.memoryMB" in vm else "N/A"
}
return templates | [
"def",
"avail_images",
"(",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The avail_images function must be called with '",
"'-f or --function, or with the --list-images option.'",
")",
"templates",
"=",
"{",
"}... | Return a list of all the templates present in this VMware environment with basic
details
CLI Example:
.. code-block:: bash
salt-cloud --list-images my-vmware-config | [
"Return",
"a",
"list",
"of",
"all",
"the",
"templates",
"present",
"in",
"this",
"VMware",
"environment",
"with",
"basic",
"details"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L2013-L2050 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | list_folders | def list_folders(kwargs=None, call=None):
'''
List all the folders for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_folders my-vmware-config
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_folders function must be called with '
'-f or --function.'
)
return {'Folders': salt.utils.vmware.list_folders(_get_si())} | python | def list_folders(kwargs=None, call=None):
'''
List all the folders for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_folders my-vmware-config
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_folders function must be called with '
'-f or --function.'
)
return {'Folders': salt.utils.vmware.list_folders(_get_si())} | [
"def",
"list_folders",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_folders function must be called with '",
"'-f or --function.'",
")",
"return",
"{",
"'Folder... | List all the folders for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_folders my-vmware-config | [
"List",
"all",
"the",
"folders",
"for",
"this",
"VMware",
"environment"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L2121-L2137 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | list_snapshots | def list_snapshots(kwargs=None, call=None):
'''
List snapshots either for all VMs and templates or for a specific VM/template
in this VMware environment
To list snapshots for all VMs and templates:
CLI Example:
.. code-block:: bash
salt-cloud -f list_snapshots my-vmware-config
To list snapshots for a specific VM/template:
CLI Example:
.. code-block:: bash
salt-cloud -f list_snapshots my-vmware-config name="vmname"
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_snapshots function must be called with '
'-f or --function.'
)
ret = {}
vm_properties = [
"name",
"rootSnapshot",
"snapshot"
]
vm_list = salt.utils.vmware.get_mors_with_properties(_get_si(), vim.VirtualMachine, vm_properties)
for vm in vm_list:
if vm["rootSnapshot"]:
if kwargs and kwargs.get('name') == vm["name"]:
return {vm["name"]: _get_snapshots(vm["snapshot"].rootSnapshotList)}
else:
ret[vm["name"]] = _get_snapshots(vm["snapshot"].rootSnapshotList)
else:
if kwargs and kwargs.get('name') == vm["name"]:
return {}
return ret | python | def list_snapshots(kwargs=None, call=None):
'''
List snapshots either for all VMs and templates or for a specific VM/template
in this VMware environment
To list snapshots for all VMs and templates:
CLI Example:
.. code-block:: bash
salt-cloud -f list_snapshots my-vmware-config
To list snapshots for a specific VM/template:
CLI Example:
.. code-block:: bash
salt-cloud -f list_snapshots my-vmware-config name="vmname"
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_snapshots function must be called with '
'-f or --function.'
)
ret = {}
vm_properties = [
"name",
"rootSnapshot",
"snapshot"
]
vm_list = salt.utils.vmware.get_mors_with_properties(_get_si(), vim.VirtualMachine, vm_properties)
for vm in vm_list:
if vm["rootSnapshot"]:
if kwargs and kwargs.get('name') == vm["name"]:
return {vm["name"]: _get_snapshots(vm["snapshot"].rootSnapshotList)}
else:
ret[vm["name"]] = _get_snapshots(vm["snapshot"].rootSnapshotList)
else:
if kwargs and kwargs.get('name') == vm["name"]:
return {}
return ret | [
"def",
"list_snapshots",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_snapshots function must be called with '",
"'-f or --function.'",
")",
"ret",
"=",
"{",
... | List snapshots either for all VMs and templates or for a specific VM/template
in this VMware environment
To list snapshots for all VMs and templates:
CLI Example:
.. code-block:: bash
salt-cloud -f list_snapshots my-vmware-config
To list snapshots for a specific VM/template:
CLI Example:
.. code-block:: bash
salt-cloud -f list_snapshots my-vmware-config name="vmname" | [
"List",
"snapshots",
"either",
"for",
"all",
"VMs",
"and",
"templates",
"or",
"for",
"a",
"specific",
"VM",
"/",
"template",
"in",
"this",
"VMware",
"environment"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L2140-L2186 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | suspend | def suspend(name, call=None):
'''
To suspend a VM using its name
CLI Example:
.. code-block:: bash
salt-cloud -a suspend vmname
'''
if call != 'action':
raise SaltCloudSystemExit(
'The suspend action must be called with '
'-a or --action.'
)
vm_properties = [
"name",
"summary.runtime.powerState"
]
vm_list = salt.utils.vmware.get_mors_with_properties(_get_si(), vim.VirtualMachine, vm_properties)
for vm in vm_list:
if vm["name"] == name:
if vm["summary.runtime.powerState"] == "poweredOff":
ret = 'cannot suspend in powered off state'
log.info('VM %s %s', name, ret)
return ret
elif vm["summary.runtime.powerState"] == "suspended":
ret = 'already suspended'
log.info('VM %s %s', name, ret)
return ret
try:
log.info('Suspending VM %s', name)
task = vm["object"].Suspend()
salt.utils.vmware.wait_for_task(task, name, 'suspend')
except Exception as exc:
log.error(
'Error while suspending VM %s: %s',
name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return 'failed to suspend'
return 'suspended' | python | def suspend(name, call=None):
'''
To suspend a VM using its name
CLI Example:
.. code-block:: bash
salt-cloud -a suspend vmname
'''
if call != 'action':
raise SaltCloudSystemExit(
'The suspend action must be called with '
'-a or --action.'
)
vm_properties = [
"name",
"summary.runtime.powerState"
]
vm_list = salt.utils.vmware.get_mors_with_properties(_get_si(), vim.VirtualMachine, vm_properties)
for vm in vm_list:
if vm["name"] == name:
if vm["summary.runtime.powerState"] == "poweredOff":
ret = 'cannot suspend in powered off state'
log.info('VM %s %s', name, ret)
return ret
elif vm["summary.runtime.powerState"] == "suspended":
ret = 'already suspended'
log.info('VM %s %s', name, ret)
return ret
try:
log.info('Suspending VM %s', name)
task = vm["object"].Suspend()
salt.utils.vmware.wait_for_task(task, name, 'suspend')
except Exception as exc:
log.error(
'Error while suspending VM %s: %s',
name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return 'failed to suspend'
return 'suspended' | [
"def",
"suspend",
"(",
"name",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The suspend action must be called with '",
"'-a or --action.'",
")",
"vm_properties",
"=",
"[",
"\"name\"",
",",
"\"summa... | To suspend a VM using its name
CLI Example:
.. code-block:: bash
salt-cloud -a suspend vmname | [
"To",
"suspend",
"a",
"VM",
"using",
"its",
"name"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L2291-L2337 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | reset | def reset(name, soft=False, call=None):
'''
To reset a VM using its name
.. note::
If ``soft=True`` then issues a command to the guest operating system
asking it to perform a reboot. Otherwise hypervisor will terminate VM and start it again.
Default is soft=False
For ``soft=True`` vmtools should be installed on guest system.
CLI Example:
.. code-block:: bash
salt-cloud -a reset vmname
salt-cloud -a reset vmname soft=True
'''
if call != 'action':
raise SaltCloudSystemExit(
'The reset action must be called with '
'-a or --action.'
)
vm_properties = [
"name",
"summary.runtime.powerState"
]
vm_list = salt.utils.vmware.get_mors_with_properties(_get_si(), vim.VirtualMachine, vm_properties)
for vm in vm_list:
if vm["name"] == name:
if vm["summary.runtime.powerState"] == "suspended" or vm["summary.runtime.powerState"] == "poweredOff":
ret = 'cannot reset in suspended/powered off state'
log.info('VM %s %s', name, ret)
return ret
try:
log.info('Resetting VM %s', name)
if soft:
vm["object"].RebootGuest()
else:
task = vm["object"].ResetVM_Task()
salt.utils.vmware.wait_for_task(task, name, 'reset')
except Exception as exc:
log.error(
'Error while resetting VM %s: %s',
name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return 'failed to reset'
return 'reset' | python | def reset(name, soft=False, call=None):
'''
To reset a VM using its name
.. note::
If ``soft=True`` then issues a command to the guest operating system
asking it to perform a reboot. Otherwise hypervisor will terminate VM and start it again.
Default is soft=False
For ``soft=True`` vmtools should be installed on guest system.
CLI Example:
.. code-block:: bash
salt-cloud -a reset vmname
salt-cloud -a reset vmname soft=True
'''
if call != 'action':
raise SaltCloudSystemExit(
'The reset action must be called with '
'-a or --action.'
)
vm_properties = [
"name",
"summary.runtime.powerState"
]
vm_list = salt.utils.vmware.get_mors_with_properties(_get_si(), vim.VirtualMachine, vm_properties)
for vm in vm_list:
if vm["name"] == name:
if vm["summary.runtime.powerState"] == "suspended" or vm["summary.runtime.powerState"] == "poweredOff":
ret = 'cannot reset in suspended/powered off state'
log.info('VM %s %s', name, ret)
return ret
try:
log.info('Resetting VM %s', name)
if soft:
vm["object"].RebootGuest()
else:
task = vm["object"].ResetVM_Task()
salt.utils.vmware.wait_for_task(task, name, 'reset')
except Exception as exc:
log.error(
'Error while resetting VM %s: %s',
name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return 'failed to reset'
return 'reset' | [
"def",
"reset",
"(",
"name",
",",
"soft",
"=",
"False",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The reset action must be called with '",
"'-a or --action.'",
")",
"vm_properties",
"=",
"[",
... | To reset a VM using its name
.. note::
If ``soft=True`` then issues a command to the guest operating system
asking it to perform a reboot. Otherwise hypervisor will terminate VM and start it again.
Default is soft=False
For ``soft=True`` vmtools should be installed on guest system.
CLI Example:
.. code-block:: bash
salt-cloud -a reset vmname
salt-cloud -a reset vmname soft=True | [
"To",
"reset",
"a",
"VM",
"using",
"its",
"name"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L2340-L2394 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | terminate | def terminate(name, call=None):
'''
To do an immediate power off of a VM using its name. A ``SIGKILL``
is issued to the vmx process of the VM
CLI Example:
.. code-block:: bash
salt-cloud -a terminate vmname
'''
if call != 'action':
raise SaltCloudSystemExit(
'The terminate action must be called with '
'-a or --action.'
)
vm_properties = [
"name",
"summary.runtime.powerState"
]
vm_list = salt.utils.vmware.get_mors_with_properties(_get_si(), vim.VirtualMachine, vm_properties)
for vm in vm_list:
if vm["name"] == name:
if vm["summary.runtime.powerState"] == "poweredOff":
ret = 'already powered off'
log.info('VM %s %s', name, ret)
return ret
try:
log.info('Terminating VM %s', name)
vm["object"].Terminate()
except Exception as exc:
log.error(
'Error while terminating VM %s: %s',
name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return 'failed to terminate'
return 'terminated' | python | def terminate(name, call=None):
'''
To do an immediate power off of a VM using its name. A ``SIGKILL``
is issued to the vmx process of the VM
CLI Example:
.. code-block:: bash
salt-cloud -a terminate vmname
'''
if call != 'action':
raise SaltCloudSystemExit(
'The terminate action must be called with '
'-a or --action.'
)
vm_properties = [
"name",
"summary.runtime.powerState"
]
vm_list = salt.utils.vmware.get_mors_with_properties(_get_si(), vim.VirtualMachine, vm_properties)
for vm in vm_list:
if vm["name"] == name:
if vm["summary.runtime.powerState"] == "poweredOff":
ret = 'already powered off'
log.info('VM %s %s', name, ret)
return ret
try:
log.info('Terminating VM %s', name)
vm["object"].Terminate()
except Exception as exc:
log.error(
'Error while terminating VM %s: %s',
name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return 'failed to terminate'
return 'terminated' | [
"def",
"terminate",
"(",
"name",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The terminate action must be called with '",
"'-a or --action.'",
")",
"vm_properties",
"=",
"[",
"\"name\"",
",",
"\"s... | To do an immediate power off of a VM using its name. A ``SIGKILL``
is issued to the vmx process of the VM
CLI Example:
.. code-block:: bash
salt-cloud -a terminate vmname | [
"To",
"do",
"an",
"immediate",
"power",
"off",
"of",
"a",
"VM",
"using",
"its",
"name",
".",
"A",
"SIGKILL",
"is",
"issued",
"to",
"the",
"vmx",
"process",
"of",
"the",
"VM"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L2397-L2439 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | destroy | def destroy(name, call=None):
'''
To destroy a VM from the VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -d vmname
salt-cloud --destroy vmname
salt-cloud -a destroy vmname
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
vm_properties = [
"name",
"summary.runtime.powerState"
]
vm_list = salt.utils.vmware.get_mors_with_properties(_get_si(), vim.VirtualMachine, vm_properties)
for vm in vm_list:
if vm["name"] == name:
if vm["summary.runtime.powerState"] != "poweredOff":
# Power off the vm first
try:
log.info('Powering Off VM %s', name)
task = vm["object"].PowerOff()
salt.utils.vmware.wait_for_task(task, name, 'power off')
except Exception as exc:
log.error(
'Error while powering off VM %s: %s',
name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return 'failed to destroy'
try:
log.info('Destroying VM %s', name)
task = vm["object"].Destroy_Task()
salt.utils.vmware.wait_for_task(task, name, 'destroy')
except Exception as exc:
log.error(
'Error while destroying VM %s: %s',
name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return 'failed to destroy'
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
return True | python | def destroy(name, call=None):
'''
To destroy a VM from the VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -d vmname
salt-cloud --destroy vmname
salt-cloud -a destroy vmname
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
vm_properties = [
"name",
"summary.runtime.powerState"
]
vm_list = salt.utils.vmware.get_mors_with_properties(_get_si(), vim.VirtualMachine, vm_properties)
for vm in vm_list:
if vm["name"] == name:
if vm["summary.runtime.powerState"] != "poweredOff":
# Power off the vm first
try:
log.info('Powering Off VM %s', name)
task = vm["object"].PowerOff()
salt.utils.vmware.wait_for_task(task, name, 'power off')
except Exception as exc:
log.error(
'Error while powering off VM %s: %s',
name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return 'failed to destroy'
try:
log.info('Destroying VM %s', name)
task = vm["object"].Destroy_Task()
salt.utils.vmware.wait_for_task(task, name, 'destroy')
except Exception as exc:
log.error(
'Error while destroying VM %s: %s',
name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return 'failed to destroy'
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
return True | [
"def",
"destroy",
"(",
"name",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The destroy action must be called with -d, --destroy, '",
"'-a or --action.'",
")",
"__utils__",
"[",
"'cloud.fire_event'",
... | To destroy a VM from the VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -d vmname
salt-cloud --destroy vmname
salt-cloud -a destroy vmname | [
"To",
"destroy",
"a",
"VM",
"from",
"the",
"VMware",
"environment"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L2442-L2516 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | create | def create(vm_):
'''
To create a single VM in the VMware environment.
Sample profile and arguments that can be specified in it can be found
:ref:`here. <vmware-cloud-profile>`
CLI Example:
.. code-block:: bash
salt-cloud -p vmware-centos6.5 vmname
'''
try:
# Check for required profile parameters before sending any API calls.
if (vm_['profile'] and
config.is_profile_configured(__opts__,
__active_provider_name__ or 'vmware',
vm_['profile'],
vm_=vm_) is False):
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
vm_name = config.get_cloud_config_value(
'name', vm_, __opts__, default=None
)
folder = config.get_cloud_config_value(
'folder', vm_, __opts__, default=None
)
datacenter = config.get_cloud_config_value(
'datacenter', vm_, __opts__, default=None
)
resourcepool = config.get_cloud_config_value(
'resourcepool', vm_, __opts__, default=None
)
cluster = config.get_cloud_config_value(
'cluster', vm_, __opts__, default=None
)
datastore = config.get_cloud_config_value(
'datastore', vm_, __opts__, default=None
)
host = config.get_cloud_config_value(
'host', vm_, __opts__, default=None
)
template = config.get_cloud_config_value(
'template', vm_, __opts__, default=False
)
num_cpus = config.get_cloud_config_value(
'num_cpus', vm_, __opts__, default=None
)
cores_per_socket = config.get_cloud_config_value(
'cores_per_socket', vm_, __opts__, default=None
)
memory = config.get_cloud_config_value(
'memory', vm_, __opts__, default=None
)
devices = config.get_cloud_config_value(
'devices', vm_, __opts__, default=None
)
extra_config = config.get_cloud_config_value(
'extra_config', vm_, __opts__, default=None
)
annotation = config.get_cloud_config_value(
'annotation', vm_, __opts__, default=None
)
power = config.get_cloud_config_value(
'power_on', vm_, __opts__, default=True
)
key_filename = config.get_cloud_config_value(
'private_key', vm_, __opts__, search_global=False, default=None
)
deploy = config.get_cloud_config_value(
'deploy', vm_, __opts__, search_global=True, default=True
)
wait_for_ip_timeout = config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=20 * 60
)
domain = config.get_cloud_config_value(
'domain', vm_, __opts__, search_global=False, default='local'
)
hardware_version = config.get_cloud_config_value(
'hardware_version', vm_, __opts__, search_global=False, default=None
)
guest_id = config.get_cloud_config_value(
'image', vm_, __opts__, search_global=False, default=None
)
customization = config.get_cloud_config_value(
'customization', vm_, __opts__, search_global=False, default=True
)
customization_spec = config.get_cloud_config_value(
'customization_spec', vm_, __opts__, search_global=False, default=None
)
win_password = config.get_cloud_config_value(
'win_password', vm_, __opts__, search_global=False, default=None
)
win_organization_name = config.get_cloud_config_value(
'win_organization_name', vm_, __opts__, search_global=False, default='Organization'
)
plain_text = config.get_cloud_config_value(
'plain_text', vm_, __opts__, search_global=False, default=False
)
win_user_fullname = config.get_cloud_config_value(
'win_user_fullname', vm_, __opts__, search_global=False, default='Windows User'
)
win_run_once = config.get_cloud_config_value(
'win_run_once', vm_, __opts__, search_global=False, default=None
)
win_ad_domain = config.get_cloud_config_value(
'win_ad_domain', vm_, __opts__, search_global=False, default=''
)
win_ad_user = config.get_cloud_config_value(
'win_ad_user', vm_, __opts__, search_global=False, default=''
)
win_ad_password = config.get_cloud_config_value(
'win_ad_password', vm_, __opts__, search_global=False, default=''
)
win_autologon = config.get_cloud_config_value(
'win_autologon', vm_, __opts__, search_global=False, default=True
)
timezone = config.get_cloud_config_value(
'timezone', vm_, __opts__, search_global=False, default=''
)
hw_clock_utc = config.get_cloud_config_value(
'hw_clock_utc', vm_, __opts__, search_global=False, default=''
)
clonefrom_datacenter = config.get_cloud_config_value(
'clonefrom_datacenter', vm_, __opts__, search_global=False, default=datacenter
)
# Get service instance object
si = _get_si()
container_ref = None
clonefrom_datacenter_ref = None
# If datacenter is specified, set the container reference to start search from it instead
if datacenter:
datacenter_ref = salt.utils.vmware.get_mor_by_property(_get_si(), vim.Datacenter, datacenter)
container_ref = datacenter_ref if datacenter_ref else None
if 'clonefrom' in vm_:
# If datacenter is specified, set the container reference to start search from it instead
if datacenter:
datacenter_ref = salt.utils.vmware.get_mor_by_property(
si,
vim.Datacenter,
datacenter
)
container_ref = datacenter_ref if datacenter_ref else None
clonefrom_container_ref = datacenter_ref if datacenter_ref else None
# allow specifying a different datacenter that the template lives in
if clonefrom_datacenter:
clonefrom_datacenter_ref = salt.utils.vmware.get_mor_by_property(
si,
vim.Datacenter,
clonefrom_datacenter
)
clonefrom_container_ref = clonefrom_datacenter_ref if clonefrom_datacenter_ref else None
# Clone VM/template from specified VM/template
object_ref = salt.utils.vmware.get_mor_by_property(
si,
vim.VirtualMachine,
vm_['clonefrom'],
container_ref=clonefrom_container_ref
)
if object_ref:
clone_type = "template" if object_ref.config.template else "vm"
else:
raise SaltCloudSystemExit(
'The VM/template that you have specified under clonefrom does not exist.'
)
else:
clone_type = None
object_ref = None
# Either a cluster, or a resource pool must be specified when cloning from template or creating.
if resourcepool:
resourcepool_ref = salt.utils.vmware.get_mor_by_property(
si,
vim.ResourcePool,
resourcepool,
container_ref=container_ref
)
if not resourcepool_ref:
log.error("Specified resource pool: '%s' does not exist", resourcepool)
if not clone_type or clone_type == "template":
raise SaltCloudSystemExit('You must specify a resource pool that exists.')
elif cluster:
cluster_ref = salt.utils.vmware.get_mor_by_property(
si,
vim.ClusterComputeResource,
cluster,
container_ref=container_ref
)
if not cluster_ref:
log.error("Specified cluster: '%s' does not exist", cluster)
if not clone_type or clone_type == "template":
raise SaltCloudSystemExit('You must specify a cluster that exists.')
else:
resourcepool_ref = cluster_ref.resourcePool
elif clone_type == "template":
raise SaltCloudSystemExit(
'You must either specify a cluster or a resource pool when cloning from a template.'
)
elif not clone_type:
raise SaltCloudSystemExit(
'You must either specify a cluster or a resource pool when creating.'
)
else:
log.debug("Using resource pool used by the %s %s", clone_type, vm_['clonefrom'])
# Either a datacenter or a folder can be optionally specified when cloning, required when creating.
# If not specified when cloning, the existing VM/template\'s parent folder is used.
if folder:
folder_parts = folder.split('/')
search_reference = container_ref
for folder_part in folder_parts:
if folder_part:
folder_ref = salt.utils.vmware.get_mor_by_property(
si,
vim.Folder,
folder_part,
container_ref=search_reference
)
search_reference = folder_ref
if not folder_ref:
log.error("Specified folder: '%s' does not exist", folder)
log.debug("Using folder in which %s %s is present", clone_type, vm_['clonefrom'])
folder_ref = object_ref.parent
elif datacenter:
if not datacenter_ref:
log.error("Specified datacenter: '%s' does not exist", datacenter)
log.debug("Using datacenter folder in which %s %s is present", clone_type, vm_['clonefrom'])
folder_ref = object_ref.parent
else:
folder_ref = datacenter_ref.vmFolder
elif not clone_type:
raise SaltCloudSystemExit(
'You must either specify a folder or a datacenter when creating not cloning.'
)
else:
log.debug("Using folder in which %s %s is present", clone_type, vm_['clonefrom'])
folder_ref = object_ref.parent
if 'clonefrom' in vm_:
# Create the relocation specs
reloc_spec = vim.vm.RelocateSpec()
if (resourcepool and resourcepool_ref) or (cluster and cluster_ref):
reloc_spec.pool = resourcepool_ref
# Either a datastore/datastore cluster can be optionally specified.
# If not specified, the current datastore is used.
if datastore:
datastore_ref = salt.utils.vmware.get_mor_by_property(
si,
vim.Datastore,
datastore,
container_ref=container_ref
)
if datastore_ref:
# specific datastore has been specified
reloc_spec.datastore = datastore_ref
else:
datastore_cluster_ref = salt.utils.vmware.get_mor_by_property(si, vim.StoragePod, datastore, container_ref=container_ref)
if not datastore_cluster_ref:
log.error("Specified datastore/datastore cluster: '%s' does not exist", datastore)
log.debug("Using datastore used by the %s %s", clone_type, vm_['clonefrom'])
else:
log.debug("No datastore/datastore cluster specified")
log.debug("Using datastore used by the %s %s", clone_type, vm_['clonefrom'])
if host:
host_ref = salt.utils.vmware.get_mor_by_property(
si,
vim.HostSystem,
host,
container_ref=container_ref
)
if host_ref:
reloc_spec.host = host_ref
else:
log.error("Specified host: '%s' does not exist", host)
else:
if not datastore:
raise SaltCloudSystemExit(
'You must specify a datastore when creating not cloning.'
)
else:
datastore_ref = salt.utils.vmware.get_mor_by_property(
si,
vim.Datastore,
datastore
)
if not datastore_ref:
raise SaltCloudSystemExit("Specified datastore: '{0}' does not exist".format(datastore))
if host:
host_ref = salt.utils.vmware.get_mor_by_property(
_get_si(),
vim.HostSystem,
host,
container_ref=container_ref
)
if not host_ref:
log.error("Specified host: '%s' does not exist", host)
# Create the config specs
config_spec = vim.vm.ConfigSpec()
# If the hardware version is specified and if it is different from the current
# hardware version, then schedule a hardware version upgrade
if hardware_version and object_ref is not None:
hardware_version = 'vmx-{0:02}'.format(hardware_version)
if hardware_version != object_ref.config.version:
log.debug(
"Scheduling hardware version upgrade from %s to %s",
object_ref.config.version, hardware_version
)
scheduled_hardware_upgrade = vim.vm.ScheduledHardwareUpgradeInfo()
scheduled_hardware_upgrade.upgradePolicy = 'always'
scheduled_hardware_upgrade.versionKey = hardware_version
config_spec.scheduledHardwareUpgradeInfo = scheduled_hardware_upgrade
else:
log.debug("Virtual hardware version already set to %s", hardware_version)
if num_cpus:
log.debug("Setting cpu to: %s", num_cpus)
config_spec.numCPUs = int(num_cpus)
if cores_per_socket:
log.debug("Setting cores per socket to: %s", cores_per_socket)
config_spec.numCoresPerSocket = int(cores_per_socket)
if memory:
try:
memory_num, memory_unit = re.findall(r"[^\W\d_]+|\d+.\d+|\d+",
memory)
if memory_unit.lower() == "mb":
memory_mb = int(memory_num)
elif memory_unit.lower() == "gb":
memory_mb = int(float(memory_num)*1024.0)
else:
err_msg = "Invalid memory type specified: '{0}'".format(memory_unit)
log.error(err_msg)
return {'Error': err_msg}
except (TypeError, ValueError):
memory_mb = int(memory)
log.debug("Setting memory to: %s MB", memory_mb)
config_spec.memoryMB = memory_mb
if devices:
specs = _manage_devices(devices, vm=object_ref, container_ref=container_ref, new_vm_name=vm_name)
config_spec.deviceChange = specs['device_specs']
if extra_config:
for key, value in six.iteritems(extra_config):
option = vim.option.OptionValue(key=key, value=value)
config_spec.extraConfig.append(option)
if annotation:
config_spec.annotation = six.text_type(annotation)
if 'clonefrom' in vm_:
clone_spec = handle_snapshot(
config_spec,
object_ref,
reloc_spec,
template,
vm_
)
if not clone_spec:
clone_spec = build_clonespec(config_spec,
object_ref,
reloc_spec,
template)
if customization and customization_spec:
customization_spec = salt.utils.vmware.get_customizationspec_ref(si=si, customization_spec_name=customization_spec)
clone_spec.customization = customization_spec.spec
elif customization and (devices and 'network' in list(devices.keys())):
global_ip = vim.vm.customization.GlobalIPSettings()
if 'dns_servers' in list(vm_.keys()):
global_ip.dnsServerList = vm_['dns_servers']
non_hostname_chars = re.compile(r'[^\w-]')
if re.search(non_hostname_chars, vm_name):
host_name = re.split(non_hostname_chars,
vm_name,
maxsplit=1)[0]
domain_name = re.split(non_hostname_chars,
vm_name,
maxsplit=1)[-1]
else:
host_name = vm_name
domain_name = domain
if 'Windows' not in object_ref.config.guestFullName:
identity = vim.vm.customization.LinuxPrep()
identity.hostName = vim.vm.customization.FixedName(name=host_name)
identity.domain = domain_name
if timezone:
identity.timeZone = timezone
if isinstance(hw_clock_utc, bool):
identity.hwClockUTC = hw_clock_utc
else:
identity = vim.vm.customization.Sysprep()
identity.guiUnattended = vim.vm.customization.GuiUnattended()
identity.guiUnattended.autoLogon = win_autologon
if win_autologon:
identity.guiUnattended.autoLogonCount = 1
else:
identity.guiUnattended.autoLogonCount = 0
identity.guiUnattended.password = vim.vm.customization.Password()
identity.guiUnattended.password.value = win_password
identity.guiUnattended.password.plainText = plain_text
if timezone:
identity.guiUnattended.timeZone = timezone
if win_run_once:
identity.guiRunOnce = vim.vm.customization.GuiRunOnce()
identity.guiRunOnce.commandList = win_run_once
identity.userData = vim.vm.customization.UserData()
identity.userData.fullName = win_user_fullname
identity.userData.orgName = win_organization_name
identity.userData.computerName = vim.vm.customization.FixedName()
identity.userData.computerName.name = host_name
identity.identification = vim.vm.customization.Identification()
if win_ad_domain and win_ad_user and win_ad_password:
identity.identification.joinDomain = win_ad_domain
identity.identification.domainAdmin = win_ad_user
identity.identification.domainAdminPassword = vim.vm.customization.Password()
identity.identification.domainAdminPassword.value = win_ad_password
identity.identification.domainAdminPassword.plainText = plain_text
custom_spec = vim.vm.customization.Specification(
globalIPSettings=global_ip,
identity=identity,
nicSettingMap=specs['nics_map']
)
clone_spec.customization = custom_spec
if not template:
clone_spec.powerOn = power
log.debug('clone_spec set to:\n%s', pprint.pformat(clone_spec))
else:
config_spec.name = vm_name
config_spec.files = vim.vm.FileInfo()
config_spec.files.vmPathName = '[{0}] {1}/{1}.vmx'.format(datastore, vm_name)
config_spec.guestId = guest_id
log.debug('config_spec set to:\n%s', pprint.pformat(config_spec))
event_kwargs = vm_.copy()
if event_kwargs.get('password'):
del event_kwargs['password']
try:
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if 'clonefrom' in vm_:
log.info("Creating %s from %s(%s)", vm_['name'], clone_type, vm_['clonefrom'])
if datastore and not datastore_ref and datastore_cluster_ref:
# datastore cluster has been specified so apply Storage DRS recommendations
pod_spec = vim.storageDrs.PodSelectionSpec(storagePod=datastore_cluster_ref)
storage_spec = vim.storageDrs.StoragePlacementSpec(
type='clone',
vm=object_ref,
podSelectionSpec=pod_spec,
cloneSpec=clone_spec,
cloneName=vm_name,
folder=folder_ref
)
# get recommended datastores
recommended_datastores = si.content.storageResourceManager.RecommendDatastores(storageSpec=storage_spec)
# apply storage DRS recommendations
task = si.content.storageResourceManager.ApplyStorageDrsRecommendation_Task(recommended_datastores.recommendations[0].key)
salt.utils.vmware.wait_for_task(task, vm_name, 'apply storage DRS recommendations', 5, 'info')
else:
# clone the VM/template
task = object_ref.Clone(folder_ref, vm_name, clone_spec)
salt.utils.vmware.wait_for_task(task, vm_name, 'clone', 5, 'info')
else:
log.info('Creating %s', vm_['name'])
if host:
task = folder_ref.CreateVM_Task(config_spec, resourcepool_ref, host_ref)
else:
task = folder_ref.CreateVM_Task(config_spec, resourcepool_ref)
salt.utils.vmware.wait_for_task(task, vm_name, "create", 15, 'info')
except Exception as exc:
err_msg = 'Error creating {0}: {1}'.format(vm_['name'], exc)
log.error(
err_msg,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return {'Error': err_msg}
new_vm_ref = salt.utils.vmware.get_mor_by_property(si, vim.VirtualMachine, vm_name, container_ref=container_ref)
# Find how to power on in CreateVM_Task (if possible), for now this will do
try:
if not clone_type and power:
task = new_vm_ref.PowerOn()
salt.utils.vmware.wait_for_task(task, vm_name, 'power', 5, 'info')
except Exception as exc:
log.info('Powering on the VM threw this exception. Ignoring.')
log.info(exc)
# If it a template or if it does not need to be powered on then do not wait for the IP
out = None
if not template and power:
ip = _wait_for_ip(new_vm_ref, wait_for_ip_timeout)
if ip:
log.info("[ %s ] IPv4 is: %s", vm_name, ip)
# ssh or smb using ip and install salt only if deploy is True
if deploy:
vm_['key_filename'] = key_filename
# if specified, prefer ssh_host to the discovered ip address
if 'ssh_host' not in vm_:
vm_['ssh_host'] = ip
log.info("[ %s ] Deploying to %s", vm_name, vm_['ssh_host'])
out = __utils__['cloud.bootstrap'](vm_, __opts__)
data = show_instance(vm_name, call='action')
if deploy and isinstance(out, dict):
data['deploy_kwargs'] = out.get('deploy_kwargs', {})
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return data | python | def create(vm_):
'''
To create a single VM in the VMware environment.
Sample profile and arguments that can be specified in it can be found
:ref:`here. <vmware-cloud-profile>`
CLI Example:
.. code-block:: bash
salt-cloud -p vmware-centos6.5 vmname
'''
try:
# Check for required profile parameters before sending any API calls.
if (vm_['profile'] and
config.is_profile_configured(__opts__,
__active_provider_name__ or 'vmware',
vm_['profile'],
vm_=vm_) is False):
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
vm_name = config.get_cloud_config_value(
'name', vm_, __opts__, default=None
)
folder = config.get_cloud_config_value(
'folder', vm_, __opts__, default=None
)
datacenter = config.get_cloud_config_value(
'datacenter', vm_, __opts__, default=None
)
resourcepool = config.get_cloud_config_value(
'resourcepool', vm_, __opts__, default=None
)
cluster = config.get_cloud_config_value(
'cluster', vm_, __opts__, default=None
)
datastore = config.get_cloud_config_value(
'datastore', vm_, __opts__, default=None
)
host = config.get_cloud_config_value(
'host', vm_, __opts__, default=None
)
template = config.get_cloud_config_value(
'template', vm_, __opts__, default=False
)
num_cpus = config.get_cloud_config_value(
'num_cpus', vm_, __opts__, default=None
)
cores_per_socket = config.get_cloud_config_value(
'cores_per_socket', vm_, __opts__, default=None
)
memory = config.get_cloud_config_value(
'memory', vm_, __opts__, default=None
)
devices = config.get_cloud_config_value(
'devices', vm_, __opts__, default=None
)
extra_config = config.get_cloud_config_value(
'extra_config', vm_, __opts__, default=None
)
annotation = config.get_cloud_config_value(
'annotation', vm_, __opts__, default=None
)
power = config.get_cloud_config_value(
'power_on', vm_, __opts__, default=True
)
key_filename = config.get_cloud_config_value(
'private_key', vm_, __opts__, search_global=False, default=None
)
deploy = config.get_cloud_config_value(
'deploy', vm_, __opts__, search_global=True, default=True
)
wait_for_ip_timeout = config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=20 * 60
)
domain = config.get_cloud_config_value(
'domain', vm_, __opts__, search_global=False, default='local'
)
hardware_version = config.get_cloud_config_value(
'hardware_version', vm_, __opts__, search_global=False, default=None
)
guest_id = config.get_cloud_config_value(
'image', vm_, __opts__, search_global=False, default=None
)
customization = config.get_cloud_config_value(
'customization', vm_, __opts__, search_global=False, default=True
)
customization_spec = config.get_cloud_config_value(
'customization_spec', vm_, __opts__, search_global=False, default=None
)
win_password = config.get_cloud_config_value(
'win_password', vm_, __opts__, search_global=False, default=None
)
win_organization_name = config.get_cloud_config_value(
'win_organization_name', vm_, __opts__, search_global=False, default='Organization'
)
plain_text = config.get_cloud_config_value(
'plain_text', vm_, __opts__, search_global=False, default=False
)
win_user_fullname = config.get_cloud_config_value(
'win_user_fullname', vm_, __opts__, search_global=False, default='Windows User'
)
win_run_once = config.get_cloud_config_value(
'win_run_once', vm_, __opts__, search_global=False, default=None
)
win_ad_domain = config.get_cloud_config_value(
'win_ad_domain', vm_, __opts__, search_global=False, default=''
)
win_ad_user = config.get_cloud_config_value(
'win_ad_user', vm_, __opts__, search_global=False, default=''
)
win_ad_password = config.get_cloud_config_value(
'win_ad_password', vm_, __opts__, search_global=False, default=''
)
win_autologon = config.get_cloud_config_value(
'win_autologon', vm_, __opts__, search_global=False, default=True
)
timezone = config.get_cloud_config_value(
'timezone', vm_, __opts__, search_global=False, default=''
)
hw_clock_utc = config.get_cloud_config_value(
'hw_clock_utc', vm_, __opts__, search_global=False, default=''
)
clonefrom_datacenter = config.get_cloud_config_value(
'clonefrom_datacenter', vm_, __opts__, search_global=False, default=datacenter
)
# Get service instance object
si = _get_si()
container_ref = None
clonefrom_datacenter_ref = None
# If datacenter is specified, set the container reference to start search from it instead
if datacenter:
datacenter_ref = salt.utils.vmware.get_mor_by_property(_get_si(), vim.Datacenter, datacenter)
container_ref = datacenter_ref if datacenter_ref else None
if 'clonefrom' in vm_:
# If datacenter is specified, set the container reference to start search from it instead
if datacenter:
datacenter_ref = salt.utils.vmware.get_mor_by_property(
si,
vim.Datacenter,
datacenter
)
container_ref = datacenter_ref if datacenter_ref else None
clonefrom_container_ref = datacenter_ref if datacenter_ref else None
# allow specifying a different datacenter that the template lives in
if clonefrom_datacenter:
clonefrom_datacenter_ref = salt.utils.vmware.get_mor_by_property(
si,
vim.Datacenter,
clonefrom_datacenter
)
clonefrom_container_ref = clonefrom_datacenter_ref if clonefrom_datacenter_ref else None
# Clone VM/template from specified VM/template
object_ref = salt.utils.vmware.get_mor_by_property(
si,
vim.VirtualMachine,
vm_['clonefrom'],
container_ref=clonefrom_container_ref
)
if object_ref:
clone_type = "template" if object_ref.config.template else "vm"
else:
raise SaltCloudSystemExit(
'The VM/template that you have specified under clonefrom does not exist.'
)
else:
clone_type = None
object_ref = None
# Either a cluster, or a resource pool must be specified when cloning from template or creating.
if resourcepool:
resourcepool_ref = salt.utils.vmware.get_mor_by_property(
si,
vim.ResourcePool,
resourcepool,
container_ref=container_ref
)
if not resourcepool_ref:
log.error("Specified resource pool: '%s' does not exist", resourcepool)
if not clone_type or clone_type == "template":
raise SaltCloudSystemExit('You must specify a resource pool that exists.')
elif cluster:
cluster_ref = salt.utils.vmware.get_mor_by_property(
si,
vim.ClusterComputeResource,
cluster,
container_ref=container_ref
)
if not cluster_ref:
log.error("Specified cluster: '%s' does not exist", cluster)
if not clone_type or clone_type == "template":
raise SaltCloudSystemExit('You must specify a cluster that exists.')
else:
resourcepool_ref = cluster_ref.resourcePool
elif clone_type == "template":
raise SaltCloudSystemExit(
'You must either specify a cluster or a resource pool when cloning from a template.'
)
elif not clone_type:
raise SaltCloudSystemExit(
'You must either specify a cluster or a resource pool when creating.'
)
else:
log.debug("Using resource pool used by the %s %s", clone_type, vm_['clonefrom'])
# Either a datacenter or a folder can be optionally specified when cloning, required when creating.
# If not specified when cloning, the existing VM/template\'s parent folder is used.
if folder:
folder_parts = folder.split('/')
search_reference = container_ref
for folder_part in folder_parts:
if folder_part:
folder_ref = salt.utils.vmware.get_mor_by_property(
si,
vim.Folder,
folder_part,
container_ref=search_reference
)
search_reference = folder_ref
if not folder_ref:
log.error("Specified folder: '%s' does not exist", folder)
log.debug("Using folder in which %s %s is present", clone_type, vm_['clonefrom'])
folder_ref = object_ref.parent
elif datacenter:
if not datacenter_ref:
log.error("Specified datacenter: '%s' does not exist", datacenter)
log.debug("Using datacenter folder in which %s %s is present", clone_type, vm_['clonefrom'])
folder_ref = object_ref.parent
else:
folder_ref = datacenter_ref.vmFolder
elif not clone_type:
raise SaltCloudSystemExit(
'You must either specify a folder or a datacenter when creating not cloning.'
)
else:
log.debug("Using folder in which %s %s is present", clone_type, vm_['clonefrom'])
folder_ref = object_ref.parent
if 'clonefrom' in vm_:
# Create the relocation specs
reloc_spec = vim.vm.RelocateSpec()
if (resourcepool and resourcepool_ref) or (cluster and cluster_ref):
reloc_spec.pool = resourcepool_ref
# Either a datastore/datastore cluster can be optionally specified.
# If not specified, the current datastore is used.
if datastore:
datastore_ref = salt.utils.vmware.get_mor_by_property(
si,
vim.Datastore,
datastore,
container_ref=container_ref
)
if datastore_ref:
# specific datastore has been specified
reloc_spec.datastore = datastore_ref
else:
datastore_cluster_ref = salt.utils.vmware.get_mor_by_property(si, vim.StoragePod, datastore, container_ref=container_ref)
if not datastore_cluster_ref:
log.error("Specified datastore/datastore cluster: '%s' does not exist", datastore)
log.debug("Using datastore used by the %s %s", clone_type, vm_['clonefrom'])
else:
log.debug("No datastore/datastore cluster specified")
log.debug("Using datastore used by the %s %s", clone_type, vm_['clonefrom'])
if host:
host_ref = salt.utils.vmware.get_mor_by_property(
si,
vim.HostSystem,
host,
container_ref=container_ref
)
if host_ref:
reloc_spec.host = host_ref
else:
log.error("Specified host: '%s' does not exist", host)
else:
if not datastore:
raise SaltCloudSystemExit(
'You must specify a datastore when creating not cloning.'
)
else:
datastore_ref = salt.utils.vmware.get_mor_by_property(
si,
vim.Datastore,
datastore
)
if not datastore_ref:
raise SaltCloudSystemExit("Specified datastore: '{0}' does not exist".format(datastore))
if host:
host_ref = salt.utils.vmware.get_mor_by_property(
_get_si(),
vim.HostSystem,
host,
container_ref=container_ref
)
if not host_ref:
log.error("Specified host: '%s' does not exist", host)
# Create the config specs
config_spec = vim.vm.ConfigSpec()
# If the hardware version is specified and if it is different from the current
# hardware version, then schedule a hardware version upgrade
if hardware_version and object_ref is not None:
hardware_version = 'vmx-{0:02}'.format(hardware_version)
if hardware_version != object_ref.config.version:
log.debug(
"Scheduling hardware version upgrade from %s to %s",
object_ref.config.version, hardware_version
)
scheduled_hardware_upgrade = vim.vm.ScheduledHardwareUpgradeInfo()
scheduled_hardware_upgrade.upgradePolicy = 'always'
scheduled_hardware_upgrade.versionKey = hardware_version
config_spec.scheduledHardwareUpgradeInfo = scheduled_hardware_upgrade
else:
log.debug("Virtual hardware version already set to %s", hardware_version)
if num_cpus:
log.debug("Setting cpu to: %s", num_cpus)
config_spec.numCPUs = int(num_cpus)
if cores_per_socket:
log.debug("Setting cores per socket to: %s", cores_per_socket)
config_spec.numCoresPerSocket = int(cores_per_socket)
if memory:
try:
memory_num, memory_unit = re.findall(r"[^\W\d_]+|\d+.\d+|\d+",
memory)
if memory_unit.lower() == "mb":
memory_mb = int(memory_num)
elif memory_unit.lower() == "gb":
memory_mb = int(float(memory_num)*1024.0)
else:
err_msg = "Invalid memory type specified: '{0}'".format(memory_unit)
log.error(err_msg)
return {'Error': err_msg}
except (TypeError, ValueError):
memory_mb = int(memory)
log.debug("Setting memory to: %s MB", memory_mb)
config_spec.memoryMB = memory_mb
if devices:
specs = _manage_devices(devices, vm=object_ref, container_ref=container_ref, new_vm_name=vm_name)
config_spec.deviceChange = specs['device_specs']
if extra_config:
for key, value in six.iteritems(extra_config):
option = vim.option.OptionValue(key=key, value=value)
config_spec.extraConfig.append(option)
if annotation:
config_spec.annotation = six.text_type(annotation)
if 'clonefrom' in vm_:
clone_spec = handle_snapshot(
config_spec,
object_ref,
reloc_spec,
template,
vm_
)
if not clone_spec:
clone_spec = build_clonespec(config_spec,
object_ref,
reloc_spec,
template)
if customization and customization_spec:
customization_spec = salt.utils.vmware.get_customizationspec_ref(si=si, customization_spec_name=customization_spec)
clone_spec.customization = customization_spec.spec
elif customization and (devices and 'network' in list(devices.keys())):
global_ip = vim.vm.customization.GlobalIPSettings()
if 'dns_servers' in list(vm_.keys()):
global_ip.dnsServerList = vm_['dns_servers']
non_hostname_chars = re.compile(r'[^\w-]')
if re.search(non_hostname_chars, vm_name):
host_name = re.split(non_hostname_chars,
vm_name,
maxsplit=1)[0]
domain_name = re.split(non_hostname_chars,
vm_name,
maxsplit=1)[-1]
else:
host_name = vm_name
domain_name = domain
if 'Windows' not in object_ref.config.guestFullName:
identity = vim.vm.customization.LinuxPrep()
identity.hostName = vim.vm.customization.FixedName(name=host_name)
identity.domain = domain_name
if timezone:
identity.timeZone = timezone
if isinstance(hw_clock_utc, bool):
identity.hwClockUTC = hw_clock_utc
else:
identity = vim.vm.customization.Sysprep()
identity.guiUnattended = vim.vm.customization.GuiUnattended()
identity.guiUnattended.autoLogon = win_autologon
if win_autologon:
identity.guiUnattended.autoLogonCount = 1
else:
identity.guiUnattended.autoLogonCount = 0
identity.guiUnattended.password = vim.vm.customization.Password()
identity.guiUnattended.password.value = win_password
identity.guiUnattended.password.plainText = plain_text
if timezone:
identity.guiUnattended.timeZone = timezone
if win_run_once:
identity.guiRunOnce = vim.vm.customization.GuiRunOnce()
identity.guiRunOnce.commandList = win_run_once
identity.userData = vim.vm.customization.UserData()
identity.userData.fullName = win_user_fullname
identity.userData.orgName = win_organization_name
identity.userData.computerName = vim.vm.customization.FixedName()
identity.userData.computerName.name = host_name
identity.identification = vim.vm.customization.Identification()
if win_ad_domain and win_ad_user and win_ad_password:
identity.identification.joinDomain = win_ad_domain
identity.identification.domainAdmin = win_ad_user
identity.identification.domainAdminPassword = vim.vm.customization.Password()
identity.identification.domainAdminPassword.value = win_ad_password
identity.identification.domainAdminPassword.plainText = plain_text
custom_spec = vim.vm.customization.Specification(
globalIPSettings=global_ip,
identity=identity,
nicSettingMap=specs['nics_map']
)
clone_spec.customization = custom_spec
if not template:
clone_spec.powerOn = power
log.debug('clone_spec set to:\n%s', pprint.pformat(clone_spec))
else:
config_spec.name = vm_name
config_spec.files = vim.vm.FileInfo()
config_spec.files.vmPathName = '[{0}] {1}/{1}.vmx'.format(datastore, vm_name)
config_spec.guestId = guest_id
log.debug('config_spec set to:\n%s', pprint.pformat(config_spec))
event_kwargs = vm_.copy()
if event_kwargs.get('password'):
del event_kwargs['password']
try:
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if 'clonefrom' in vm_:
log.info("Creating %s from %s(%s)", vm_['name'], clone_type, vm_['clonefrom'])
if datastore and not datastore_ref and datastore_cluster_ref:
# datastore cluster has been specified so apply Storage DRS recommendations
pod_spec = vim.storageDrs.PodSelectionSpec(storagePod=datastore_cluster_ref)
storage_spec = vim.storageDrs.StoragePlacementSpec(
type='clone',
vm=object_ref,
podSelectionSpec=pod_spec,
cloneSpec=clone_spec,
cloneName=vm_name,
folder=folder_ref
)
# get recommended datastores
recommended_datastores = si.content.storageResourceManager.RecommendDatastores(storageSpec=storage_spec)
# apply storage DRS recommendations
task = si.content.storageResourceManager.ApplyStorageDrsRecommendation_Task(recommended_datastores.recommendations[0].key)
salt.utils.vmware.wait_for_task(task, vm_name, 'apply storage DRS recommendations', 5, 'info')
else:
# clone the VM/template
task = object_ref.Clone(folder_ref, vm_name, clone_spec)
salt.utils.vmware.wait_for_task(task, vm_name, 'clone', 5, 'info')
else:
log.info('Creating %s', vm_['name'])
if host:
task = folder_ref.CreateVM_Task(config_spec, resourcepool_ref, host_ref)
else:
task = folder_ref.CreateVM_Task(config_spec, resourcepool_ref)
salt.utils.vmware.wait_for_task(task, vm_name, "create", 15, 'info')
except Exception as exc:
err_msg = 'Error creating {0}: {1}'.format(vm_['name'], exc)
log.error(
err_msg,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return {'Error': err_msg}
new_vm_ref = salt.utils.vmware.get_mor_by_property(si, vim.VirtualMachine, vm_name, container_ref=container_ref)
# Find how to power on in CreateVM_Task (if possible), for now this will do
try:
if not clone_type and power:
task = new_vm_ref.PowerOn()
salt.utils.vmware.wait_for_task(task, vm_name, 'power', 5, 'info')
except Exception as exc:
log.info('Powering on the VM threw this exception. Ignoring.')
log.info(exc)
# If it a template or if it does not need to be powered on then do not wait for the IP
out = None
if not template and power:
ip = _wait_for_ip(new_vm_ref, wait_for_ip_timeout)
if ip:
log.info("[ %s ] IPv4 is: %s", vm_name, ip)
# ssh or smb using ip and install salt only if deploy is True
if deploy:
vm_['key_filename'] = key_filename
# if specified, prefer ssh_host to the discovered ip address
if 'ssh_host' not in vm_:
vm_['ssh_host'] = ip
log.info("[ %s ] Deploying to %s", vm_name, vm_['ssh_host'])
out = __utils__['cloud.bootstrap'](vm_, __opts__)
data = show_instance(vm_name, call='action')
if deploy and isinstance(out, dict):
data['deploy_kwargs'] = out.get('deploy_kwargs', {})
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return data | [
"def",
"create",
"(",
"vm_",
")",
":",
"try",
":",
"# Check for required profile parameters before sending any API calls.",
"if",
"(",
"vm_",
"[",
"'profile'",
"]",
"and",
"config",
".",
"is_profile_configured",
"(",
"__opts__",
",",
"__active_provider_name__",
"or",
... | To create a single VM in the VMware environment.
Sample profile and arguments that can be specified in it can be found
:ref:`here. <vmware-cloud-profile>`
CLI Example:
.. code-block:: bash
salt-cloud -p vmware-centos6.5 vmname | [
"To",
"create",
"a",
"single",
"VM",
"in",
"the",
"VMware",
"environment",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L2519-L3080 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | handle_snapshot | def handle_snapshot(config_spec, object_ref, reloc_spec, template, vm_):
'''
Returns a clone spec for cloning from shapshots
:rtype vim.vm.CloneSpec
'''
if 'snapshot' not in vm_:
return None
allowed_types = [
FLATTEN_DISK_FULL_CLONE,
COPY_ALL_DISKS_FULL_CLONE,
CURRENT_STATE_LINKED_CLONE,
QUICK_LINKED_CLONE,
]
clone_spec = get_clonespec_for_valid_snapshot(
config_spec,
object_ref,
reloc_spec,
template,
vm_)
if not clone_spec:
raise SaltCloudSystemExit('Invalid disk move type specified'
' supported types are'
' {0}'.format(' '.join(allowed_types)))
return clone_spec | python | def handle_snapshot(config_spec, object_ref, reloc_spec, template, vm_):
'''
Returns a clone spec for cloning from shapshots
:rtype vim.vm.CloneSpec
'''
if 'snapshot' not in vm_:
return None
allowed_types = [
FLATTEN_DISK_FULL_CLONE,
COPY_ALL_DISKS_FULL_CLONE,
CURRENT_STATE_LINKED_CLONE,
QUICK_LINKED_CLONE,
]
clone_spec = get_clonespec_for_valid_snapshot(
config_spec,
object_ref,
reloc_spec,
template,
vm_)
if not clone_spec:
raise SaltCloudSystemExit('Invalid disk move type specified'
' supported types are'
' {0}'.format(' '.join(allowed_types)))
return clone_spec | [
"def",
"handle_snapshot",
"(",
"config_spec",
",",
"object_ref",
",",
"reloc_spec",
",",
"template",
",",
"vm_",
")",
":",
"if",
"'snapshot'",
"not",
"in",
"vm_",
":",
"return",
"None",
"allowed_types",
"=",
"[",
"FLATTEN_DISK_FULL_CLONE",
",",
"COPY_ALL_DISKS_F... | Returns a clone spec for cloning from shapshots
:rtype vim.vm.CloneSpec | [
"Returns",
"a",
"clone",
"spec",
"for",
"cloning",
"from",
"shapshots",
":",
"rtype",
"vim",
".",
"vm",
".",
"CloneSpec"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L3083-L3108 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | get_clonespec_for_valid_snapshot | def get_clonespec_for_valid_snapshot(config_spec, object_ref, reloc_spec, template, vm_):
'''
return clonespec only if values are valid
'''
moving = True
if QUICK_LINKED_CLONE == vm_['snapshot']['disk_move_type']:
reloc_spec.diskMoveType = QUICK_LINKED_CLONE
elif CURRENT_STATE_LINKED_CLONE == vm_['snapshot']['disk_move_type']:
reloc_spec.diskMoveType = CURRENT_STATE_LINKED_CLONE
elif COPY_ALL_DISKS_FULL_CLONE == vm_['snapshot']['disk_move_type']:
reloc_spec.diskMoveType = COPY_ALL_DISKS_FULL_CLONE
elif FLATTEN_DISK_FULL_CLONE == vm_['snapshot']['disk_move_type']:
reloc_spec.diskMoveType = FLATTEN_DISK_FULL_CLONE
else:
moving = False
if moving:
return build_clonespec(config_spec, object_ref, reloc_spec, template)
return None | python | def get_clonespec_for_valid_snapshot(config_spec, object_ref, reloc_spec, template, vm_):
'''
return clonespec only if values are valid
'''
moving = True
if QUICK_LINKED_CLONE == vm_['snapshot']['disk_move_type']:
reloc_spec.diskMoveType = QUICK_LINKED_CLONE
elif CURRENT_STATE_LINKED_CLONE == vm_['snapshot']['disk_move_type']:
reloc_spec.diskMoveType = CURRENT_STATE_LINKED_CLONE
elif COPY_ALL_DISKS_FULL_CLONE == vm_['snapshot']['disk_move_type']:
reloc_spec.diskMoveType = COPY_ALL_DISKS_FULL_CLONE
elif FLATTEN_DISK_FULL_CLONE == vm_['snapshot']['disk_move_type']:
reloc_spec.diskMoveType = FLATTEN_DISK_FULL_CLONE
else:
moving = False
if moving:
return build_clonespec(config_spec, object_ref, reloc_spec, template)
return None | [
"def",
"get_clonespec_for_valid_snapshot",
"(",
"config_spec",
",",
"object_ref",
",",
"reloc_spec",
",",
"template",
",",
"vm_",
")",
":",
"moving",
"=",
"True",
"if",
"QUICK_LINKED_CLONE",
"==",
"vm_",
"[",
"'snapshot'",
"]",
"[",
"'disk_move_type'",
"]",
":",... | return clonespec only if values are valid | [
"return",
"clonespec",
"only",
"if",
"values",
"are",
"valid"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L3111-L3130 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | build_clonespec | def build_clonespec(config_spec, object_ref, reloc_spec, template):
'''
Returns the clone spec
'''
if reloc_spec.diskMoveType == QUICK_LINKED_CLONE:
return vim.vm.CloneSpec(
template=template,
location=reloc_spec,
config=config_spec,
snapshot=object_ref.snapshot.currentSnapshot
)
return vim.vm.CloneSpec(
template=template,
location=reloc_spec,
config=config_spec
) | python | def build_clonespec(config_spec, object_ref, reloc_spec, template):
'''
Returns the clone spec
'''
if reloc_spec.diskMoveType == QUICK_LINKED_CLONE:
return vim.vm.CloneSpec(
template=template,
location=reloc_spec,
config=config_spec,
snapshot=object_ref.snapshot.currentSnapshot
)
return vim.vm.CloneSpec(
template=template,
location=reloc_spec,
config=config_spec
) | [
"def",
"build_clonespec",
"(",
"config_spec",
",",
"object_ref",
",",
"reloc_spec",
",",
"template",
")",
":",
"if",
"reloc_spec",
".",
"diskMoveType",
"==",
"QUICK_LINKED_CLONE",
":",
"return",
"vim",
".",
"vm",
".",
"CloneSpec",
"(",
"template",
"=",
"templa... | Returns the clone spec | [
"Returns",
"the",
"clone",
"spec"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L3133-L3149 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | create_datacenter | def create_datacenter(kwargs=None, call=None):
'''
Create a new data center in this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f create_datacenter my-vmware-config name="MyNewDatacenter"
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_datacenter function must be called with '
'-f or --function.'
)
datacenter_name = kwargs.get('name') if kwargs and 'name' in kwargs else None
if not datacenter_name:
raise SaltCloudSystemExit(
'You must specify name of the new datacenter to be created.'
)
if not datacenter_name or len(datacenter_name) >= 80:
raise SaltCloudSystemExit(
'The datacenter name must be a non empty string of less than 80 characters.'
)
# Get the service instance
si = _get_si()
# Check if datacenter already exists
datacenter_ref = salt.utils.vmware.get_mor_by_property(si, vim.Datacenter, datacenter_name)
if datacenter_ref:
return {datacenter_name: 'datacenter already exists'}
folder = si.content.rootFolder
# Verify that the folder is of type vim.Folder
if isinstance(folder, vim.Folder):
try:
folder.CreateDatacenter(name=datacenter_name)
except Exception as exc:
log.error(
'Error creating datacenter %s: %s',
datacenter_name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
log.debug("Created datacenter %s", datacenter_name)
return {datacenter_name: 'created'}
return False | python | def create_datacenter(kwargs=None, call=None):
'''
Create a new data center in this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f create_datacenter my-vmware-config name="MyNewDatacenter"
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_datacenter function must be called with '
'-f or --function.'
)
datacenter_name = kwargs.get('name') if kwargs and 'name' in kwargs else None
if not datacenter_name:
raise SaltCloudSystemExit(
'You must specify name of the new datacenter to be created.'
)
if not datacenter_name or len(datacenter_name) >= 80:
raise SaltCloudSystemExit(
'The datacenter name must be a non empty string of less than 80 characters.'
)
# Get the service instance
si = _get_si()
# Check if datacenter already exists
datacenter_ref = salt.utils.vmware.get_mor_by_property(si, vim.Datacenter, datacenter_name)
if datacenter_ref:
return {datacenter_name: 'datacenter already exists'}
folder = si.content.rootFolder
# Verify that the folder is of type vim.Folder
if isinstance(folder, vim.Folder):
try:
folder.CreateDatacenter(name=datacenter_name)
except Exception as exc:
log.error(
'Error creating datacenter %s: %s',
datacenter_name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
log.debug("Created datacenter %s", datacenter_name)
return {datacenter_name: 'created'}
return False | [
"def",
"create_datacenter",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The create_datacenter function must be called with '",
"'-f or --function.'",
")",
"datacenter_name"... | Create a new data center in this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f create_datacenter my-vmware-config name="MyNewDatacenter" | [
"Create",
"a",
"new",
"data",
"center",
"in",
"this",
"VMware",
"environment"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L3152-L3206 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | create_cluster | def create_cluster(kwargs=None, call=None):
'''
Create a new cluster under the specified datacenter in this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f create_cluster my-vmware-config name="myNewCluster" datacenter="datacenterName"
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_cluster function must be called with '
'-f or --function.'
)
cluster_name = kwargs.get('name') if kwargs and 'name' in kwargs else None
datacenter = kwargs.get('datacenter') if kwargs and 'datacenter' in kwargs else None
if not cluster_name:
raise SaltCloudSystemExit(
'You must specify name of the new cluster to be created.'
)
if not datacenter:
raise SaltCloudSystemExit(
'You must specify name of the datacenter where the cluster should be created.'
)
# Get the service instance
si = _get_si()
if not isinstance(datacenter, vim.Datacenter):
datacenter = salt.utils.vmware.get_mor_by_property(si, vim.Datacenter, datacenter)
if not datacenter:
raise SaltCloudSystemExit(
'The specified datacenter does not exist.'
)
# Check if cluster already exists
cluster_ref = salt.utils.vmware.get_mor_by_property(si, vim.ClusterComputeResource, cluster_name)
if cluster_ref:
return {cluster_name: 'cluster already exists'}
cluster_spec = vim.cluster.ConfigSpecEx()
folder = datacenter.hostFolder
# Verify that the folder is of type vim.Folder
if isinstance(folder, vim.Folder):
try:
folder.CreateClusterEx(name=cluster_name, spec=cluster_spec)
except Exception as exc:
log.error(
'Error creating cluster %s: %s',
cluster_name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
log.debug(
"Created cluster %s under datacenter %s",
cluster_name, datacenter.name
)
return {cluster_name: 'created'}
return False | python | def create_cluster(kwargs=None, call=None):
'''
Create a new cluster under the specified datacenter in this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f create_cluster my-vmware-config name="myNewCluster" datacenter="datacenterName"
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_cluster function must be called with '
'-f or --function.'
)
cluster_name = kwargs.get('name') if kwargs and 'name' in kwargs else None
datacenter = kwargs.get('datacenter') if kwargs and 'datacenter' in kwargs else None
if not cluster_name:
raise SaltCloudSystemExit(
'You must specify name of the new cluster to be created.'
)
if not datacenter:
raise SaltCloudSystemExit(
'You must specify name of the datacenter where the cluster should be created.'
)
# Get the service instance
si = _get_si()
if not isinstance(datacenter, vim.Datacenter):
datacenter = salt.utils.vmware.get_mor_by_property(si, vim.Datacenter, datacenter)
if not datacenter:
raise SaltCloudSystemExit(
'The specified datacenter does not exist.'
)
# Check if cluster already exists
cluster_ref = salt.utils.vmware.get_mor_by_property(si, vim.ClusterComputeResource, cluster_name)
if cluster_ref:
return {cluster_name: 'cluster already exists'}
cluster_spec = vim.cluster.ConfigSpecEx()
folder = datacenter.hostFolder
# Verify that the folder is of type vim.Folder
if isinstance(folder, vim.Folder):
try:
folder.CreateClusterEx(name=cluster_name, spec=cluster_spec)
except Exception as exc:
log.error(
'Error creating cluster %s: %s',
cluster_name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
log.debug(
"Created cluster %s under datacenter %s",
cluster_name, datacenter.name
)
return {cluster_name: 'created'}
return False | [
"def",
"create_cluster",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The create_cluster function must be called with '",
"'-f or --function.'",
")",
"cluster_name",
"=",
... | Create a new cluster under the specified datacenter in this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f create_cluster my-vmware-config name="myNewCluster" datacenter="datacenterName" | [
"Create",
"a",
"new",
"cluster",
"under",
"the",
"specified",
"datacenter",
"in",
"this",
"VMware",
"environment"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L3209-L3275 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | rescan_hba | def rescan_hba(kwargs=None, call=None):
'''
To rescan a specified HBA or all the HBAs on the Host System
CLI Example:
.. code-block:: bash
salt-cloud -f rescan_hba my-vmware-config host="hostSystemName"
salt-cloud -f rescan_hba my-vmware-config hba="hbaDeviceName" host="hostSystemName"
'''
if call != 'function':
raise SaltCloudSystemExit(
'The rescan_hba function must be called with '
'-f or --function.'
)
hba = kwargs.get('hba') if kwargs and 'hba' in kwargs else None
host_name = kwargs.get('host') if kwargs and 'host' in kwargs else None
if not host_name:
raise SaltCloudSystemExit(
'You must specify name of the host system.'
)
host_ref = salt.utils.vmware.get_mor_by_property(_get_si(), vim.HostSystem, host_name)
try:
if hba:
log.info('Rescanning HBA %s on host %s', hba, host_name)
host_ref.configManager.storageSystem.RescanHba(hba)
ret = 'rescanned HBA {0}'.format(hba)
else:
log.info('Rescanning all HBAs on host %s', host_name)
host_ref.configManager.storageSystem.RescanAllHba()
ret = 'rescanned all HBAs'
except Exception as exc:
log.error(
'Error while rescaning HBA on host %s: %s',
host_name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return {host_name: 'failed to rescan HBA'}
return {host_name: ret} | python | def rescan_hba(kwargs=None, call=None):
'''
To rescan a specified HBA or all the HBAs on the Host System
CLI Example:
.. code-block:: bash
salt-cloud -f rescan_hba my-vmware-config host="hostSystemName"
salt-cloud -f rescan_hba my-vmware-config hba="hbaDeviceName" host="hostSystemName"
'''
if call != 'function':
raise SaltCloudSystemExit(
'The rescan_hba function must be called with '
'-f or --function.'
)
hba = kwargs.get('hba') if kwargs and 'hba' in kwargs else None
host_name = kwargs.get('host') if kwargs and 'host' in kwargs else None
if not host_name:
raise SaltCloudSystemExit(
'You must specify name of the host system.'
)
host_ref = salt.utils.vmware.get_mor_by_property(_get_si(), vim.HostSystem, host_name)
try:
if hba:
log.info('Rescanning HBA %s on host %s', hba, host_name)
host_ref.configManager.storageSystem.RescanHba(hba)
ret = 'rescanned HBA {0}'.format(hba)
else:
log.info('Rescanning all HBAs on host %s', host_name)
host_ref.configManager.storageSystem.RescanAllHba()
ret = 'rescanned all HBAs'
except Exception as exc:
log.error(
'Error while rescaning HBA on host %s: %s',
host_name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return {host_name: 'failed to rescan HBA'}
return {host_name: ret} | [
"def",
"rescan_hba",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The rescan_hba function must be called with '",
"'-f or --function.'",
")",
"hba",
"=",
"kwargs",
"."... | To rescan a specified HBA or all the HBAs on the Host System
CLI Example:
.. code-block:: bash
salt-cloud -f rescan_hba my-vmware-config host="hostSystemName"
salt-cloud -f rescan_hba my-vmware-config hba="hbaDeviceName" host="hostSystemName" | [
"To",
"rescan",
"a",
"specified",
"HBA",
"or",
"all",
"the",
"HBAs",
"on",
"the",
"Host",
"System"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L3278-L3323 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | upgrade_tools_all | def upgrade_tools_all(call=None):
'''
To upgrade VMware Tools on all virtual machines present in
the specified provider
.. note::
If the virtual machine is running Windows OS, this function
will attempt to suppress the automatic reboot caused by a
VMware Tools upgrade.
CLI Example:
.. code-block:: bash
salt-cloud -f upgrade_tools_all my-vmware-config
'''
if call != 'function':
raise SaltCloudSystemExit(
'The upgrade_tools_all function must be called with '
'-f or --function.'
)
ret = {}
vm_properties = ["name"]
vm_list = salt.utils.vmware.get_mors_with_properties(_get_si(), vim.VirtualMachine, vm_properties)
for vm in vm_list:
ret[vm['name']] = _upg_tools_helper(vm['object'])
return ret | python | def upgrade_tools_all(call=None):
'''
To upgrade VMware Tools on all virtual machines present in
the specified provider
.. note::
If the virtual machine is running Windows OS, this function
will attempt to suppress the automatic reboot caused by a
VMware Tools upgrade.
CLI Example:
.. code-block:: bash
salt-cloud -f upgrade_tools_all my-vmware-config
'''
if call != 'function':
raise SaltCloudSystemExit(
'The upgrade_tools_all function must be called with '
'-f or --function.'
)
ret = {}
vm_properties = ["name"]
vm_list = salt.utils.vmware.get_mors_with_properties(_get_si(), vim.VirtualMachine, vm_properties)
for vm in vm_list:
ret[vm['name']] = _upg_tools_helper(vm['object'])
return ret | [
"def",
"upgrade_tools_all",
"(",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The upgrade_tools_all function must be called with '",
"'-f or --function.'",
")",
"ret",
"=",
"{",
"}",
"vm_properties",
"=",... | To upgrade VMware Tools on all virtual machines present in
the specified provider
.. note::
If the virtual machine is running Windows OS, this function
will attempt to suppress the automatic reboot caused by a
VMware Tools upgrade.
CLI Example:
.. code-block:: bash
salt-cloud -f upgrade_tools_all my-vmware-config | [
"To",
"upgrade",
"VMware",
"Tools",
"on",
"all",
"virtual",
"machines",
"present",
"in",
"the",
"specified",
"provider"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L3326-L3357 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | upgrade_tools | def upgrade_tools(name, reboot=False, call=None):
'''
To upgrade VMware Tools on a specified virtual machine.
.. note::
If the virtual machine is running Windows OS, use ``reboot=True``
to reboot the virtual machine after VMware tools upgrade. Default
is ``reboot=False``
CLI Example:
.. code-block:: bash
salt-cloud -a upgrade_tools vmname
salt-cloud -a upgrade_tools vmname reboot=True
'''
if call != 'action':
raise SaltCloudSystemExit(
'The upgrade_tools action must be called with '
'-a or --action.'
)
vm_ref = salt.utils.vmware.get_mor_by_property(_get_si(), vim.VirtualMachine, name)
return _upg_tools_helper(vm_ref, reboot) | python | def upgrade_tools(name, reboot=False, call=None):
'''
To upgrade VMware Tools on a specified virtual machine.
.. note::
If the virtual machine is running Windows OS, use ``reboot=True``
to reboot the virtual machine after VMware tools upgrade. Default
is ``reboot=False``
CLI Example:
.. code-block:: bash
salt-cloud -a upgrade_tools vmname
salt-cloud -a upgrade_tools vmname reboot=True
'''
if call != 'action':
raise SaltCloudSystemExit(
'The upgrade_tools action must be called with '
'-a or --action.'
)
vm_ref = salt.utils.vmware.get_mor_by_property(_get_si(), vim.VirtualMachine, name)
return _upg_tools_helper(vm_ref, reboot) | [
"def",
"upgrade_tools",
"(",
"name",
",",
"reboot",
"=",
"False",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The upgrade_tools action must be called with '",
"'-a or --action.'",
")",
"vm_ref",
"... | To upgrade VMware Tools on a specified virtual machine.
.. note::
If the virtual machine is running Windows OS, use ``reboot=True``
to reboot the virtual machine after VMware tools upgrade. Default
is ``reboot=False``
CLI Example:
.. code-block:: bash
salt-cloud -a upgrade_tools vmname
salt-cloud -a upgrade_tools vmname reboot=True | [
"To",
"upgrade",
"VMware",
"Tools",
"on",
"a",
"specified",
"virtual",
"machine",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L3360-L3385 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | list_hosts_by_cluster | def list_hosts_by_cluster(kwargs=None, call=None):
'''
List hosts for each cluster; or hosts for a specified cluster in
this VMware environment
To list hosts for each cluster:
CLI Example:
.. code-block:: bash
salt-cloud -f list_hosts_by_cluster my-vmware-config
To list hosts for a specified cluster:
CLI Example:
.. code-block:: bash
salt-cloud -f list_hosts_by_cluster my-vmware-config cluster="clusterName"
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_hosts_by_cluster function must be called with '
'-f or --function.'
)
ret = {}
cluster_name = kwargs.get('cluster') if kwargs and 'cluster' in kwargs else None
cluster_properties = ["name"]
cluster_list = salt.utils.vmware.get_mors_with_properties(_get_si(),
vim.ClusterComputeResource,
cluster_properties)
for cluster in cluster_list:
ret[cluster['name']] = []
for host in cluster['object'].host:
if isinstance(host, vim.HostSystem):
ret[cluster['name']].append(host.name)
if cluster_name and cluster_name == cluster['name']:
return {'Hosts by Cluster': {cluster_name: ret[cluster_name]}}
return {'Hosts by Cluster': ret} | python | def list_hosts_by_cluster(kwargs=None, call=None):
'''
List hosts for each cluster; or hosts for a specified cluster in
this VMware environment
To list hosts for each cluster:
CLI Example:
.. code-block:: bash
salt-cloud -f list_hosts_by_cluster my-vmware-config
To list hosts for a specified cluster:
CLI Example:
.. code-block:: bash
salt-cloud -f list_hosts_by_cluster my-vmware-config cluster="clusterName"
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_hosts_by_cluster function must be called with '
'-f or --function.'
)
ret = {}
cluster_name = kwargs.get('cluster') if kwargs and 'cluster' in kwargs else None
cluster_properties = ["name"]
cluster_list = salt.utils.vmware.get_mors_with_properties(_get_si(),
vim.ClusterComputeResource,
cluster_properties)
for cluster in cluster_list:
ret[cluster['name']] = []
for host in cluster['object'].host:
if isinstance(host, vim.HostSystem):
ret[cluster['name']].append(host.name)
if cluster_name and cluster_name == cluster['name']:
return {'Hosts by Cluster': {cluster_name: ret[cluster_name]}}
return {'Hosts by Cluster': ret} | [
"def",
"list_hosts_by_cluster",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_hosts_by_cluster function must be called with '",
"'-f or --function.'",
")",
"ret",
... | List hosts for each cluster; or hosts for a specified cluster in
this VMware environment
To list hosts for each cluster:
CLI Example:
.. code-block:: bash
salt-cloud -f list_hosts_by_cluster my-vmware-config
To list hosts for a specified cluster:
CLI Example:
.. code-block:: bash
salt-cloud -f list_hosts_by_cluster my-vmware-config cluster="clusterName" | [
"List",
"hosts",
"for",
"each",
"cluster",
";",
"or",
"hosts",
"for",
"a",
"specified",
"cluster",
"in",
"this",
"VMware",
"environment"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L3388-L3431 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | list_clusters_by_datacenter | def list_clusters_by_datacenter(kwargs=None, call=None):
'''
List clusters for each datacenter; or clusters for a specified datacenter in
this VMware environment
To list clusters for each datacenter:
CLI Example:
.. code-block:: bash
salt-cloud -f list_clusters_by_datacenter my-vmware-config
To list clusters for a specified datacenter:
CLI Example:
.. code-block:: bash
salt-cloud -f list_clusters_by_datacenter my-vmware-config datacenter="datacenterName"
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_clusters_by_datacenter function must be called with '
'-f or --function.'
)
ret = {}
datacenter_name = kwargs.get('datacenter') if kwargs and 'datacenter' in kwargs else None
datacenter_properties = ["name"]
datacenter_list = salt.utils.vmware.get_mors_with_properties(_get_si(), vim.Datacenter, datacenter_properties)
for datacenter in datacenter_list:
ret[datacenter['name']] = []
for cluster in datacenter['object'].hostFolder.childEntity:
if isinstance(cluster, vim.ClusterComputeResource):
ret[datacenter['name']].append(cluster.name)
if datacenter_name and datacenter_name == datacenter['name']:
return {'Clusters by Datacenter': {datacenter_name: ret[datacenter_name]}}
return {'Clusters by Datacenter': ret} | python | def list_clusters_by_datacenter(kwargs=None, call=None):
'''
List clusters for each datacenter; or clusters for a specified datacenter in
this VMware environment
To list clusters for each datacenter:
CLI Example:
.. code-block:: bash
salt-cloud -f list_clusters_by_datacenter my-vmware-config
To list clusters for a specified datacenter:
CLI Example:
.. code-block:: bash
salt-cloud -f list_clusters_by_datacenter my-vmware-config datacenter="datacenterName"
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_clusters_by_datacenter function must be called with '
'-f or --function.'
)
ret = {}
datacenter_name = kwargs.get('datacenter') if kwargs and 'datacenter' in kwargs else None
datacenter_properties = ["name"]
datacenter_list = salt.utils.vmware.get_mors_with_properties(_get_si(), vim.Datacenter, datacenter_properties)
for datacenter in datacenter_list:
ret[datacenter['name']] = []
for cluster in datacenter['object'].hostFolder.childEntity:
if isinstance(cluster, vim.ClusterComputeResource):
ret[datacenter['name']].append(cluster.name)
if datacenter_name and datacenter_name == datacenter['name']:
return {'Clusters by Datacenter': {datacenter_name: ret[datacenter_name]}}
return {'Clusters by Datacenter': ret} | [
"def",
"list_clusters_by_datacenter",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_clusters_by_datacenter function must be called with '",
"'-f or --function.'",
")",... | List clusters for each datacenter; or clusters for a specified datacenter in
this VMware environment
To list clusters for each datacenter:
CLI Example:
.. code-block:: bash
salt-cloud -f list_clusters_by_datacenter my-vmware-config
To list clusters for a specified datacenter:
CLI Example:
.. code-block:: bash
salt-cloud -f list_clusters_by_datacenter my-vmware-config datacenter="datacenterName" | [
"List",
"clusters",
"for",
"each",
"datacenter",
";",
"or",
"clusters",
"for",
"a",
"specified",
"datacenter",
"in",
"this",
"VMware",
"environment"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L3434-L3475 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | list_hbas | def list_hbas(kwargs=None, call=None):
'''
List all HBAs for each host system; or all HBAs for a specified host
system; or HBAs of specified type for each host system; or HBAs of
specified type for a specified host system in this VMware environment
.. note::
You can specify type as either ``parallel``, ``iscsi``, ``block``
or ``fibre``.
To list all HBAs for each host system:
CLI Example:
.. code-block:: bash
salt-cloud -f list_hbas my-vmware-config
To list all HBAs for a specified host system:
CLI Example:
.. code-block:: bash
salt-cloud -f list_hbas my-vmware-config host="hostSystemName"
To list HBAs of specified type for each host system:
CLI Example:
.. code-block:: bash
salt-cloud -f list_hbas my-vmware-config type="HBAType"
To list HBAs of specified type for a specified host system:
CLI Example:
.. code-block:: bash
salt-cloud -f list_hbas my-vmware-config host="hostSystemName" type="HBAtype"
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_hbas function must be called with '
'-f or --function.'
)
ret = {}
hba_type = kwargs.get('type').lower() if kwargs and 'type' in kwargs else None
host_name = kwargs.get('host') if kwargs and 'host' in kwargs else None
host_properties = [
"name",
"config.storageDevice.hostBusAdapter"
]
if hba_type and hba_type not in ["parallel", "block", "iscsi", "fibre"]:
raise SaltCloudSystemExit(
'Specified hba type {0} currently not supported.'.format(hba_type)
)
host_list = salt.utils.vmware.get_mors_with_properties(_get_si(), vim.HostSystem, host_properties)
for host in host_list:
ret[host['name']] = {}
for hba in host['config.storageDevice.hostBusAdapter']:
hba_spec = {
'driver': hba.driver,
'status': hba.status,
'type': type(hba).__name__.rsplit(".", 1)[1]
}
if hba_type:
if isinstance(hba, _get_hba_type(hba_type)):
if hba.model in ret[host['name']]:
ret[host['name']][hba.model][hba.device] = hba_spec
else:
ret[host['name']][hba.model] = {hba.device: hba_spec}
else:
if hba.model in ret[host['name']]:
ret[host['name']][hba.model][hba.device] = hba_spec
else:
ret[host['name']][hba.model] = {hba.device: hba_spec}
if host['name'] == host_name:
return {'HBAs by Host': {host_name: ret[host_name]}}
return {'HBAs by Host': ret} | python | def list_hbas(kwargs=None, call=None):
'''
List all HBAs for each host system; or all HBAs for a specified host
system; or HBAs of specified type for each host system; or HBAs of
specified type for a specified host system in this VMware environment
.. note::
You can specify type as either ``parallel``, ``iscsi``, ``block``
or ``fibre``.
To list all HBAs for each host system:
CLI Example:
.. code-block:: bash
salt-cloud -f list_hbas my-vmware-config
To list all HBAs for a specified host system:
CLI Example:
.. code-block:: bash
salt-cloud -f list_hbas my-vmware-config host="hostSystemName"
To list HBAs of specified type for each host system:
CLI Example:
.. code-block:: bash
salt-cloud -f list_hbas my-vmware-config type="HBAType"
To list HBAs of specified type for a specified host system:
CLI Example:
.. code-block:: bash
salt-cloud -f list_hbas my-vmware-config host="hostSystemName" type="HBAtype"
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_hbas function must be called with '
'-f or --function.'
)
ret = {}
hba_type = kwargs.get('type').lower() if kwargs and 'type' in kwargs else None
host_name = kwargs.get('host') if kwargs and 'host' in kwargs else None
host_properties = [
"name",
"config.storageDevice.hostBusAdapter"
]
if hba_type and hba_type not in ["parallel", "block", "iscsi", "fibre"]:
raise SaltCloudSystemExit(
'Specified hba type {0} currently not supported.'.format(hba_type)
)
host_list = salt.utils.vmware.get_mors_with_properties(_get_si(), vim.HostSystem, host_properties)
for host in host_list:
ret[host['name']] = {}
for hba in host['config.storageDevice.hostBusAdapter']:
hba_spec = {
'driver': hba.driver,
'status': hba.status,
'type': type(hba).__name__.rsplit(".", 1)[1]
}
if hba_type:
if isinstance(hba, _get_hba_type(hba_type)):
if hba.model in ret[host['name']]:
ret[host['name']][hba.model][hba.device] = hba_spec
else:
ret[host['name']][hba.model] = {hba.device: hba_spec}
else:
if hba.model in ret[host['name']]:
ret[host['name']][hba.model][hba.device] = hba_spec
else:
ret[host['name']][hba.model] = {hba.device: hba_spec}
if host['name'] == host_name:
return {'HBAs by Host': {host_name: ret[host_name]}}
return {'HBAs by Host': ret} | [
"def",
"list_hbas",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_hbas function must be called with '",
"'-f or --function.'",
")",
"ret",
"=",
"{",
"}",
"hb... | List all HBAs for each host system; or all HBAs for a specified host
system; or HBAs of specified type for each host system; or HBAs of
specified type for a specified host system in this VMware environment
.. note::
You can specify type as either ``parallel``, ``iscsi``, ``block``
or ``fibre``.
To list all HBAs for each host system:
CLI Example:
.. code-block:: bash
salt-cloud -f list_hbas my-vmware-config
To list all HBAs for a specified host system:
CLI Example:
.. code-block:: bash
salt-cloud -f list_hbas my-vmware-config host="hostSystemName"
To list HBAs of specified type for each host system:
CLI Example:
.. code-block:: bash
salt-cloud -f list_hbas my-vmware-config type="HBAType"
To list HBAs of specified type for a specified host system:
CLI Example:
.. code-block:: bash
salt-cloud -f list_hbas my-vmware-config host="hostSystemName" type="HBAtype" | [
"List",
"all",
"HBAs",
"for",
"each",
"host",
"system",
";",
"or",
"all",
"HBAs",
"for",
"a",
"specified",
"host",
"system",
";",
"or",
"HBAs",
"of",
"specified",
"type",
"for",
"each",
"host",
"system",
";",
"or",
"HBAs",
"of",
"specified",
"type",
"f... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L3524-L3610 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | list_dvs | def list_dvs(kwargs=None, call=None):
'''
List all the distributed virtual switches for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_dvs my-vmware-config
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_dvs function must be called with '
'-f or --function.'
)
return {'Distributed Virtual Switches': salt.utils.vmware.list_dvs(_get_si())} | python | def list_dvs(kwargs=None, call=None):
'''
List all the distributed virtual switches for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_dvs my-vmware-config
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_dvs function must be called with '
'-f or --function.'
)
return {'Distributed Virtual Switches': salt.utils.vmware.list_dvs(_get_si())} | [
"def",
"list_dvs",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_dvs function must be called with '",
"'-f or --function.'",
")",
"return",
"{",
"'Distributed Vi... | List all the distributed virtual switches for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_dvs my-vmware-config | [
"List",
"all",
"the",
"distributed",
"virtual",
"switches",
"for",
"this",
"VMware",
"environment"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L3613-L3629 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | list_vapps | def list_vapps(kwargs=None, call=None):
'''
List all the vApps for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_vapps my-vmware-config
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_vapps function must be called with '
'-f or --function.'
)
return {'vApps': salt.utils.vmware.list_vapps(_get_si())} | python | def list_vapps(kwargs=None, call=None):
'''
List all the vApps for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_vapps my-vmware-config
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_vapps function must be called with '
'-f or --function.'
)
return {'vApps': salt.utils.vmware.list_vapps(_get_si())} | [
"def",
"list_vapps",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_vapps function must be called with '",
"'-f or --function.'",
")",
"return",
"{",
"'vApps'",
... | List all the vApps for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_vapps my-vmware-config | [
"List",
"all",
"the",
"vApps",
"for",
"this",
"VMware",
"environment"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L3632-L3648 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | enter_maintenance_mode | def enter_maintenance_mode(kwargs=None, call=None):
'''
To put the specified host system in maintenance mode in this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f enter_maintenance_mode my-vmware-config host="myHostSystemName"
'''
if call != 'function':
raise SaltCloudSystemExit(
'The enter_maintenance_mode function must be called with '
'-f or --function.'
)
host_name = kwargs.get('host') if kwargs and 'host' in kwargs else None
host_ref = salt.utils.vmware.get_mor_by_property(_get_si(), vim.HostSystem, host_name)
if not host_name or not host_ref:
raise SaltCloudSystemExit(
'You must specify a valid name of the host system.'
)
if host_ref.runtime.inMaintenanceMode:
return {host_name: 'already in maintenance mode'}
try:
task = host_ref.EnterMaintenanceMode(timeout=0, evacuatePoweredOffVms=True)
salt.utils.vmware.wait_for_task(task, host_name, 'enter maintenance mode')
except Exception as exc:
log.error(
'Error while moving host system %s in maintenance mode: %s',
host_name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return {host_name: 'failed to enter maintenance mode'}
return {host_name: 'entered maintenance mode'} | python | def enter_maintenance_mode(kwargs=None, call=None):
'''
To put the specified host system in maintenance mode in this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f enter_maintenance_mode my-vmware-config host="myHostSystemName"
'''
if call != 'function':
raise SaltCloudSystemExit(
'The enter_maintenance_mode function must be called with '
'-f or --function.'
)
host_name = kwargs.get('host') if kwargs and 'host' in kwargs else None
host_ref = salt.utils.vmware.get_mor_by_property(_get_si(), vim.HostSystem, host_name)
if not host_name or not host_ref:
raise SaltCloudSystemExit(
'You must specify a valid name of the host system.'
)
if host_ref.runtime.inMaintenanceMode:
return {host_name: 'already in maintenance mode'}
try:
task = host_ref.EnterMaintenanceMode(timeout=0, evacuatePoweredOffVms=True)
salt.utils.vmware.wait_for_task(task, host_name, 'enter maintenance mode')
except Exception as exc:
log.error(
'Error while moving host system %s in maintenance mode: %s',
host_name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return {host_name: 'failed to enter maintenance mode'}
return {host_name: 'entered maintenance mode'} | [
"def",
"enter_maintenance_mode",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The enter_maintenance_mode function must be called with '",
"'-f or --function.'",
")",
"host_n... | To put the specified host system in maintenance mode in this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f enter_maintenance_mode my-vmware-config host="myHostSystemName" | [
"To",
"put",
"the",
"specified",
"host",
"system",
"in",
"maintenance",
"mode",
"in",
"this",
"VMware",
"environment"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L3651-L3691 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | create_folder | def create_folder(kwargs=None, call=None):
'''
Create the specified folder path in this VMware environment
.. note::
To create a Host and Cluster Folder under a Datacenter, specify
``path="/yourDatacenterName/host/yourFolderName"``
To create a Network Folder under a Datacenter, specify
``path="/yourDatacenterName/network/yourFolderName"``
To create a Storage Folder under a Datacenter, specify
``path="/yourDatacenterName/datastore/yourFolderName"``
To create a VM and Template Folder under a Datacenter, specify
``path="/yourDatacenterName/vm/yourFolderName"``
CLI Example:
.. code-block:: bash
salt-cloud -f create_folder my-vmware-config path="/Local/a/b/c"
salt-cloud -f create_folder my-vmware-config path="/MyDatacenter/vm/MyVMFolder"
salt-cloud -f create_folder my-vmware-config path="/MyDatacenter/host/MyHostFolder"
salt-cloud -f create_folder my-vmware-config path="/MyDatacenter/network/MyNetworkFolder"
salt-cloud -f create_folder my-vmware-config path="/MyDatacenter/storage/MyStorageFolder"
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_folder function must be called with '
'-f or --function.'
)
# Get the service instance object
si = _get_si()
folder_path = kwargs.get('path') if kwargs and 'path' in kwargs else None
if not folder_path:
raise SaltCloudSystemExit(
'You must specify a non empty folder path.'
)
folder_refs = []
inventory_path = '/'
path_exists = True
# Split the path in a list and loop over it to check for its existence
for index, folder_name in enumerate(os.path.normpath(folder_path.strip('/')).split('/')):
inventory_path = os.path.join(inventory_path, folder_name)
folder_ref = si.content.searchIndex.FindByInventoryPath(inventoryPath=inventory_path)
if isinstance(folder_ref, vim.Folder):
# This is a folder that exists so just append and skip it
log.debug("Path %s/ exists in the inventory", inventory_path)
folder_refs.append(folder_ref)
elif isinstance(folder_ref, vim.Datacenter):
# This is a datacenter that exists so just append and skip it
log.debug("Path %s/ exists in the inventory", inventory_path)
folder_refs.append(folder_ref)
else:
path_exists = False
if not folder_refs:
# If this is the first folder, create it under the rootFolder
log.debug("Creating folder %s under rootFolder in the inventory", folder_name)
folder_refs.append(si.content.rootFolder.CreateFolder(folder_name))
else:
# Create the folder under the parent folder
log.debug("Creating path %s/ in the inventory", inventory_path)
folder_refs.append(folder_refs[index-1].CreateFolder(folder_name))
if path_exists:
return {inventory_path: 'specfied path already exists'}
return {inventory_path: 'created the specified path'} | python | def create_folder(kwargs=None, call=None):
'''
Create the specified folder path in this VMware environment
.. note::
To create a Host and Cluster Folder under a Datacenter, specify
``path="/yourDatacenterName/host/yourFolderName"``
To create a Network Folder under a Datacenter, specify
``path="/yourDatacenterName/network/yourFolderName"``
To create a Storage Folder under a Datacenter, specify
``path="/yourDatacenterName/datastore/yourFolderName"``
To create a VM and Template Folder under a Datacenter, specify
``path="/yourDatacenterName/vm/yourFolderName"``
CLI Example:
.. code-block:: bash
salt-cloud -f create_folder my-vmware-config path="/Local/a/b/c"
salt-cloud -f create_folder my-vmware-config path="/MyDatacenter/vm/MyVMFolder"
salt-cloud -f create_folder my-vmware-config path="/MyDatacenter/host/MyHostFolder"
salt-cloud -f create_folder my-vmware-config path="/MyDatacenter/network/MyNetworkFolder"
salt-cloud -f create_folder my-vmware-config path="/MyDatacenter/storage/MyStorageFolder"
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_folder function must be called with '
'-f or --function.'
)
# Get the service instance object
si = _get_si()
folder_path = kwargs.get('path') if kwargs and 'path' in kwargs else None
if not folder_path:
raise SaltCloudSystemExit(
'You must specify a non empty folder path.'
)
folder_refs = []
inventory_path = '/'
path_exists = True
# Split the path in a list and loop over it to check for its existence
for index, folder_name in enumerate(os.path.normpath(folder_path.strip('/')).split('/')):
inventory_path = os.path.join(inventory_path, folder_name)
folder_ref = si.content.searchIndex.FindByInventoryPath(inventoryPath=inventory_path)
if isinstance(folder_ref, vim.Folder):
# This is a folder that exists so just append and skip it
log.debug("Path %s/ exists in the inventory", inventory_path)
folder_refs.append(folder_ref)
elif isinstance(folder_ref, vim.Datacenter):
# This is a datacenter that exists so just append and skip it
log.debug("Path %s/ exists in the inventory", inventory_path)
folder_refs.append(folder_ref)
else:
path_exists = False
if not folder_refs:
# If this is the first folder, create it under the rootFolder
log.debug("Creating folder %s under rootFolder in the inventory", folder_name)
folder_refs.append(si.content.rootFolder.CreateFolder(folder_name))
else:
# Create the folder under the parent folder
log.debug("Creating path %s/ in the inventory", inventory_path)
folder_refs.append(folder_refs[index-1].CreateFolder(folder_name))
if path_exists:
return {inventory_path: 'specfied path already exists'}
return {inventory_path: 'created the specified path'} | [
"def",
"create_folder",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The create_folder function must be called with '",
"'-f or --function.'",
")",
"# Get the service instan... | Create the specified folder path in this VMware environment
.. note::
To create a Host and Cluster Folder under a Datacenter, specify
``path="/yourDatacenterName/host/yourFolderName"``
To create a Network Folder under a Datacenter, specify
``path="/yourDatacenterName/network/yourFolderName"``
To create a Storage Folder under a Datacenter, specify
``path="/yourDatacenterName/datastore/yourFolderName"``
To create a VM and Template Folder under a Datacenter, specify
``path="/yourDatacenterName/vm/yourFolderName"``
CLI Example:
.. code-block:: bash
salt-cloud -f create_folder my-vmware-config path="/Local/a/b/c"
salt-cloud -f create_folder my-vmware-config path="/MyDatacenter/vm/MyVMFolder"
salt-cloud -f create_folder my-vmware-config path="/MyDatacenter/host/MyHostFolder"
salt-cloud -f create_folder my-vmware-config path="/MyDatacenter/network/MyNetworkFolder"
salt-cloud -f create_folder my-vmware-config path="/MyDatacenter/storage/MyStorageFolder" | [
"Create",
"the",
"specified",
"folder",
"path",
"in",
"this",
"VMware",
"environment"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L3737-L3811 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | create_snapshot | def create_snapshot(name, kwargs=None, call=None):
'''
Create a snapshot of the specified virtual machine in this VMware
environment
.. note::
If the VM is powered on, the internal state of the VM (memory
dump) is included in the snapshot by default which will also set
the power state of the snapshot to "powered on". You can set
``memdump=False`` to override this. This field is ignored if
the virtual machine is powered off or if the VM does not support
snapshots with memory dumps. Default is ``memdump=True``
.. note::
If the VM is powered on when the snapshot is taken, VMware Tools
can be used to quiesce the file system in the virtual machine by
setting ``quiesce=True``. This field is ignored if the virtual
machine is powered off; if VMware Tools are not available or if
``memdump=True``. Default is ``quiesce=False``
CLI Example:
.. code-block:: bash
salt-cloud -a create_snapshot vmname snapshot_name="mySnapshot"
salt-cloud -a create_snapshot vmname snapshot_name="mySnapshot" [description="My snapshot"] [memdump=False] [quiesce=True]
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_snapshot action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
snapshot_name = kwargs.get('snapshot_name') if kwargs and 'snapshot_name' in kwargs else None
if not snapshot_name:
raise SaltCloudSystemExit(
'You must specify snapshot name for the snapshot to be created.'
)
memdump = _str_to_bool(kwargs.get('memdump', True))
quiesce = _str_to_bool(kwargs.get('quiesce', False))
vm_ref = salt.utils.vmware.get_mor_by_property(_get_si(), vim.VirtualMachine, name)
if vm_ref.summary.runtime.powerState != "poweredOn":
log.debug('VM %s is not powered on. Setting both memdump and quiesce to False', name)
memdump = False
quiesce = False
if memdump and quiesce:
# Either memdump or quiesce should be set to True
log.warning('You can only set either memdump or quiesce to True. Setting quiesce=False')
quiesce = False
desc = kwargs.get('description') if 'description' in kwargs else ''
try:
task = vm_ref.CreateSnapshot(snapshot_name, desc, memdump, quiesce)
salt.utils.vmware.wait_for_task(task, name, 'create snapshot', 5, 'info')
except Exception as exc:
log.error(
'Error while creating snapshot of %s: %s',
name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return 'failed to create snapshot'
return {'Snapshot created successfully': _get_snapshots(vm_ref.snapshot.rootSnapshotList,
vm_ref.snapshot.currentSnapshot)} | python | def create_snapshot(name, kwargs=None, call=None):
'''
Create a snapshot of the specified virtual machine in this VMware
environment
.. note::
If the VM is powered on, the internal state of the VM (memory
dump) is included in the snapshot by default which will also set
the power state of the snapshot to "powered on". You can set
``memdump=False`` to override this. This field is ignored if
the virtual machine is powered off or if the VM does not support
snapshots with memory dumps. Default is ``memdump=True``
.. note::
If the VM is powered on when the snapshot is taken, VMware Tools
can be used to quiesce the file system in the virtual machine by
setting ``quiesce=True``. This field is ignored if the virtual
machine is powered off; if VMware Tools are not available or if
``memdump=True``. Default is ``quiesce=False``
CLI Example:
.. code-block:: bash
salt-cloud -a create_snapshot vmname snapshot_name="mySnapshot"
salt-cloud -a create_snapshot vmname snapshot_name="mySnapshot" [description="My snapshot"] [memdump=False] [quiesce=True]
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_snapshot action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
snapshot_name = kwargs.get('snapshot_name') if kwargs and 'snapshot_name' in kwargs else None
if not snapshot_name:
raise SaltCloudSystemExit(
'You must specify snapshot name for the snapshot to be created.'
)
memdump = _str_to_bool(kwargs.get('memdump', True))
quiesce = _str_to_bool(kwargs.get('quiesce', False))
vm_ref = salt.utils.vmware.get_mor_by_property(_get_si(), vim.VirtualMachine, name)
if vm_ref.summary.runtime.powerState != "poweredOn":
log.debug('VM %s is not powered on. Setting both memdump and quiesce to False', name)
memdump = False
quiesce = False
if memdump and quiesce:
# Either memdump or quiesce should be set to True
log.warning('You can only set either memdump or quiesce to True. Setting quiesce=False')
quiesce = False
desc = kwargs.get('description') if 'description' in kwargs else ''
try:
task = vm_ref.CreateSnapshot(snapshot_name, desc, memdump, quiesce)
salt.utils.vmware.wait_for_task(task, name, 'create snapshot', 5, 'info')
except Exception as exc:
log.error(
'Error while creating snapshot of %s: %s',
name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return 'failed to create snapshot'
return {'Snapshot created successfully': _get_snapshots(vm_ref.snapshot.rootSnapshotList,
vm_ref.snapshot.currentSnapshot)} | [
"def",
"create_snapshot",
"(",
"name",
",",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The create_snapshot action must be called with '",
"'-a or --action.'",
")",
"if",
"k... | Create a snapshot of the specified virtual machine in this VMware
environment
.. note::
If the VM is powered on, the internal state of the VM (memory
dump) is included in the snapshot by default which will also set
the power state of the snapshot to "powered on". You can set
``memdump=False`` to override this. This field is ignored if
the virtual machine is powered off or if the VM does not support
snapshots with memory dumps. Default is ``memdump=True``
.. note::
If the VM is powered on when the snapshot is taken, VMware Tools
can be used to quiesce the file system in the virtual machine by
setting ``quiesce=True``. This field is ignored if the virtual
machine is powered off; if VMware Tools are not available or if
``memdump=True``. Default is ``quiesce=False``
CLI Example:
.. code-block:: bash
salt-cloud -a create_snapshot vmname snapshot_name="mySnapshot"
salt-cloud -a create_snapshot vmname snapshot_name="mySnapshot" [description="My snapshot"] [memdump=False] [quiesce=True] | [
"Create",
"a",
"snapshot",
"of",
"the",
"specified",
"virtual",
"machine",
"in",
"this",
"VMware",
"environment"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L3814-L3889 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | revert_to_snapshot | def revert_to_snapshot(name, kwargs=None, call=None):
'''
Revert virtual machine to it's current snapshot. If no snapshot
exists, the state of the virtual machine remains unchanged
.. note::
The virtual machine will be powered on if the power state of
the snapshot when it was created was set to "Powered On". Set
``power_off=True`` so that the virtual machine stays powered
off regardless of the power state of the snapshot when it was
created. Default is ``power_off=False``.
If the power state of the snapshot when it was created was
"Powered On" and if ``power_off=True``, the VM will be put in
suspended state after it has been reverted to the snapshot.
CLI Example:
.. code-block:: bash
salt-cloud -a revert_to_snapshot vmame [power_off=True]
salt-cloud -a revert_to_snapshot vmame snapshot_name="selectedSnapshot" [power_off=True]
'''
if call != 'action':
raise SaltCloudSystemExit(
'The revert_to_snapshot action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
snapshot_name = kwargs.get('snapshot_name') if kwargs and 'snapshot_name' in kwargs else None
suppress_power_on = _str_to_bool(kwargs.get('power_off', False))
vm_ref = salt.utils.vmware.get_mor_by_property(_get_si(), vim.VirtualMachine, name)
if not vm_ref.rootSnapshot:
log.error('VM %s does not contain any current snapshots', name)
return 'revert failed'
msg = "reverted to current snapshot"
try:
if snapshot_name is None:
log.debug("Reverting VM %s to current snapshot", name)
task = vm_ref.RevertToCurrentSnapshot(suppressPowerOn=suppress_power_on)
else:
log.debug("Reverting VM %s to snapshot %s", name, snapshot_name)
msg = "reverted to snapshot {0}".format(snapshot_name)
snapshot_ref = _get_snapshot_ref_by_name(vm_ref, snapshot_name)
if snapshot_ref is None:
return 'specified snapshot \'{0}\' does not exist'.format(snapshot_name)
task = snapshot_ref.snapshot.Revert(suppressPowerOn=suppress_power_on)
salt.utils.vmware.wait_for_task(task, name, 'revert to snapshot', 5, 'info')
except Exception as exc:
log.error(
'Error while reverting VM %s to snapshot: %s',
name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return 'revert failed'
return msg | python | def revert_to_snapshot(name, kwargs=None, call=None):
'''
Revert virtual machine to it's current snapshot. If no snapshot
exists, the state of the virtual machine remains unchanged
.. note::
The virtual machine will be powered on if the power state of
the snapshot when it was created was set to "Powered On". Set
``power_off=True`` so that the virtual machine stays powered
off regardless of the power state of the snapshot when it was
created. Default is ``power_off=False``.
If the power state of the snapshot when it was created was
"Powered On" and if ``power_off=True``, the VM will be put in
suspended state after it has been reverted to the snapshot.
CLI Example:
.. code-block:: bash
salt-cloud -a revert_to_snapshot vmame [power_off=True]
salt-cloud -a revert_to_snapshot vmame snapshot_name="selectedSnapshot" [power_off=True]
'''
if call != 'action':
raise SaltCloudSystemExit(
'The revert_to_snapshot action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
snapshot_name = kwargs.get('snapshot_name') if kwargs and 'snapshot_name' in kwargs else None
suppress_power_on = _str_to_bool(kwargs.get('power_off', False))
vm_ref = salt.utils.vmware.get_mor_by_property(_get_si(), vim.VirtualMachine, name)
if not vm_ref.rootSnapshot:
log.error('VM %s does not contain any current snapshots', name)
return 'revert failed'
msg = "reverted to current snapshot"
try:
if snapshot_name is None:
log.debug("Reverting VM %s to current snapshot", name)
task = vm_ref.RevertToCurrentSnapshot(suppressPowerOn=suppress_power_on)
else:
log.debug("Reverting VM %s to snapshot %s", name, snapshot_name)
msg = "reverted to snapshot {0}".format(snapshot_name)
snapshot_ref = _get_snapshot_ref_by_name(vm_ref, snapshot_name)
if snapshot_ref is None:
return 'specified snapshot \'{0}\' does not exist'.format(snapshot_name)
task = snapshot_ref.snapshot.Revert(suppressPowerOn=suppress_power_on)
salt.utils.vmware.wait_for_task(task, name, 'revert to snapshot', 5, 'info')
except Exception as exc:
log.error(
'Error while reverting VM %s to snapshot: %s',
name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return 'revert failed'
return msg | [
"def",
"revert_to_snapshot",
"(",
"name",
",",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The revert_to_snapshot action must be called with '",
"'-a or --action.'",
")",
"if"... | Revert virtual machine to it's current snapshot. If no snapshot
exists, the state of the virtual machine remains unchanged
.. note::
The virtual machine will be powered on if the power state of
the snapshot when it was created was set to "Powered On". Set
``power_off=True`` so that the virtual machine stays powered
off regardless of the power state of the snapshot when it was
created. Default is ``power_off=False``.
If the power state of the snapshot when it was created was
"Powered On" and if ``power_off=True``, the VM will be put in
suspended state after it has been reverted to the snapshot.
CLI Example:
.. code-block:: bash
salt-cloud -a revert_to_snapshot vmame [power_off=True]
salt-cloud -a revert_to_snapshot vmame snapshot_name="selectedSnapshot" [power_off=True] | [
"Revert",
"virtual",
"machine",
"to",
"it",
"s",
"current",
"snapshot",
".",
"If",
"no",
"snapshot",
"exists",
"the",
"state",
"of",
"the",
"virtual",
"machine",
"remains",
"unchanged"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L3892-L3960 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | remove_snapshot | def remove_snapshot(name, kwargs=None, call=None):
'''
Remove a snapshot of the specified virtual machine in this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -a remove_snapshot vmname snapshot_name="mySnapshot"
salt-cloud -a remove_snapshot vmname snapshot_name="mySnapshot" [remove_children="True"]
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_snapshot action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
snapshot_name = kwargs.get('snapshot_name') if kwargs and 'snapshot_name' in kwargs else None
remove_children = _str_to_bool(kwargs.get('remove_children', False))
if not snapshot_name:
raise SaltCloudSystemExit(
'You must specify snapshot name for the snapshot to be deleted.'
)
vm_ref = salt.utils.vmware.get_mor_by_property(_get_si(), vim.VirtualMachine, name)
if not _get_snapshot_ref_by_name(vm_ref, snapshot_name):
raise SaltCloudSystemExit(
'Сould not find the snapshot with the specified name.'
)
try:
snap_obj = _get_snapshot_ref_by_name(vm_ref, snapshot_name).snapshot
task = snap_obj.RemoveSnapshot_Task(remove_children)
salt.utils.vmware.wait_for_task(task, name, 'remove snapshot', 5, 'info')
except Exception as exc:
log.error(
'Error while removing snapshot of %s: %s',
name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return 'failed to remove snapshot'
if vm_ref.snapshot:
return {'Snapshot removed successfully':
_get_snapshots(vm_ref.snapshot.rootSnapshotList,
vm_ref.snapshot.currentSnapshot)}
return 'Snapshots removed successfully' | python | def remove_snapshot(name, kwargs=None, call=None):
'''
Remove a snapshot of the specified virtual machine in this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -a remove_snapshot vmname snapshot_name="mySnapshot"
salt-cloud -a remove_snapshot vmname snapshot_name="mySnapshot" [remove_children="True"]
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_snapshot action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
snapshot_name = kwargs.get('snapshot_name') if kwargs and 'snapshot_name' in kwargs else None
remove_children = _str_to_bool(kwargs.get('remove_children', False))
if not snapshot_name:
raise SaltCloudSystemExit(
'You must specify snapshot name for the snapshot to be deleted.'
)
vm_ref = salt.utils.vmware.get_mor_by_property(_get_si(), vim.VirtualMachine, name)
if not _get_snapshot_ref_by_name(vm_ref, snapshot_name):
raise SaltCloudSystemExit(
'Сould not find the snapshot with the specified name.'
)
try:
snap_obj = _get_snapshot_ref_by_name(vm_ref, snapshot_name).snapshot
task = snap_obj.RemoveSnapshot_Task(remove_children)
salt.utils.vmware.wait_for_task(task, name, 'remove snapshot', 5, 'info')
except Exception as exc:
log.error(
'Error while removing snapshot of %s: %s',
name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return 'failed to remove snapshot'
if vm_ref.snapshot:
return {'Snapshot removed successfully':
_get_snapshots(vm_ref.snapshot.rootSnapshotList,
vm_ref.snapshot.currentSnapshot)}
return 'Snapshots removed successfully' | [
"def",
"remove_snapshot",
"(",
"name",
",",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The create_snapshot action must be called with '",
"'-a or --action.'",
")",
"if",
"k... | Remove a snapshot of the specified virtual machine in this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -a remove_snapshot vmname snapshot_name="mySnapshot"
salt-cloud -a remove_snapshot vmname snapshot_name="mySnapshot" [remove_children="True"] | [
"Remove",
"a",
"snapshot",
"of",
"the",
"specified",
"virtual",
"machine",
"in",
"this",
"VMware",
"environment"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L3963-L4018 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | remove_all_snapshots | def remove_all_snapshots(name, kwargs=None, call=None):
'''
Remove all the snapshots present for the specified virtual machine.
.. note::
All the snapshots higher up in the hierarchy of the current snapshot tree
are consolidated and their virtual disks are merged. To override this
behavior and only remove all snapshots, set ``merge_snapshots=False``.
Default is ``merge_snapshots=True``
CLI Example:
.. code-block:: bash
salt-cloud -a remove_all_snapshots vmname [merge_snapshots=False]
'''
if call != 'action':
raise SaltCloudSystemExit(
'The remove_all_snapshots action must be called with '
'-a or --action.'
)
vm_ref = salt.utils.vmware.get_mor_by_property(_get_si(),
vim.VirtualMachine,
name)
try:
task = vm_ref.RemoveAllSnapshots()
salt.utils.vmware.wait_for_task(task, name, 'remove snapshots', 5, 'info')
except Exception as exc:
log.error(
'Error while removing snapshots on VM %s: %s',
name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return 'Failed to remove snapshots'
return 'Removed all snapshots' | python | def remove_all_snapshots(name, kwargs=None, call=None):
'''
Remove all the snapshots present for the specified virtual machine.
.. note::
All the snapshots higher up in the hierarchy of the current snapshot tree
are consolidated and their virtual disks are merged. To override this
behavior and only remove all snapshots, set ``merge_snapshots=False``.
Default is ``merge_snapshots=True``
CLI Example:
.. code-block:: bash
salt-cloud -a remove_all_snapshots vmname [merge_snapshots=False]
'''
if call != 'action':
raise SaltCloudSystemExit(
'The remove_all_snapshots action must be called with '
'-a or --action.'
)
vm_ref = salt.utils.vmware.get_mor_by_property(_get_si(),
vim.VirtualMachine,
name)
try:
task = vm_ref.RemoveAllSnapshots()
salt.utils.vmware.wait_for_task(task, name, 'remove snapshots', 5, 'info')
except Exception as exc:
log.error(
'Error while removing snapshots on VM %s: %s',
name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return 'Failed to remove snapshots'
return 'Removed all snapshots' | [
"def",
"remove_all_snapshots",
"(",
"name",
",",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The remove_all_snapshots action must be called with '",
"'-a or --action.'",
")",
... | Remove all the snapshots present for the specified virtual machine.
.. note::
All the snapshots higher up in the hierarchy of the current snapshot tree
are consolidated and their virtual disks are merged. To override this
behavior and only remove all snapshots, set ``merge_snapshots=False``.
Default is ``merge_snapshots=True``
CLI Example:
.. code-block:: bash
salt-cloud -a remove_all_snapshots vmname [merge_snapshots=False] | [
"Remove",
"all",
"the",
"snapshots",
"present",
"for",
"the",
"specified",
"virtual",
"machine",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L4021-L4060 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | convert_to_template | def convert_to_template(name, kwargs=None, call=None):
'''
Convert the specified virtual machine to template.
CLI Example:
.. code-block:: bash
salt-cloud -a convert_to_template vmname
'''
if call != 'action':
raise SaltCloudSystemExit(
'The convert_to_template action must be called with '
'-a or --action.'
)
vm_ref = salt.utils.vmware.get_mor_by_property(_get_si(), vim.VirtualMachine, name)
if vm_ref.config.template:
raise SaltCloudSystemExit(
'{0} already a template'.format(
name
)
)
try:
vm_ref.MarkAsTemplate()
except Exception as exc:
log.error(
'Error while converting VM to template %s: %s',
name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return 'failed to convert to teamplate'
return '{0} converted to template'.format(name) | python | def convert_to_template(name, kwargs=None, call=None):
'''
Convert the specified virtual machine to template.
CLI Example:
.. code-block:: bash
salt-cloud -a convert_to_template vmname
'''
if call != 'action':
raise SaltCloudSystemExit(
'The convert_to_template action must be called with '
'-a or --action.'
)
vm_ref = salt.utils.vmware.get_mor_by_property(_get_si(), vim.VirtualMachine, name)
if vm_ref.config.template:
raise SaltCloudSystemExit(
'{0} already a template'.format(
name
)
)
try:
vm_ref.MarkAsTemplate()
except Exception as exc:
log.error(
'Error while converting VM to template %s: %s',
name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return 'failed to convert to teamplate'
return '{0} converted to template'.format(name) | [
"def",
"convert_to_template",
"(",
"name",
",",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The convert_to_template action must be called with '",
"'-a or --action.'",
")",
"v... | Convert the specified virtual machine to template.
CLI Example:
.. code-block:: bash
salt-cloud -a convert_to_template vmname | [
"Convert",
"the",
"specified",
"virtual",
"machine",
"to",
"template",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L4063-L4099 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | add_host | def add_host(kwargs=None, call=None):
'''
Add a host system to the specified cluster or datacenter in this VMware environment
.. note::
To use this function, you need to specify ``esxi_host_user`` and
``esxi_host_password`` under your provider configuration set up at
``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/vmware.conf``:
.. code-block:: yaml
vcenter01:
driver: vmware
user: 'DOMAIN\\user'
password: 'verybadpass'
url: 'vcenter01.domain.com'
# Required when adding a host system
esxi_host_user: 'root'
esxi_host_password: 'myhostpassword'
# Optional fields that can be specified when adding a host system
esxi_host_ssl_thumbprint: '12:A3:45:B6:CD:7E:F8:90:A1:BC:23:45:D6:78:9E:FA:01:2B:34:CD'
The SSL thumbprint of the host system can be optionally specified by setting
``esxi_host_ssl_thumbprint`` under your provider configuration. To get the SSL
thumbprint of the host system, execute the following command from a remote
server:
.. code-block:: bash
echo -n | openssl s_client -connect <YOUR-HOSTSYSTEM-DNS/IP>:443 2>/dev/null | openssl x509 -noout -fingerprint -sha1
CLI Example:
.. code-block:: bash
salt-cloud -f add_host my-vmware-config host="myHostSystemName" cluster="myClusterName"
salt-cloud -f add_host my-vmware-config host="myHostSystemName" datacenter="myDatacenterName"
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_host function must be called with '
'-f or --function.'
)
host_name = kwargs.get('host') if kwargs and 'host' in kwargs else None
cluster_name = kwargs.get('cluster') if kwargs and 'cluster' in kwargs else None
datacenter_name = kwargs.get('datacenter') if kwargs and 'datacenter' in kwargs else None
host_user = config.get_cloud_config_value(
'esxi_host_user', get_configured_provider(), __opts__, search_global=False
)
host_password = config.get_cloud_config_value(
'esxi_host_password', get_configured_provider(), __opts__, search_global=False
)
host_ssl_thumbprint = config.get_cloud_config_value(
'esxi_host_ssl_thumbprint', get_configured_provider(), __opts__, search_global=False
)
if not host_user:
raise SaltCloudSystemExit(
'You must specify the ESXi host username in your providers config.'
)
if not host_password:
raise SaltCloudSystemExit(
'You must specify the ESXi host password in your providers config.'
)
if not host_name:
raise SaltCloudSystemExit(
'You must specify either the IP or DNS name of the host system.'
)
if (cluster_name and datacenter_name) or not(cluster_name or datacenter_name):
raise SaltCloudSystemExit(
'You must specify either the cluster name or the datacenter name.'
)
# Get the service instance
si = _get_si()
if cluster_name:
cluster_ref = salt.utils.vmware.get_mor_by_property(si, vim.ClusterComputeResource, cluster_name)
if not cluster_ref:
raise SaltCloudSystemExit(
'Specified cluster does not exist.'
)
if datacenter_name:
datacenter_ref = salt.utils.vmware.get_mor_by_property(si, vim.Datacenter, datacenter_name)
if not datacenter_ref:
raise SaltCloudSystemExit(
'Specified datacenter does not exist.'
)
spec = vim.host.ConnectSpec(
hostName=host_name,
userName=host_user,
password=host_password,
)
if host_ssl_thumbprint:
spec.sslThumbprint = host_ssl_thumbprint
else:
log.warning('SSL thumbprint has not been specified in provider configuration')
# This smells like a not-so-good idea. A plenty of VMWare VCenters
# do not listen to the default port 443.
try:
log.debug('Trying to get the SSL thumbprint directly from the host system')
p1 = subprocess.Popen(('echo', '-n'),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
p2 = subprocess.Popen(('openssl',
's_client',
'-connect',
'{0}:443'.format(host_name)),
stdin=p1.stdout,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
p3 = subprocess.Popen(('openssl',
'x509',
'-noout',
'-fingerprint',
'-sha1'),
stdin=p2.stdout,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out = salt.utils.stringutils.to_str(p3.stdout.read())
ssl_thumbprint = out.split('=')[-1].strip()
log.debug('SSL thumbprint received from the host system: %s', ssl_thumbprint)
spec.sslThumbprint = ssl_thumbprint
except Exception as exc:
log.error(
'Error while trying to get SSL thumbprint of host %s: %s',
host_name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return {host_name: 'failed to add host'}
try:
if cluster_name:
task = cluster_ref.AddHost(spec=spec, asConnected=True)
ret = 'added host system to cluster {0}'.format(cluster_name)
if datacenter_name:
task = datacenter_ref.hostFolder.AddStandaloneHost(spec=spec, addConnected=True)
ret = 'added host system to datacenter {0}'.format(datacenter_name)
salt.utils.vmware.wait_for_task(task, host_name, 'add host system', 5, 'info')
except Exception as exc:
if isinstance(exc, vim.fault.SSLVerifyFault):
log.error('Authenticity of the host\'s SSL certificate is not verified')
log.info('Try again after setting the esxi_host_ssl_thumbprint '
'to %s in provider configuration', spec.sslThumbprint)
log.error(
'Error while adding host %s: %s',
host_name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return {host_name: 'failed to add host'}
return {host_name: ret} | python | def add_host(kwargs=None, call=None):
'''
Add a host system to the specified cluster or datacenter in this VMware environment
.. note::
To use this function, you need to specify ``esxi_host_user`` and
``esxi_host_password`` under your provider configuration set up at
``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/vmware.conf``:
.. code-block:: yaml
vcenter01:
driver: vmware
user: 'DOMAIN\\user'
password: 'verybadpass'
url: 'vcenter01.domain.com'
# Required when adding a host system
esxi_host_user: 'root'
esxi_host_password: 'myhostpassword'
# Optional fields that can be specified when adding a host system
esxi_host_ssl_thumbprint: '12:A3:45:B6:CD:7E:F8:90:A1:BC:23:45:D6:78:9E:FA:01:2B:34:CD'
The SSL thumbprint of the host system can be optionally specified by setting
``esxi_host_ssl_thumbprint`` under your provider configuration. To get the SSL
thumbprint of the host system, execute the following command from a remote
server:
.. code-block:: bash
echo -n | openssl s_client -connect <YOUR-HOSTSYSTEM-DNS/IP>:443 2>/dev/null | openssl x509 -noout -fingerprint -sha1
CLI Example:
.. code-block:: bash
salt-cloud -f add_host my-vmware-config host="myHostSystemName" cluster="myClusterName"
salt-cloud -f add_host my-vmware-config host="myHostSystemName" datacenter="myDatacenterName"
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_host function must be called with '
'-f or --function.'
)
host_name = kwargs.get('host') if kwargs and 'host' in kwargs else None
cluster_name = kwargs.get('cluster') if kwargs and 'cluster' in kwargs else None
datacenter_name = kwargs.get('datacenter') if kwargs and 'datacenter' in kwargs else None
host_user = config.get_cloud_config_value(
'esxi_host_user', get_configured_provider(), __opts__, search_global=False
)
host_password = config.get_cloud_config_value(
'esxi_host_password', get_configured_provider(), __opts__, search_global=False
)
host_ssl_thumbprint = config.get_cloud_config_value(
'esxi_host_ssl_thumbprint', get_configured_provider(), __opts__, search_global=False
)
if not host_user:
raise SaltCloudSystemExit(
'You must specify the ESXi host username in your providers config.'
)
if not host_password:
raise SaltCloudSystemExit(
'You must specify the ESXi host password in your providers config.'
)
if not host_name:
raise SaltCloudSystemExit(
'You must specify either the IP or DNS name of the host system.'
)
if (cluster_name and datacenter_name) or not(cluster_name or datacenter_name):
raise SaltCloudSystemExit(
'You must specify either the cluster name or the datacenter name.'
)
# Get the service instance
si = _get_si()
if cluster_name:
cluster_ref = salt.utils.vmware.get_mor_by_property(si, vim.ClusterComputeResource, cluster_name)
if not cluster_ref:
raise SaltCloudSystemExit(
'Specified cluster does not exist.'
)
if datacenter_name:
datacenter_ref = salt.utils.vmware.get_mor_by_property(si, vim.Datacenter, datacenter_name)
if not datacenter_ref:
raise SaltCloudSystemExit(
'Specified datacenter does not exist.'
)
spec = vim.host.ConnectSpec(
hostName=host_name,
userName=host_user,
password=host_password,
)
if host_ssl_thumbprint:
spec.sslThumbprint = host_ssl_thumbprint
else:
log.warning('SSL thumbprint has not been specified in provider configuration')
# This smells like a not-so-good idea. A plenty of VMWare VCenters
# do not listen to the default port 443.
try:
log.debug('Trying to get the SSL thumbprint directly from the host system')
p1 = subprocess.Popen(('echo', '-n'),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
p2 = subprocess.Popen(('openssl',
's_client',
'-connect',
'{0}:443'.format(host_name)),
stdin=p1.stdout,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
p3 = subprocess.Popen(('openssl',
'x509',
'-noout',
'-fingerprint',
'-sha1'),
stdin=p2.stdout,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out = salt.utils.stringutils.to_str(p3.stdout.read())
ssl_thumbprint = out.split('=')[-1].strip()
log.debug('SSL thumbprint received from the host system: %s', ssl_thumbprint)
spec.sslThumbprint = ssl_thumbprint
except Exception as exc:
log.error(
'Error while trying to get SSL thumbprint of host %s: %s',
host_name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return {host_name: 'failed to add host'}
try:
if cluster_name:
task = cluster_ref.AddHost(spec=spec, asConnected=True)
ret = 'added host system to cluster {0}'.format(cluster_name)
if datacenter_name:
task = datacenter_ref.hostFolder.AddStandaloneHost(spec=spec, addConnected=True)
ret = 'added host system to datacenter {0}'.format(datacenter_name)
salt.utils.vmware.wait_for_task(task, host_name, 'add host system', 5, 'info')
except Exception as exc:
if isinstance(exc, vim.fault.SSLVerifyFault):
log.error('Authenticity of the host\'s SSL certificate is not verified')
log.info('Try again after setting the esxi_host_ssl_thumbprint '
'to %s in provider configuration', spec.sslThumbprint)
log.error(
'Error while adding host %s: %s',
host_name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return {host_name: 'failed to add host'}
return {host_name: ret} | [
"def",
"add_host",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The add_host function must be called with '",
"'-f or --function.'",
")",
"host_name",
"=",
"kwargs",
"... | Add a host system to the specified cluster or datacenter in this VMware environment
.. note::
To use this function, you need to specify ``esxi_host_user`` and
``esxi_host_password`` under your provider configuration set up at
``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/vmware.conf``:
.. code-block:: yaml
vcenter01:
driver: vmware
user: 'DOMAIN\\user'
password: 'verybadpass'
url: 'vcenter01.domain.com'
# Required when adding a host system
esxi_host_user: 'root'
esxi_host_password: 'myhostpassword'
# Optional fields that can be specified when adding a host system
esxi_host_ssl_thumbprint: '12:A3:45:B6:CD:7E:F8:90:A1:BC:23:45:D6:78:9E:FA:01:2B:34:CD'
The SSL thumbprint of the host system can be optionally specified by setting
``esxi_host_ssl_thumbprint`` under your provider configuration. To get the SSL
thumbprint of the host system, execute the following command from a remote
server:
.. code-block:: bash
echo -n | openssl s_client -connect <YOUR-HOSTSYSTEM-DNS/IP>:443 2>/dev/null | openssl x509 -noout -fingerprint -sha1
CLI Example:
.. code-block:: bash
salt-cloud -f add_host my-vmware-config host="myHostSystemName" cluster="myClusterName"
salt-cloud -f add_host my-vmware-config host="myHostSystemName" datacenter="myDatacenterName" | [
"Add",
"a",
"host",
"system",
"to",
"the",
"specified",
"cluster",
"or",
"datacenter",
"in",
"this",
"VMware",
"environment"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L4102-L4265 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | remove_host | def remove_host(kwargs=None, call=None):
'''
Remove the specified host system from this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f remove_host my-vmware-config host="myHostSystemName"
'''
if call != 'function':
raise SaltCloudSystemExit(
'The remove_host function must be called with '
'-f or --function.'
)
host_name = kwargs.get('host') if kwargs and 'host' in kwargs else None
if not host_name:
raise SaltCloudSystemExit(
'You must specify name of the host system.'
)
# Get the service instance
si = _get_si()
host_ref = salt.utils.vmware.get_mor_by_property(si, vim.HostSystem, host_name)
if not host_ref:
raise SaltCloudSystemExit(
'Specified host system does not exist.'
)
try:
if isinstance(host_ref.parent, vim.ClusterComputeResource):
# This is a host system that is part of a Cluster
task = host_ref.Destroy_Task()
else:
# This is a standalone host system
task = host_ref.parent.Destroy_Task()
salt.utils.vmware.wait_for_task(task, host_name, 'remove host', log_level='info')
except Exception as exc:
log.error(
'Error while removing host %s: %s',
host_name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return {host_name: 'failed to remove host'}
return {host_name: 'removed host from vcenter'} | python | def remove_host(kwargs=None, call=None):
'''
Remove the specified host system from this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f remove_host my-vmware-config host="myHostSystemName"
'''
if call != 'function':
raise SaltCloudSystemExit(
'The remove_host function must be called with '
'-f or --function.'
)
host_name = kwargs.get('host') if kwargs and 'host' in kwargs else None
if not host_name:
raise SaltCloudSystemExit(
'You must specify name of the host system.'
)
# Get the service instance
si = _get_si()
host_ref = salt.utils.vmware.get_mor_by_property(si, vim.HostSystem, host_name)
if not host_ref:
raise SaltCloudSystemExit(
'Specified host system does not exist.'
)
try:
if isinstance(host_ref.parent, vim.ClusterComputeResource):
# This is a host system that is part of a Cluster
task = host_ref.Destroy_Task()
else:
# This is a standalone host system
task = host_ref.parent.Destroy_Task()
salt.utils.vmware.wait_for_task(task, host_name, 'remove host', log_level='info')
except Exception as exc:
log.error(
'Error while removing host %s: %s',
host_name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return {host_name: 'failed to remove host'}
return {host_name: 'removed host from vcenter'} | [
"def",
"remove_host",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The remove_host function must be called with '",
"'-f or --function.'",
")",
"host_name",
"=",
"kwargs... | Remove the specified host system from this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f remove_host my-vmware-config host="myHostSystemName" | [
"Remove",
"the",
"specified",
"host",
"system",
"from",
"this",
"VMware",
"environment"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L4268-L4317 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | connect_host | def connect_host(kwargs=None, call=None):
'''
Connect the specified host system in this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f connect_host my-vmware-config host="myHostSystemName"
'''
if call != 'function':
raise SaltCloudSystemExit(
'The connect_host function must be called with '
'-f or --function.'
)
host_name = kwargs.get('host') if kwargs and 'host' in kwargs else None
if not host_name:
raise SaltCloudSystemExit(
'You must specify name of the host system.'
)
# Get the service instance
si = _get_si()
host_ref = salt.utils.vmware.get_mor_by_property(si, vim.HostSystem, host_name)
if not host_ref:
raise SaltCloudSystemExit(
'Specified host system does not exist.'
)
if host_ref.runtime.connectionState == 'connected':
return {host_name: 'host system already connected'}
try:
task = host_ref.ReconnectHost_Task()
salt.utils.vmware.wait_for_task(task, host_name, 'connect host', 5, 'info')
except Exception as exc:
log.error(
'Error while connecting host %s: %s',
host_name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return {host_name: 'failed to connect host'}
return {host_name: 'connected host'} | python | def connect_host(kwargs=None, call=None):
'''
Connect the specified host system in this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f connect_host my-vmware-config host="myHostSystemName"
'''
if call != 'function':
raise SaltCloudSystemExit(
'The connect_host function must be called with '
'-f or --function.'
)
host_name = kwargs.get('host') if kwargs and 'host' in kwargs else None
if not host_name:
raise SaltCloudSystemExit(
'You must specify name of the host system.'
)
# Get the service instance
si = _get_si()
host_ref = salt.utils.vmware.get_mor_by_property(si, vim.HostSystem, host_name)
if not host_ref:
raise SaltCloudSystemExit(
'Specified host system does not exist.'
)
if host_ref.runtime.connectionState == 'connected':
return {host_name: 'host system already connected'}
try:
task = host_ref.ReconnectHost_Task()
salt.utils.vmware.wait_for_task(task, host_name, 'connect host', 5, 'info')
except Exception as exc:
log.error(
'Error while connecting host %s: %s',
host_name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return {host_name: 'failed to connect host'}
return {host_name: 'connected host'} | [
"def",
"connect_host",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The connect_host function must be called with '",
"'-f or --function.'",
")",
"host_name",
"=",
"kwar... | Connect the specified host system in this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f connect_host my-vmware-config host="myHostSystemName" | [
"Connect",
"the",
"specified",
"host",
"system",
"in",
"this",
"VMware",
"environment"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L4320-L4367 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | create_datastore_cluster | def create_datastore_cluster(kwargs=None, call=None):
'''
Create a new datastore cluster for the specified datacenter in this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f create_datastore_cluster my-vmware-config name="datastoreClusterName" datacenter="datacenterName"
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_datastore_cluster function must be called with '
'-f or --function.'
)
datastore_cluster_name = kwargs.get('name') if kwargs and 'name' in kwargs else None
datacenter_name = kwargs.get('datacenter') if kwargs and 'datacenter' in kwargs else None
if not datastore_cluster_name:
raise SaltCloudSystemExit(
'You must specify name of the new datastore cluster to be created.'
)
if not datastore_cluster_name or len(datastore_cluster_name) >= 80:
raise SaltCloudSystemExit(
'The datastore cluster name must be a non empty string of less than 80 characters.'
)
if not datacenter_name:
raise SaltCloudSystemExit(
'You must specify name of the datacenter where the datastore cluster should be created.'
)
# Get the service instance
si = _get_si()
# Check if datastore cluster already exists
datastore_cluster_ref = salt.utils.vmware.get_mor_by_property(si, vim.StoragePod, datastore_cluster_name)
if datastore_cluster_ref:
return {datastore_cluster_name: 'datastore cluster already exists'}
datacenter_ref = salt.utils.vmware.get_mor_by_property(si, vim.Datacenter, datacenter_name)
if not datacenter_ref:
raise SaltCloudSystemExit(
'The specified datacenter does not exist.'
)
try:
datacenter_ref.datastoreFolder.CreateStoragePod(name=datastore_cluster_name)
except Exception as exc:
log.error(
'Error creating datastore cluster %s: %s',
datastore_cluster_name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
return {datastore_cluster_name: 'created'} | python | def create_datastore_cluster(kwargs=None, call=None):
'''
Create a new datastore cluster for the specified datacenter in this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f create_datastore_cluster my-vmware-config name="datastoreClusterName" datacenter="datacenterName"
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_datastore_cluster function must be called with '
'-f or --function.'
)
datastore_cluster_name = kwargs.get('name') if kwargs and 'name' in kwargs else None
datacenter_name = kwargs.get('datacenter') if kwargs and 'datacenter' in kwargs else None
if not datastore_cluster_name:
raise SaltCloudSystemExit(
'You must specify name of the new datastore cluster to be created.'
)
if not datastore_cluster_name or len(datastore_cluster_name) >= 80:
raise SaltCloudSystemExit(
'The datastore cluster name must be a non empty string of less than 80 characters.'
)
if not datacenter_name:
raise SaltCloudSystemExit(
'You must specify name of the datacenter where the datastore cluster should be created.'
)
# Get the service instance
si = _get_si()
# Check if datastore cluster already exists
datastore_cluster_ref = salt.utils.vmware.get_mor_by_property(si, vim.StoragePod, datastore_cluster_name)
if datastore_cluster_ref:
return {datastore_cluster_name: 'datastore cluster already exists'}
datacenter_ref = salt.utils.vmware.get_mor_by_property(si, vim.Datacenter, datacenter_name)
if not datacenter_ref:
raise SaltCloudSystemExit(
'The specified datacenter does not exist.'
)
try:
datacenter_ref.datastoreFolder.CreateStoragePod(name=datastore_cluster_name)
except Exception as exc:
log.error(
'Error creating datastore cluster %s: %s',
datastore_cluster_name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
return {datastore_cluster_name: 'created'} | [
"def",
"create_datastore_cluster",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The create_datastore_cluster function must be called with '",
"'-f or --function.'",
")",
"da... | Create a new datastore cluster for the specified datacenter in this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f create_datastore_cluster my-vmware-config name="datastoreClusterName" datacenter="datacenterName" | [
"Create",
"a",
"new",
"datastore",
"cluster",
"for",
"the",
"specified",
"datacenter",
"in",
"this",
"VMware",
"environment"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L4491-L4550 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | shutdown_host | def shutdown_host(kwargs=None, call=None):
'''
Shut down the specified host system in this VMware environment
.. note::
If the host system is not in maintenance mode, it will not be shut down. If you
want to shut down the host system regardless of whether it is in maintenance mode,
set ``force=True``. Default is ``force=False``.
CLI Example:
.. code-block:: bash
salt-cloud -f shutdown_host my-vmware-config host="myHostSystemName" [force=True]
'''
if call != 'function':
raise SaltCloudSystemExit(
'The shutdown_host function must be called with '
'-f or --function.'
)
host_name = kwargs.get('host') if kwargs and 'host' in kwargs else None
force = _str_to_bool(kwargs.get('force')) if kwargs and 'force' in kwargs else False
if not host_name:
raise SaltCloudSystemExit(
'You must specify name of the host system.'
)
# Get the service instance
si = _get_si()
host_ref = salt.utils.vmware.get_mor_by_property(si, vim.HostSystem, host_name)
if not host_ref:
raise SaltCloudSystemExit(
'Specified host system does not exist.'
)
if host_ref.runtime.connectionState == 'notResponding':
raise SaltCloudSystemExit(
'Specified host system cannot be shut down in it\'s current state (not responding).'
)
if not host_ref.capability.rebootSupported:
raise SaltCloudSystemExit(
'Specified host system does not support shutdown.'
)
if not host_ref.runtime.inMaintenanceMode and not force:
raise SaltCloudSystemExit(
'Specified host system is not in maintenance mode. Specify force=True to '
'force reboot even if there are virtual machines running or other operations '
'in progress.'
)
try:
host_ref.ShutdownHost_Task(force)
except Exception as exc:
log.error(
'Error while shutting down host %s: %s',
host_name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return {host_name: 'failed to shut down host'}
return {host_name: 'shut down host'} | python | def shutdown_host(kwargs=None, call=None):
'''
Shut down the specified host system in this VMware environment
.. note::
If the host system is not in maintenance mode, it will not be shut down. If you
want to shut down the host system regardless of whether it is in maintenance mode,
set ``force=True``. Default is ``force=False``.
CLI Example:
.. code-block:: bash
salt-cloud -f shutdown_host my-vmware-config host="myHostSystemName" [force=True]
'''
if call != 'function':
raise SaltCloudSystemExit(
'The shutdown_host function must be called with '
'-f or --function.'
)
host_name = kwargs.get('host') if kwargs and 'host' in kwargs else None
force = _str_to_bool(kwargs.get('force')) if kwargs and 'force' in kwargs else False
if not host_name:
raise SaltCloudSystemExit(
'You must specify name of the host system.'
)
# Get the service instance
si = _get_si()
host_ref = salt.utils.vmware.get_mor_by_property(si, vim.HostSystem, host_name)
if not host_ref:
raise SaltCloudSystemExit(
'Specified host system does not exist.'
)
if host_ref.runtime.connectionState == 'notResponding':
raise SaltCloudSystemExit(
'Specified host system cannot be shut down in it\'s current state (not responding).'
)
if not host_ref.capability.rebootSupported:
raise SaltCloudSystemExit(
'Specified host system does not support shutdown.'
)
if not host_ref.runtime.inMaintenanceMode and not force:
raise SaltCloudSystemExit(
'Specified host system is not in maintenance mode. Specify force=True to '
'force reboot even if there are virtual machines running or other operations '
'in progress.'
)
try:
host_ref.ShutdownHost_Task(force)
except Exception as exc:
log.error(
'Error while shutting down host %s: %s',
host_name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return {host_name: 'failed to shut down host'}
return {host_name: 'shut down host'} | [
"def",
"shutdown_host",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The shutdown_host function must be called with '",
"'-f or --function.'",
")",
"host_name",
"=",
"kw... | Shut down the specified host system in this VMware environment
.. note::
If the host system is not in maintenance mode, it will not be shut down. If you
want to shut down the host system regardless of whether it is in maintenance mode,
set ``force=True``. Default is ``force=False``.
CLI Example:
.. code-block:: bash
salt-cloud -f shutdown_host my-vmware-config host="myHostSystemName" [force=True] | [
"Shut",
"down",
"the",
"specified",
"host",
"system",
"in",
"this",
"VMware",
"environment"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L4553-L4620 | train |
saltstack/salt | salt/states/zabbix_usermacro.py | present | def present(name, value, hostid=None, **kwargs):
'''
Creates a new usermacro.
:param name: name of the usermacro
:param value: value of the usermacro
:param hostid: id's of the hosts to apply the usermacro on, if missing a global usermacro is assumed.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. code-block:: yaml
override host usermacro:
zabbix_usermacro.present:
- name: '{$SNMP_COMMUNITY}''
- value: 'public'
- hostid: 21
'''
connection_args = {}
if '_connection_user' in kwargs:
connection_args['_connection_user'] = kwargs['_connection_user']
if '_connection_password' in kwargs:
connection_args['_connection_password'] = kwargs['_connection_password']
if '_connection_url' in kwargs:
connection_args['_connection_url'] = kwargs['_connection_url']
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
# Comment and change messages
if hostid:
comment_usermacro_created = 'Usermacro {0} created on hostid {1}.'.format(name, hostid)
comment_usermacro_updated = 'Usermacro {0} updated on hostid {1}.'.format(name, hostid)
comment_usermacro_notcreated = 'Unable to create usermacro: {0} on hostid {1}. '.format(name, hostid)
comment_usermacro_exists = 'Usermacro {0} already exists on hostid {1}.'.format(name, hostid)
changes_usermacro_created = {name: {'old': 'Usermacro {0} does not exist on hostid {1}.'.format(name, hostid),
'new': 'Usermacro {0} created on hostid {1}.'.format(name, hostid),
}
}
else:
comment_usermacro_created = 'Usermacro {0} created.'.format(name)
comment_usermacro_updated = 'Usermacro {0} updated.'.format(name)
comment_usermacro_notcreated = 'Unable to create usermacro: {0}. '.format(name)
comment_usermacro_exists = 'Usermacro {0} already exists.'.format(name)
changes_usermacro_created = {name: {'old': 'Usermacro {0} does not exist.'.format(name),
'new': 'Usermacro {0} created.'.format(name),
}
}
# Zabbix API expects script parameters as a string of arguments seperated by newline characters
if 'exec_params' in kwargs:
if isinstance(kwargs['exec_params'], list):
kwargs['exec_params'] = '\n'.join(kwargs['exec_params'])+'\n'
else:
kwargs['exec_params'] = six.text_type(kwargs['exec_params'])+'\n'
if hostid:
usermacro_exists = __salt__['zabbix.usermacro_get'](name, hostids=hostid, **connection_args)
else:
usermacro_exists = __salt__['zabbix.usermacro_get'](name, globalmacro=True, **connection_args)
if usermacro_exists:
usermacroobj = usermacro_exists[0]
if hostid:
usermacroid = int(usermacroobj['hostmacroid'])
else:
usermacroid = int(usermacroobj['globalmacroid'])
update_value = False
if six.text_type(value) != usermacroobj['value']:
update_value = True
# Dry run, test=true mode
if __opts__['test']:
if usermacro_exists:
if update_value:
ret['result'] = None
ret['comment'] = comment_usermacro_updated
else:
ret['result'] = True
ret['comment'] = comment_usermacro_exists
else:
ret['result'] = None
ret['comment'] = comment_usermacro_created
return ret
error = []
if usermacro_exists:
if update_value:
ret['result'] = True
ret['comment'] = comment_usermacro_updated
if hostid:
updated_value = __salt__['zabbix.usermacro_update'](usermacroid,
value=value,
**connection_args)
else:
updated_value = __salt__['zabbix.usermacro_updateglobal'](usermacroid,
value=value,
**connection_args)
if not isinstance(updated_value, int):
if 'error' in updated_value:
error.append(updated_value['error'])
else:
ret['changes']['value'] = value
else:
ret['result'] = True
ret['comment'] = comment_usermacro_exists
else:
if hostid:
usermacro_create = __salt__['zabbix.usermacro_create'](name, value, hostid, **connection_args)
else:
usermacro_create = __salt__['zabbix.usermacro_createglobal'](name, value, **connection_args)
if 'error' not in usermacro_create:
ret['result'] = True
ret['comment'] = comment_usermacro_created
ret['changes'] = changes_usermacro_created
else:
ret['result'] = False
ret['comment'] = comment_usermacro_notcreated + six.text_type(usermacro_create['error'])
# error detected
if error:
ret['changes'] = {}
ret['result'] = False
ret['comment'] = six.text_type(error)
return ret | python | def present(name, value, hostid=None, **kwargs):
'''
Creates a new usermacro.
:param name: name of the usermacro
:param value: value of the usermacro
:param hostid: id's of the hosts to apply the usermacro on, if missing a global usermacro is assumed.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. code-block:: yaml
override host usermacro:
zabbix_usermacro.present:
- name: '{$SNMP_COMMUNITY}''
- value: 'public'
- hostid: 21
'''
connection_args = {}
if '_connection_user' in kwargs:
connection_args['_connection_user'] = kwargs['_connection_user']
if '_connection_password' in kwargs:
connection_args['_connection_password'] = kwargs['_connection_password']
if '_connection_url' in kwargs:
connection_args['_connection_url'] = kwargs['_connection_url']
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
# Comment and change messages
if hostid:
comment_usermacro_created = 'Usermacro {0} created on hostid {1}.'.format(name, hostid)
comment_usermacro_updated = 'Usermacro {0} updated on hostid {1}.'.format(name, hostid)
comment_usermacro_notcreated = 'Unable to create usermacro: {0} on hostid {1}. '.format(name, hostid)
comment_usermacro_exists = 'Usermacro {0} already exists on hostid {1}.'.format(name, hostid)
changes_usermacro_created = {name: {'old': 'Usermacro {0} does not exist on hostid {1}.'.format(name, hostid),
'new': 'Usermacro {0} created on hostid {1}.'.format(name, hostid),
}
}
else:
comment_usermacro_created = 'Usermacro {0} created.'.format(name)
comment_usermacro_updated = 'Usermacro {0} updated.'.format(name)
comment_usermacro_notcreated = 'Unable to create usermacro: {0}. '.format(name)
comment_usermacro_exists = 'Usermacro {0} already exists.'.format(name)
changes_usermacro_created = {name: {'old': 'Usermacro {0} does not exist.'.format(name),
'new': 'Usermacro {0} created.'.format(name),
}
}
# Zabbix API expects script parameters as a string of arguments seperated by newline characters
if 'exec_params' in kwargs:
if isinstance(kwargs['exec_params'], list):
kwargs['exec_params'] = '\n'.join(kwargs['exec_params'])+'\n'
else:
kwargs['exec_params'] = six.text_type(kwargs['exec_params'])+'\n'
if hostid:
usermacro_exists = __salt__['zabbix.usermacro_get'](name, hostids=hostid, **connection_args)
else:
usermacro_exists = __salt__['zabbix.usermacro_get'](name, globalmacro=True, **connection_args)
if usermacro_exists:
usermacroobj = usermacro_exists[0]
if hostid:
usermacroid = int(usermacroobj['hostmacroid'])
else:
usermacroid = int(usermacroobj['globalmacroid'])
update_value = False
if six.text_type(value) != usermacroobj['value']:
update_value = True
# Dry run, test=true mode
if __opts__['test']:
if usermacro_exists:
if update_value:
ret['result'] = None
ret['comment'] = comment_usermacro_updated
else:
ret['result'] = True
ret['comment'] = comment_usermacro_exists
else:
ret['result'] = None
ret['comment'] = comment_usermacro_created
return ret
error = []
if usermacro_exists:
if update_value:
ret['result'] = True
ret['comment'] = comment_usermacro_updated
if hostid:
updated_value = __salt__['zabbix.usermacro_update'](usermacroid,
value=value,
**connection_args)
else:
updated_value = __salt__['zabbix.usermacro_updateglobal'](usermacroid,
value=value,
**connection_args)
if not isinstance(updated_value, int):
if 'error' in updated_value:
error.append(updated_value['error'])
else:
ret['changes']['value'] = value
else:
ret['result'] = True
ret['comment'] = comment_usermacro_exists
else:
if hostid:
usermacro_create = __salt__['zabbix.usermacro_create'](name, value, hostid, **connection_args)
else:
usermacro_create = __salt__['zabbix.usermacro_createglobal'](name, value, **connection_args)
if 'error' not in usermacro_create:
ret['result'] = True
ret['comment'] = comment_usermacro_created
ret['changes'] = changes_usermacro_created
else:
ret['result'] = False
ret['comment'] = comment_usermacro_notcreated + six.text_type(usermacro_create['error'])
# error detected
if error:
ret['changes'] = {}
ret['result'] = False
ret['comment'] = six.text_type(error)
return ret | [
"def",
"present",
"(",
"name",
",",
"value",
",",
"hostid",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"connection_args",
"=",
"{",
"}",
"if",
"'_connection_user'",
"in",
"kwargs",
":",
"connection_args",
"[",
"'_connection_user'",
"]",
"=",
"kwargs",... | Creates a new usermacro.
:param name: name of the usermacro
:param value: value of the usermacro
:param hostid: id's of the hosts to apply the usermacro on, if missing a global usermacro is assumed.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. code-block:: yaml
override host usermacro:
zabbix_usermacro.present:
- name: '{$SNMP_COMMUNITY}''
- value: 'public'
- hostid: 21 | [
"Creates",
"a",
"new",
"usermacro",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zabbix_usermacro.py#L22-L152 | train |
saltstack/salt | salt/states/zabbix_usermacro.py | absent | def absent(name, hostid=None, **kwargs):
'''
Ensures that the mediatype does not exist, eventually deletes the mediatype.
:param name: name of the usermacro
:param hostid: id's of the hosts to apply the usermacro on, if missing a global usermacro is assumed.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. code-block:: yaml
delete_usermacro:
zabbix_usermacro.absent:
- name: '{$SNMP_COMMUNITY}'
'''
connection_args = {}
if '_connection_user' in kwargs:
connection_args['_connection_user'] = kwargs['_connection_user']
if '_connection_password' in kwargs:
connection_args['_connection_password'] = kwargs['_connection_password']
if '_connection_url' in kwargs:
connection_args['_connection_url'] = kwargs['_connection_url']
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
# Comment and change messages
if hostid:
comment_usermacro_deleted = 'Usermacro {0} deleted from hostid {1}.'.format(name, hostid)
comment_usermacro_notdeleted = 'Unable to delete usermacro: {0} from hostid {1}.'.format(name, hostid)
comment_usermacro_notexists = 'Usermacro {0} does not exist on hostid {1}.'.format(name, hostid)
changes_usermacro_deleted = {name: {'old': 'Usermacro {0} exists on hostid {1}.'.format(name, hostid),
'new': 'Usermacro {0} deleted from {1}.'.format(name, hostid),
}
}
else:
comment_usermacro_deleted = 'Usermacro {0} deleted.'.format(name)
comment_usermacro_notdeleted = 'Unable to delete usermacro: {0}.'.format(name)
comment_usermacro_notexists = 'Usermacro {0} does not exist.'.format(name)
changes_usermacro_deleted = {name: {'old': 'Usermacro {0} exists.'.format(name),
'new': 'Usermacro {0} deleted.'.format(name),
}
}
if hostid:
usermacro_exists = __salt__['zabbix.usermacro_get'](name, hostids=hostid, **connection_args)
else:
usermacro_exists = __salt__['zabbix.usermacro_get'](name, globalmacro=True, **connection_args)
# Dry run, test=true mode
if __opts__['test']:
if not usermacro_exists:
ret['result'] = True
ret['comment'] = comment_usermacro_notexists
else:
ret['result'] = None
ret['comment'] = comment_usermacro_deleted
return ret
if not usermacro_exists:
ret['result'] = True
ret['comment'] = comment_usermacro_notexists
else:
try:
if hostid:
usermacroid = usermacro_exists[0]['hostmacroid']
usermacro_delete = __salt__['zabbix.usermacro_delete'](usermacroid, **connection_args)
else:
usermacroid = usermacro_exists[0]['globalmacroid']
usermacro_delete = __salt__['zabbix.usermacro_deleteglobal'](usermacroid, **connection_args)
except KeyError:
usermacro_delete = False
if usermacro_delete and 'error' not in usermacro_delete:
ret['result'] = True
ret['comment'] = comment_usermacro_deleted
ret['changes'] = changes_usermacro_deleted
else:
ret['result'] = False
ret['comment'] = comment_usermacro_notdeleted + six.text_type(usermacro_delete['error'])
return ret | python | def absent(name, hostid=None, **kwargs):
'''
Ensures that the mediatype does not exist, eventually deletes the mediatype.
:param name: name of the usermacro
:param hostid: id's of the hosts to apply the usermacro on, if missing a global usermacro is assumed.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. code-block:: yaml
delete_usermacro:
zabbix_usermacro.absent:
- name: '{$SNMP_COMMUNITY}'
'''
connection_args = {}
if '_connection_user' in kwargs:
connection_args['_connection_user'] = kwargs['_connection_user']
if '_connection_password' in kwargs:
connection_args['_connection_password'] = kwargs['_connection_password']
if '_connection_url' in kwargs:
connection_args['_connection_url'] = kwargs['_connection_url']
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
# Comment and change messages
if hostid:
comment_usermacro_deleted = 'Usermacro {0} deleted from hostid {1}.'.format(name, hostid)
comment_usermacro_notdeleted = 'Unable to delete usermacro: {0} from hostid {1}.'.format(name, hostid)
comment_usermacro_notexists = 'Usermacro {0} does not exist on hostid {1}.'.format(name, hostid)
changes_usermacro_deleted = {name: {'old': 'Usermacro {0} exists on hostid {1}.'.format(name, hostid),
'new': 'Usermacro {0} deleted from {1}.'.format(name, hostid),
}
}
else:
comment_usermacro_deleted = 'Usermacro {0} deleted.'.format(name)
comment_usermacro_notdeleted = 'Unable to delete usermacro: {0}.'.format(name)
comment_usermacro_notexists = 'Usermacro {0} does not exist.'.format(name)
changes_usermacro_deleted = {name: {'old': 'Usermacro {0} exists.'.format(name),
'new': 'Usermacro {0} deleted.'.format(name),
}
}
if hostid:
usermacro_exists = __salt__['zabbix.usermacro_get'](name, hostids=hostid, **connection_args)
else:
usermacro_exists = __salt__['zabbix.usermacro_get'](name, globalmacro=True, **connection_args)
# Dry run, test=true mode
if __opts__['test']:
if not usermacro_exists:
ret['result'] = True
ret['comment'] = comment_usermacro_notexists
else:
ret['result'] = None
ret['comment'] = comment_usermacro_deleted
return ret
if not usermacro_exists:
ret['result'] = True
ret['comment'] = comment_usermacro_notexists
else:
try:
if hostid:
usermacroid = usermacro_exists[0]['hostmacroid']
usermacro_delete = __salt__['zabbix.usermacro_delete'](usermacroid, **connection_args)
else:
usermacroid = usermacro_exists[0]['globalmacroid']
usermacro_delete = __salt__['zabbix.usermacro_deleteglobal'](usermacroid, **connection_args)
except KeyError:
usermacro_delete = False
if usermacro_delete and 'error' not in usermacro_delete:
ret['result'] = True
ret['comment'] = comment_usermacro_deleted
ret['changes'] = changes_usermacro_deleted
else:
ret['result'] = False
ret['comment'] = comment_usermacro_notdeleted + six.text_type(usermacro_delete['error'])
return ret | [
"def",
"absent",
"(",
"name",
",",
"hostid",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"connection_args",
"=",
"{",
"}",
"if",
"'_connection_user'",
"in",
"kwargs",
":",
"connection_args",
"[",
"'_connection_user'",
"]",
"=",
"kwargs",
"[",
"'_connec... | Ensures that the mediatype does not exist, eventually deletes the mediatype.
:param name: name of the usermacro
:param hostid: id's of the hosts to apply the usermacro on, if missing a global usermacro is assumed.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. code-block:: yaml
delete_usermacro:
zabbix_usermacro.absent:
- name: '{$SNMP_COMMUNITY}' | [
"Ensures",
"that",
"the",
"mediatype",
"does",
"not",
"exist",
"eventually",
"deletes",
"the",
"mediatype",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zabbix_usermacro.py#L155-L237 | train |
saltstack/salt | salt/runners/survey.py | diff | def diff(*args, **kwargs):
'''
Return the DIFFERENCE of the result sets returned by each matching minion
pool
.. versionadded:: 2014.7.0
These pools are determined from the aggregated and sorted results of
a salt command.
This command displays the "diffs" as a series of 2-way differences --
namely the difference between the FIRST displayed minion pool
(according to sort order) and EACH SUBSEQUENT minion pool result set.
Differences are displayed according to the Python ``difflib.unified_diff()``
as in the case of the salt execution module ``file.get_diff``.
This command is submitted via a salt runner using the general form::
salt-run survey.diff [survey_sort=up/down] <target>
<salt-execution-module> <salt-execution-module parameters>
Optionally accept a ``survey_sort=`` parameter. Default:
``survey_sort=down``
CLI Example #1: (Example to display the "differences of files")
.. code-block:: bash
salt-run survey.diff survey_sort=up "*" cp.get_file_str file:///etc/hosts
'''
# TODO: The salt execution module "cp.get_file_str file:///..." is a
# non-obvious way to display the differences between files using
# survey.diff . A more obvious method needs to be found or developed.
import difflib
bulk_ret = _get_pool_results(*args, **kwargs)
is_first_time = True
for k in bulk_ret:
print('minion pool :\n'
'------------')
print(k['pool'])
print('pool size :\n'
'----------')
print(' ' + six.text_type(len(k['pool'])))
if is_first_time:
is_first_time = False
print('pool result :\n'
'------------')
print(' ' + bulk_ret[0]['result'])
print()
continue
outs = ('differences from "{0}" results :').format(
bulk_ret[0]['pool'][0])
print(outs)
print('-' * (len(outs) - 1))
from_result = bulk_ret[0]['result'].splitlines()
for i in range(0, len(from_result)):
from_result[i] += '\n'
to_result = k['result'].splitlines()
for i in range(0, len(to_result)):
to_result[i] += '\n'
outs = ''
outs += ''.join(difflib.unified_diff(from_result,
to_result,
fromfile=bulk_ret[0]['pool'][0],
tofile=k['pool'][0],
n=0))
print(outs)
print()
return bulk_ret | python | def diff(*args, **kwargs):
'''
Return the DIFFERENCE of the result sets returned by each matching minion
pool
.. versionadded:: 2014.7.0
These pools are determined from the aggregated and sorted results of
a salt command.
This command displays the "diffs" as a series of 2-way differences --
namely the difference between the FIRST displayed minion pool
(according to sort order) and EACH SUBSEQUENT minion pool result set.
Differences are displayed according to the Python ``difflib.unified_diff()``
as in the case of the salt execution module ``file.get_diff``.
This command is submitted via a salt runner using the general form::
salt-run survey.diff [survey_sort=up/down] <target>
<salt-execution-module> <salt-execution-module parameters>
Optionally accept a ``survey_sort=`` parameter. Default:
``survey_sort=down``
CLI Example #1: (Example to display the "differences of files")
.. code-block:: bash
salt-run survey.diff survey_sort=up "*" cp.get_file_str file:///etc/hosts
'''
# TODO: The salt execution module "cp.get_file_str file:///..." is a
# non-obvious way to display the differences between files using
# survey.diff . A more obvious method needs to be found or developed.
import difflib
bulk_ret = _get_pool_results(*args, **kwargs)
is_first_time = True
for k in bulk_ret:
print('minion pool :\n'
'------------')
print(k['pool'])
print('pool size :\n'
'----------')
print(' ' + six.text_type(len(k['pool'])))
if is_first_time:
is_first_time = False
print('pool result :\n'
'------------')
print(' ' + bulk_ret[0]['result'])
print()
continue
outs = ('differences from "{0}" results :').format(
bulk_ret[0]['pool'][0])
print(outs)
print('-' * (len(outs) - 1))
from_result = bulk_ret[0]['result'].splitlines()
for i in range(0, len(from_result)):
from_result[i] += '\n'
to_result = k['result'].splitlines()
for i in range(0, len(to_result)):
to_result[i] += '\n'
outs = ''
outs += ''.join(difflib.unified_diff(from_result,
to_result,
fromfile=bulk_ret[0]['pool'][0],
tofile=k['pool'][0],
n=0))
print(outs)
print()
return bulk_ret | [
"def",
"diff",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# TODO: The salt execution module \"cp.get_file_str file:///...\" is a",
"# non-obvious way to display the differences between files using",
"# survey.diff . A more obvious method needs to be found or developed.",
"imp... | Return the DIFFERENCE of the result sets returned by each matching minion
pool
.. versionadded:: 2014.7.0
These pools are determined from the aggregated and sorted results of
a salt command.
This command displays the "diffs" as a series of 2-way differences --
namely the difference between the FIRST displayed minion pool
(according to sort order) and EACH SUBSEQUENT minion pool result set.
Differences are displayed according to the Python ``difflib.unified_diff()``
as in the case of the salt execution module ``file.get_diff``.
This command is submitted via a salt runner using the general form::
salt-run survey.diff [survey_sort=up/down] <target>
<salt-execution-module> <salt-execution-module parameters>
Optionally accept a ``survey_sort=`` parameter. Default:
``survey_sort=down``
CLI Example #1: (Example to display the "differences of files")
.. code-block:: bash
salt-run survey.diff survey_sort=up "*" cp.get_file_str file:///etc/hosts | [
"Return",
"the",
"DIFFERENCE",
"of",
"the",
"result",
"sets",
"returned",
"by",
"each",
"matching",
"minion",
"pool"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/survey.py#L58-L132 | train |
saltstack/salt | salt/runners/survey.py | _get_pool_results | def _get_pool_results(*args, **kwargs):
'''
A helper function which returns a dictionary of minion pools along with
their matching result sets.
Useful for developing other "survey style" functions.
Optionally accepts a "survey_sort=up" or "survey_sort=down" kwargs for
specifying sort order.
Because the kwargs namespace of the "salt" and "survey" command are shared,
the name "survey_sort" was chosen to help avoid option conflicts.
'''
# TODO: the option "survey.sort=" would be preferred for namespace
# separation but the kwargs parser for the salt-run command seems to
# improperly pass the options containing a "." in them for later modules to
# process. The "_" is used here instead.
import hashlib
tgt = args[0]
cmd = args[1]
ret = {}
sort = kwargs.pop('survey_sort', 'down')
direction = sort != 'up'
tgt_type = kwargs.pop('tgt_type', 'compound')
if tgt_type not in ['compound', 'pcre']:
tgt_type = 'compound'
kwargs_passthru = dict((k, kwargs[k]) for k in six.iterkeys(kwargs) if not k.startswith('_'))
client = salt.client.get_local_client(__opts__['conf_file'])
try:
minions = client.cmd(tgt, cmd, args[2:], timeout=__opts__['timeout'], tgt_type=tgt_type, kwarg=kwargs_passthru)
except SaltClientError as client_error:
print(client_error)
return ret
# hash minion return values as a string
for minion in sorted(minions):
digest = hashlib.sha256(six.text_type(minions[minion]).encode(__salt_system_encoding__)).hexdigest()
if digest not in ret:
ret[digest] = {}
ret[digest]['pool'] = []
ret[digest]['result'] = six.text_type(minions[minion])
ret[digest]['pool'].append(minion)
sorted_ret = []
for k in sorted(ret, key=lambda k: len(ret[k]['pool']), reverse=direction):
# return aggregated results, sorted by size of the hash pool
sorted_ret.append(ret[k])
return sorted_ret | python | def _get_pool_results(*args, **kwargs):
'''
A helper function which returns a dictionary of minion pools along with
their matching result sets.
Useful for developing other "survey style" functions.
Optionally accepts a "survey_sort=up" or "survey_sort=down" kwargs for
specifying sort order.
Because the kwargs namespace of the "salt" and "survey" command are shared,
the name "survey_sort" was chosen to help avoid option conflicts.
'''
# TODO: the option "survey.sort=" would be preferred for namespace
# separation but the kwargs parser for the salt-run command seems to
# improperly pass the options containing a "." in them for later modules to
# process. The "_" is used here instead.
import hashlib
tgt = args[0]
cmd = args[1]
ret = {}
sort = kwargs.pop('survey_sort', 'down')
direction = sort != 'up'
tgt_type = kwargs.pop('tgt_type', 'compound')
if tgt_type not in ['compound', 'pcre']:
tgt_type = 'compound'
kwargs_passthru = dict((k, kwargs[k]) for k in six.iterkeys(kwargs) if not k.startswith('_'))
client = salt.client.get_local_client(__opts__['conf_file'])
try:
minions = client.cmd(tgt, cmd, args[2:], timeout=__opts__['timeout'], tgt_type=tgt_type, kwarg=kwargs_passthru)
except SaltClientError as client_error:
print(client_error)
return ret
# hash minion return values as a string
for minion in sorted(minions):
digest = hashlib.sha256(six.text_type(minions[minion]).encode(__salt_system_encoding__)).hexdigest()
if digest not in ret:
ret[digest] = {}
ret[digest]['pool'] = []
ret[digest]['result'] = six.text_type(minions[minion])
ret[digest]['pool'].append(minion)
sorted_ret = []
for k in sorted(ret, key=lambda k: len(ret[k]['pool']), reverse=direction):
# return aggregated results, sorted by size of the hash pool
sorted_ret.append(ret[k])
return sorted_ret | [
"def",
"_get_pool_results",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# TODO: the option \"survey.sort=\" would be preferred for namespace",
"# separation but the kwargs parser for the salt-run command seems to",
"# improperly pass the options containing a \".\" in them for lat... | A helper function which returns a dictionary of minion pools along with
their matching result sets.
Useful for developing other "survey style" functions.
Optionally accepts a "survey_sort=up" or "survey_sort=down" kwargs for
specifying sort order.
Because the kwargs namespace of the "salt" and "survey" command are shared,
the name "survey_sort" was chosen to help avoid option conflicts. | [
"A",
"helper",
"function",
"which",
"returns",
"a",
"dictionary",
"of",
"minion",
"pools",
"along",
"with",
"their",
"matching",
"result",
"sets",
".",
"Useful",
"for",
"developing",
"other",
"survey",
"style",
"functions",
".",
"Optionally",
"accepts",
"a",
"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/survey.py#L135-L188 | train |
saltstack/salt | salt/states/artifactory.py | downloaded | def downloaded(name, artifact, target_dir='/tmp', target_file=None, use_literal_group_id=False):
'''
Ensures that the artifact from artifactory exists at given location. If it doesn't exist, then
it will be downloaded. If it already exists then the checksum of existing file is checked against checksum
in artifactory. If it is different then the step will fail.
artifact
Details of the artifact to be downloaded from artifactory. Various options are:
- artifactory_url: URL of the artifactory instance
- repository: Repository in artifactory
- artifact_id: Artifact ID
- group_id: Group ID
- packaging: Packaging
- classifier: Classifier
.. versionadded:: 2015.8.0
- version: Version
One of the following:
- Version to download
- ``latest`` - Download the latest release of this artifact
- ``latest_snapshot`` - Download the latest snapshot for this artifact
- username: Artifactory username
.. versionadded:: 2015.8.0
- password: Artifactory password
.. versionadded:: 2015.8.0
target_dir
Directory where the artifact should be downloaded. By default it is downloaded to /tmp directory.
target_file
Target file to download artifact to. By default file name is resolved by artifactory.
An example to download an artifact to a specific file:
.. code-block:: yaml
jboss_module_downloaded:
artifactory.downloaded:
- artifact:
artifactory_url: http://artifactory.intranet.example.com/artifactory
repository: 'libs-release-local'
artifact_id: 'module'
group_id: 'com.company.module'
packaging: 'jar'
classifier: 'sources'
version: '1.0'
- target_file: /opt/jboss7/modules/com/company/lib/module.jar
Download artifact to the folder (automatically resolves file name):
.. code-block:: yaml
jboss_module_downloaded:
artifactory.downloaded:
- artifact:
artifactory_url: http://artifactory.intranet.example.com/artifactory
repository: 'libs-release-local'
artifact_id: 'module'
group_id: 'com.company.module'
packaging: 'jar'
classifier: 'sources'
version: '1.0'
- target_dir: /opt/jboss7/modules/com/company/lib
'''
log.debug(" ======================== STATE: artifactory.downloaded (name: %s) ", name)
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
if 'test' in __opts__ and __opts__['test'] is True:
fetch_result = {}
fetch_result['status'] = True
fetch_result['comment'] = 'Artifact would be downloaded from URL: {0}'.format(artifact['artifactory_url'])
fetch_result['changes'] = {}
else:
try:
fetch_result = __fetch_from_artifactory(artifact, target_dir, target_file, use_literal_group_id)
except Exception as exc:
ret['result'] = False
ret['comment'] = six.text_type(exc)
return ret
log.debug('fetch_result = %s', fetch_result)
ret['result'] = fetch_result['status']
ret['comment'] = fetch_result['comment']
ret['changes'] = fetch_result['changes']
log.debug('ret = %s', ret)
return ret | python | def downloaded(name, artifact, target_dir='/tmp', target_file=None, use_literal_group_id=False):
'''
Ensures that the artifact from artifactory exists at given location. If it doesn't exist, then
it will be downloaded. If it already exists then the checksum of existing file is checked against checksum
in artifactory. If it is different then the step will fail.
artifact
Details of the artifact to be downloaded from artifactory. Various options are:
- artifactory_url: URL of the artifactory instance
- repository: Repository in artifactory
- artifact_id: Artifact ID
- group_id: Group ID
- packaging: Packaging
- classifier: Classifier
.. versionadded:: 2015.8.0
- version: Version
One of the following:
- Version to download
- ``latest`` - Download the latest release of this artifact
- ``latest_snapshot`` - Download the latest snapshot for this artifact
- username: Artifactory username
.. versionadded:: 2015.8.0
- password: Artifactory password
.. versionadded:: 2015.8.0
target_dir
Directory where the artifact should be downloaded. By default it is downloaded to /tmp directory.
target_file
Target file to download artifact to. By default file name is resolved by artifactory.
An example to download an artifact to a specific file:
.. code-block:: yaml
jboss_module_downloaded:
artifactory.downloaded:
- artifact:
artifactory_url: http://artifactory.intranet.example.com/artifactory
repository: 'libs-release-local'
artifact_id: 'module'
group_id: 'com.company.module'
packaging: 'jar'
classifier: 'sources'
version: '1.0'
- target_file: /opt/jboss7/modules/com/company/lib/module.jar
Download artifact to the folder (automatically resolves file name):
.. code-block:: yaml
jboss_module_downloaded:
artifactory.downloaded:
- artifact:
artifactory_url: http://artifactory.intranet.example.com/artifactory
repository: 'libs-release-local'
artifact_id: 'module'
group_id: 'com.company.module'
packaging: 'jar'
classifier: 'sources'
version: '1.0'
- target_dir: /opt/jboss7/modules/com/company/lib
'''
log.debug(" ======================== STATE: artifactory.downloaded (name: %s) ", name)
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
if 'test' in __opts__ and __opts__['test'] is True:
fetch_result = {}
fetch_result['status'] = True
fetch_result['comment'] = 'Artifact would be downloaded from URL: {0}'.format(artifact['artifactory_url'])
fetch_result['changes'] = {}
else:
try:
fetch_result = __fetch_from_artifactory(artifact, target_dir, target_file, use_literal_group_id)
except Exception as exc:
ret['result'] = False
ret['comment'] = six.text_type(exc)
return ret
log.debug('fetch_result = %s', fetch_result)
ret['result'] = fetch_result['status']
ret['comment'] = fetch_result['comment']
ret['changes'] = fetch_result['changes']
log.debug('ret = %s', ret)
return ret | [
"def",
"downloaded",
"(",
"name",
",",
"artifact",
",",
"target_dir",
"=",
"'/tmp'",
",",
"target_file",
"=",
"None",
",",
"use_literal_group_id",
"=",
"False",
")",
":",
"log",
".",
"debug",
"(",
"\" ======================== STATE: artifactory.downloaded (name: %s) \... | Ensures that the artifact from artifactory exists at given location. If it doesn't exist, then
it will be downloaded. If it already exists then the checksum of existing file is checked against checksum
in artifactory. If it is different then the step will fail.
artifact
Details of the artifact to be downloaded from artifactory. Various options are:
- artifactory_url: URL of the artifactory instance
- repository: Repository in artifactory
- artifact_id: Artifact ID
- group_id: Group ID
- packaging: Packaging
- classifier: Classifier
.. versionadded:: 2015.8.0
- version: Version
One of the following:
- Version to download
- ``latest`` - Download the latest release of this artifact
- ``latest_snapshot`` - Download the latest snapshot for this artifact
- username: Artifactory username
.. versionadded:: 2015.8.0
- password: Artifactory password
.. versionadded:: 2015.8.0
target_dir
Directory where the artifact should be downloaded. By default it is downloaded to /tmp directory.
target_file
Target file to download artifact to. By default file name is resolved by artifactory.
An example to download an artifact to a specific file:
.. code-block:: yaml
jboss_module_downloaded:
artifactory.downloaded:
- artifact:
artifactory_url: http://artifactory.intranet.example.com/artifactory
repository: 'libs-release-local'
artifact_id: 'module'
group_id: 'com.company.module'
packaging: 'jar'
classifier: 'sources'
version: '1.0'
- target_file: /opt/jboss7/modules/com/company/lib/module.jar
Download artifact to the folder (automatically resolves file name):
.. code-block:: yaml
jboss_module_downloaded:
artifactory.downloaded:
- artifact:
artifactory_url: http://artifactory.intranet.example.com/artifactory
repository: 'libs-release-local'
artifact_id: 'module'
group_id: 'com.company.module'
packaging: 'jar'
classifier: 'sources'
version: '1.0'
- target_dir: /opt/jboss7/modules/com/company/lib | [
"Ensures",
"that",
"the",
"artifact",
"from",
"artifactory",
"exists",
"at",
"given",
"location",
".",
"If",
"it",
"doesn",
"t",
"exist",
"then",
"it",
"will",
"be",
"downloaded",
".",
"If",
"it",
"already",
"exists",
"then",
"the",
"checksum",
"of",
"exis... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/artifactory.py#L15-L107 | train |
saltstack/salt | salt/states/saltutil.py | sync_all | def sync_all(name, **kwargs):
'''
Performs the same task as saltutil.sync_all module
See :mod:`saltutil module for full list of options <salt.modules.saltutil>`
.. code-block:: yaml
sync_everything:
saltutil.sync_all:
- refresh: True
'''
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
if __opts__['test']:
ret['result'] = None
ret['comment'] = "saltutil.sync_all would have been run"
return ret
try:
sync_status = __salt__['saltutil.sync_all'](**kwargs)
for key, value in sync_status.items():
if value:
ret['changes'][key] = value
ret['comment'] = "Sync performed"
except Exception as e:
log.error("Failed to run saltutil.sync_all: %s", e)
ret['result'] = False
ret['comment'] = "Failed to run sync_all: {0}".format(e)
return ret
if not ret['changes']:
ret['comment'] = "No updates to sync"
return ret | python | def sync_all(name, **kwargs):
'''
Performs the same task as saltutil.sync_all module
See :mod:`saltutil module for full list of options <salt.modules.saltutil>`
.. code-block:: yaml
sync_everything:
saltutil.sync_all:
- refresh: True
'''
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
if __opts__['test']:
ret['result'] = None
ret['comment'] = "saltutil.sync_all would have been run"
return ret
try:
sync_status = __salt__['saltutil.sync_all'](**kwargs)
for key, value in sync_status.items():
if value:
ret['changes'][key] = value
ret['comment'] = "Sync performed"
except Exception as e:
log.error("Failed to run saltutil.sync_all: %s", e)
ret['result'] = False
ret['comment'] = "Failed to run sync_all: {0}".format(e)
return ret
if not ret['changes']:
ret['comment'] = "No updates to sync"
return ret | [
"def",
"sync_all",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
"}",
"if",
"__opts__",
"[",
"'test'",
"]",
":",... | Performs the same task as saltutil.sync_all module
See :mod:`saltutil module for full list of options <salt.modules.saltutil>`
.. code-block:: yaml
sync_everything:
saltutil.sync_all:
- refresh: True | [
"Performs",
"the",
"same",
"task",
"as",
"saltutil",
".",
"sync_all",
"module",
"See",
":",
"mod",
":",
"saltutil",
"module",
"for",
"full",
"list",
"of",
"options",
"<salt",
".",
"modules",
".",
"saltutil",
">"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/saltutil.py#L54-L87 | train |
saltstack/salt | salt/modules/random_org.py | _query | def _query(api_version=None, data=None):
'''
Slack object method function to construct and execute on the API URL.
:param api_key: The Random.org api key.
:param api_version: The version of Random.org api.
:param data: The data to be sent for POST method.
:return: The json response from the API call or False.
'''
if data is None:
data = {}
ret = {'res': True}
api_url = 'https://api.random.org/'
base_url = _urljoin(api_url, 'json-rpc/' + six.text_type(api_version) + '/invoke')
data = salt.utils.json.dumps(data)
result = salt.utils.http.query(
base_url,
method='POST',
params={},
data=data,
decode=True,
status=True,
header_dict={},
opts=__opts__,
)
if result.get('status', None) == salt.ext.six.moves.http_client.OK:
_result = result['dict']
if _result.get('result'):
return _result.get('result')
if _result.get('error'):
return _result.get('error')
return False
elif result.get('status', None) == salt.ext.six.moves.http_client.NO_CONTENT:
return False
else:
ret['message'] = result.text if hasattr(result, 'text') else ''
return ret | python | def _query(api_version=None, data=None):
'''
Slack object method function to construct and execute on the API URL.
:param api_key: The Random.org api key.
:param api_version: The version of Random.org api.
:param data: The data to be sent for POST method.
:return: The json response from the API call or False.
'''
if data is None:
data = {}
ret = {'res': True}
api_url = 'https://api.random.org/'
base_url = _urljoin(api_url, 'json-rpc/' + six.text_type(api_version) + '/invoke')
data = salt.utils.json.dumps(data)
result = salt.utils.http.query(
base_url,
method='POST',
params={},
data=data,
decode=True,
status=True,
header_dict={},
opts=__opts__,
)
if result.get('status', None) == salt.ext.six.moves.http_client.OK:
_result = result['dict']
if _result.get('result'):
return _result.get('result')
if _result.get('error'):
return _result.get('error')
return False
elif result.get('status', None) == salt.ext.six.moves.http_client.NO_CONTENT:
return False
else:
ret['message'] = result.text if hasattr(result, 'text') else ''
return ret | [
"def",
"_query",
"(",
"api_version",
"=",
"None",
",",
"data",
"=",
"None",
")",
":",
"if",
"data",
"is",
"None",
":",
"data",
"=",
"{",
"}",
"ret",
"=",
"{",
"'res'",
":",
"True",
"}",
"api_url",
"=",
"'https://api.random.org/'",
"base_url",
"=",
"_... | Slack object method function to construct and execute on the API URL.
:param api_key: The Random.org api key.
:param api_version: The version of Random.org api.
:param data: The data to be sent for POST method.
:return: The json response from the API call or False. | [
"Slack",
"object",
"method",
"function",
"to",
"construct",
"and",
"execute",
"on",
"the",
"API",
"URL",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/random_org.py#L81-L123 | train |
saltstack/salt | salt/modules/random_org.py | getUsage | def getUsage(api_key=None, api_version=None):
'''
Show current usages statistics
:param api_key: The Random.org api key.
:param api_version: The Random.org api version.
:return: The current usage statistics.
CLI Example:
.. code-block:: bash
salt '*' random_org.getUsage
salt '*' random_org.getUsage api_key=peWcBiMOS9HrZG15peWcBiMOS9HrZG15 api_version=1
'''
ret = {'res': True}
if not api_key or not api_version:
try:
options = __salt__['config.option']('random_org')
if not api_key:
api_key = options.get('api_key')
if not api_version:
api_version = options.get('api_version')
except (NameError, KeyError, AttributeError):
log.error('No Random.org api key found.')
ret['message'] = 'No Random.org api key or api version found.'
ret['res'] = False
return ret
if isinstance(api_version, int):
api_version = six.text_type(api_version)
_function = RANDOM_ORG_FUNCTIONS.get(api_version).get('getUsage').get('method')
data = {}
data['id'] = 1911220
data['jsonrpc'] = '2.0'
data['method'] = _function
data['params'] = {'apiKey': api_key}
result = _query(api_version=api_version, data=data)
if result:
ret['bitsLeft'] = result.get('bitsLeft')
ret['requestsLeft'] = result.get('requestsLeft')
ret['totalBits'] = result.get('totalBits')
ret['totalRequests'] = result.get('totalRequests')
else:
ret['res'] = False
ret['message'] = result['message']
return ret | python | def getUsage(api_key=None, api_version=None):
'''
Show current usages statistics
:param api_key: The Random.org api key.
:param api_version: The Random.org api version.
:return: The current usage statistics.
CLI Example:
.. code-block:: bash
salt '*' random_org.getUsage
salt '*' random_org.getUsage api_key=peWcBiMOS9HrZG15peWcBiMOS9HrZG15 api_version=1
'''
ret = {'res': True}
if not api_key or not api_version:
try:
options = __salt__['config.option']('random_org')
if not api_key:
api_key = options.get('api_key')
if not api_version:
api_version = options.get('api_version')
except (NameError, KeyError, AttributeError):
log.error('No Random.org api key found.')
ret['message'] = 'No Random.org api key or api version found.'
ret['res'] = False
return ret
if isinstance(api_version, int):
api_version = six.text_type(api_version)
_function = RANDOM_ORG_FUNCTIONS.get(api_version).get('getUsage').get('method')
data = {}
data['id'] = 1911220
data['jsonrpc'] = '2.0'
data['method'] = _function
data['params'] = {'apiKey': api_key}
result = _query(api_version=api_version, data=data)
if result:
ret['bitsLeft'] = result.get('bitsLeft')
ret['requestsLeft'] = result.get('requestsLeft')
ret['totalBits'] = result.get('totalBits')
ret['totalRequests'] = result.get('totalRequests')
else:
ret['res'] = False
ret['message'] = result['message']
return ret | [
"def",
"getUsage",
"(",
"api_key",
"=",
"None",
",",
"api_version",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'res'",
":",
"True",
"}",
"if",
"not",
"api_key",
"or",
"not",
"api_version",
":",
"try",
":",
"options",
"=",
"__salt__",
"[",
"'config.option... | Show current usages statistics
:param api_key: The Random.org api key.
:param api_version: The Random.org api version.
:return: The current usage statistics.
CLI Example:
.. code-block:: bash
salt '*' random_org.getUsage
salt '*' random_org.getUsage api_key=peWcBiMOS9HrZG15peWcBiMOS9HrZG15 api_version=1 | [
"Show",
"current",
"usages",
"statistics"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/random_org.py#L126-L177 | train |
saltstack/salt | salt/modules/random_org.py | generateIntegers | def generateIntegers(api_key=None,
api_version=None,
**kwargs):
'''
Generate random integers
:param api_key: The Random.org api key.
:param api_version: The Random.org api version.
:param number: The number of integers to generate
:param minimum: The lower boundary for the range from which the
random numbers will be picked. Must be within
the [-1e9,1e9] range.
:param maximum: The upper boundary for the range from which the
random numbers will be picked. Must be within
the [-1e9,1e9] range.
:param replacement: Specifies whether the random numbers should
be picked with replacement. The default (true)
will cause the numbers to be picked with replacement,
i.e., the resulting numbers may contain duplicate
values (like a series of dice rolls). If you want the
numbers picked to be unique (like raffle tickets drawn
from a container), set this value to false.
:param base: Specifies the base that will be used to display the numbers.
Values allowed are 2, 8, 10 and 16. This affects the JSON
types and formatting of the resulting data as discussed below.
:return: A list of integers.
CLI Example:
.. code-block:: bash
salt '*' random_org.generateIntegers number=5 minimum=1 maximum=6
salt '*' random_org.generateIntegers number=5 minimum=2 maximum=255 base=2
'''
ret = {'res': True}
if not api_key or not api_version:
try:
options = __salt__['config.option']('random_org')
if not api_key:
api_key = options.get('api_key')
if not api_version:
api_version = options.get('api_version')
except (NameError, KeyError, AttributeError):
log.error('No Random.org api key found.')
ret['message'] = 'No Random.org api key or api version found.'
ret['res'] = False
return ret
for item in ['number', 'minimum', 'maximum']:
if item not in kwargs:
ret['res'] = False
ret['message'] = 'Rquired argument, {0} is missing.'.format(item)
return ret
if not _numeric(kwargs['number']) or not 1 <= kwargs['number'] <= 10000:
ret['res'] = False
ret['message'] = 'Number of integers must be between 1 and 10000'
return ret
if not _numeric(kwargs['minimum']) or not -1000000000 <= kwargs['minimum'] <= 1000000000:
ret['res'] = False
ret['message'] = 'Minimum argument must be between -1,000,000,000 and 1,000,000,000'
return ret
if not _numeric(kwargs['maximum']) or not -1000000000 <= kwargs['maximum'] <= 1000000000:
ret['res'] = False
ret['message'] = 'Maximum argument must be between -1,000,000,000 and 1,000,000,000'
return ret
if 'base' in kwargs:
base = kwargs['base']
if base not in [2, 8, 10, 16]:
ret['res'] = False
ret['message'] = 'Base must be either 2, 8, 10 or 16.'
return ret
else:
base = 10
if 'replacement' not in kwargs:
replacement = True
else:
replacement = kwargs['replacement']
if isinstance(api_version, int):
api_version = six.text_type(api_version)
_function = RANDOM_ORG_FUNCTIONS.get(api_version).get('generateIntegers').get('method')
data = {}
data['id'] = 1911220
data['jsonrpc'] = '2.0'
data['method'] = _function
data['params'] = {'apiKey': api_key,
'n': kwargs['number'],
'min': kwargs['minimum'],
'max': kwargs['maximum'],
'replacement': replacement,
'base': base
}
result = _query(api_version=api_version, data=data)
log.debug('result %s', result)
if result:
if 'random' in result:
random_data = result.get('random').get('data')
ret['data'] = random_data
else:
ret['res'] = False
ret['message'] = result['message']
else:
ret['res'] = False
ret['message'] = result['message']
return ret | python | def generateIntegers(api_key=None,
api_version=None,
**kwargs):
'''
Generate random integers
:param api_key: The Random.org api key.
:param api_version: The Random.org api version.
:param number: The number of integers to generate
:param minimum: The lower boundary for the range from which the
random numbers will be picked. Must be within
the [-1e9,1e9] range.
:param maximum: The upper boundary for the range from which the
random numbers will be picked. Must be within
the [-1e9,1e9] range.
:param replacement: Specifies whether the random numbers should
be picked with replacement. The default (true)
will cause the numbers to be picked with replacement,
i.e., the resulting numbers may contain duplicate
values (like a series of dice rolls). If you want the
numbers picked to be unique (like raffle tickets drawn
from a container), set this value to false.
:param base: Specifies the base that will be used to display the numbers.
Values allowed are 2, 8, 10 and 16. This affects the JSON
types and formatting of the resulting data as discussed below.
:return: A list of integers.
CLI Example:
.. code-block:: bash
salt '*' random_org.generateIntegers number=5 minimum=1 maximum=6
salt '*' random_org.generateIntegers number=5 minimum=2 maximum=255 base=2
'''
ret = {'res': True}
if not api_key or not api_version:
try:
options = __salt__['config.option']('random_org')
if not api_key:
api_key = options.get('api_key')
if not api_version:
api_version = options.get('api_version')
except (NameError, KeyError, AttributeError):
log.error('No Random.org api key found.')
ret['message'] = 'No Random.org api key or api version found.'
ret['res'] = False
return ret
for item in ['number', 'minimum', 'maximum']:
if item not in kwargs:
ret['res'] = False
ret['message'] = 'Rquired argument, {0} is missing.'.format(item)
return ret
if not _numeric(kwargs['number']) or not 1 <= kwargs['number'] <= 10000:
ret['res'] = False
ret['message'] = 'Number of integers must be between 1 and 10000'
return ret
if not _numeric(kwargs['minimum']) or not -1000000000 <= kwargs['minimum'] <= 1000000000:
ret['res'] = False
ret['message'] = 'Minimum argument must be between -1,000,000,000 and 1,000,000,000'
return ret
if not _numeric(kwargs['maximum']) or not -1000000000 <= kwargs['maximum'] <= 1000000000:
ret['res'] = False
ret['message'] = 'Maximum argument must be between -1,000,000,000 and 1,000,000,000'
return ret
if 'base' in kwargs:
base = kwargs['base']
if base not in [2, 8, 10, 16]:
ret['res'] = False
ret['message'] = 'Base must be either 2, 8, 10 or 16.'
return ret
else:
base = 10
if 'replacement' not in kwargs:
replacement = True
else:
replacement = kwargs['replacement']
if isinstance(api_version, int):
api_version = six.text_type(api_version)
_function = RANDOM_ORG_FUNCTIONS.get(api_version).get('generateIntegers').get('method')
data = {}
data['id'] = 1911220
data['jsonrpc'] = '2.0'
data['method'] = _function
data['params'] = {'apiKey': api_key,
'n': kwargs['number'],
'min': kwargs['minimum'],
'max': kwargs['maximum'],
'replacement': replacement,
'base': base
}
result = _query(api_version=api_version, data=data)
log.debug('result %s', result)
if result:
if 'random' in result:
random_data = result.get('random').get('data')
ret['data'] = random_data
else:
ret['res'] = False
ret['message'] = result['message']
else:
ret['res'] = False
ret['message'] = result['message']
return ret | [
"def",
"generateIntegers",
"(",
"api_key",
"=",
"None",
",",
"api_version",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'res'",
":",
"True",
"}",
"if",
"not",
"api_key",
"or",
"not",
"api_version",
":",
"try",
":",
"options",
"=... | Generate random integers
:param api_key: The Random.org api key.
:param api_version: The Random.org api version.
:param number: The number of integers to generate
:param minimum: The lower boundary for the range from which the
random numbers will be picked. Must be within
the [-1e9,1e9] range.
:param maximum: The upper boundary for the range from which the
random numbers will be picked. Must be within
the [-1e9,1e9] range.
:param replacement: Specifies whether the random numbers should
be picked with replacement. The default (true)
will cause the numbers to be picked with replacement,
i.e., the resulting numbers may contain duplicate
values (like a series of dice rolls). If you want the
numbers picked to be unique (like raffle tickets drawn
from a container), set this value to false.
:param base: Specifies the base that will be used to display the numbers.
Values allowed are 2, 8, 10 and 16. This affects the JSON
types and formatting of the resulting data as discussed below.
:return: A list of integers.
CLI Example:
.. code-block:: bash
salt '*' random_org.generateIntegers number=5 minimum=1 maximum=6
salt '*' random_org.generateIntegers number=5 minimum=2 maximum=255 base=2 | [
"Generate",
"random",
"integers"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/random_org.py#L180-L294 | train |
saltstack/salt | salt/utils/oset.py | OrderedSet.add | def add(self, key):
"""
Add `key` as an item to this OrderedSet, then return its index.
If `key` is already in the OrderedSet, return the index it already
had.
"""
if key not in self.map:
self.map[key] = len(self.items)
self.items.append(key)
return self.map[key] | python | def add(self, key):
"""
Add `key` as an item to this OrderedSet, then return its index.
If `key` is already in the OrderedSet, return the index it already
had.
"""
if key not in self.map:
self.map[key] = len(self.items)
self.items.append(key)
return self.map[key] | [
"def",
"add",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
"not",
"in",
"self",
".",
"map",
":",
"self",
".",
"map",
"[",
"key",
"]",
"=",
"len",
"(",
"self",
".",
"items",
")",
"self",
".",
"items",
".",
"append",
"(",
"key",
")",
"return... | Add `key` as an item to this OrderedSet, then return its index.
If `key` is already in the OrderedSet, return the index it already
had. | [
"Add",
"key",
"as",
"an",
"item",
"to",
"this",
"OrderedSet",
"then",
"return",
"its",
"index",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/oset.py#L110-L120 | train |
saltstack/salt | salt/utils/oset.py | OrderedSet.index | def index(self, key):
"""
Get the index of a given entry, raising an IndexError if it's not
present.
`key` can be an iterable of entries that is not a string, in which case
this returns a list of indices.
"""
if is_iterable(key):
return [self.index(subkey) for subkey in key]
return self.map[key] | python | def index(self, key):
"""
Get the index of a given entry, raising an IndexError if it's not
present.
`key` can be an iterable of entries that is not a string, in which case
this returns a list of indices.
"""
if is_iterable(key):
return [self.index(subkey) for subkey in key]
return self.map[key] | [
"def",
"index",
"(",
"self",
",",
"key",
")",
":",
"if",
"is_iterable",
"(",
"key",
")",
":",
"return",
"[",
"self",
".",
"index",
"(",
"subkey",
")",
"for",
"subkey",
"in",
"key",
"]",
"return",
"self",
".",
"map",
"[",
"key",
"]"
] | Get the index of a given entry, raising an IndexError if it's not
present.
`key` can be an iterable of entries that is not a string, in which case
this returns a list of indices. | [
"Get",
"the",
"index",
"of",
"a",
"given",
"entry",
"raising",
"an",
"IndexError",
"if",
"it",
"s",
"not",
"present",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/oset.py#L136-L146 | train |
saltstack/salt | salt/utils/oset.py | OrderedSet.discard | def discard(self, key):
"""
Remove an element. Do not raise an exception if absent.
The MutableSet mixin uses this to implement the .remove() method, which
*does* raise an error when asked to remove a non-existent item.
"""
if key in self:
i = self.map[key]
del self.items[i]
del self.map[key]
for k, v in self.map.items():
if v >= i:
self.map[k] = v - 1 | python | def discard(self, key):
"""
Remove an element. Do not raise an exception if absent.
The MutableSet mixin uses this to implement the .remove() method, which
*does* raise an error when asked to remove a non-existent item.
"""
if key in self:
i = self.map[key]
del self.items[i]
del self.map[key]
for k, v in self.map.items():
if v >= i:
self.map[k] = v - 1 | [
"def",
"discard",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
"in",
"self",
":",
"i",
"=",
"self",
".",
"map",
"[",
"key",
"]",
"del",
"self",
".",
"items",
"[",
"i",
"]",
"del",
"self",
".",
"map",
"[",
"key",
"]",
"for",
"k",
",",
"v"... | Remove an element. Do not raise an exception if absent.
The MutableSet mixin uses this to implement the .remove() method, which
*does* raise an error when asked to remove a non-existent item. | [
"Remove",
"an",
"element",
".",
"Do",
"not",
"raise",
"an",
"exception",
"if",
"absent",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/oset.py#L162-L175 | train |
saltstack/salt | salt/runners/git_pillar.py | update | def update(branch=None, repo=None):
'''
.. versionadded:: 2014.1.0
.. versionchanged:: 2015.8.4
This runner function now supports the :ref:`git_pillar
configuration schema <git-pillar-configuration>` introduced in
2015.8.0. Additionally, the branch and repo can now be omitted to
update all git_pillar remotes. The return data has also changed to
a dictionary. The values will be ``True`` only if new commits were
fetched, and ``False`` if there were errors or no new commits were
fetched.
.. versionchanged:: 2018.3.0
The return for a given git_pillar remote will now be ``None`` when no
changes were fetched. ``False`` now is reserved only for instances in
which there were errors.
Fetch one or all configured git_pillar remotes.
.. note::
This will *not* fast-forward the git_pillar cachedir on the master. All
it does is perform a ``git fetch``. If this runner is executed with
``-l debug``, you may see a log message that says that the repo is
up-to-date. Keep in mind that Salt automatically fetches git_pillar
repos roughly every 60 seconds (or whatever
:conf_master:`loop_interval` is set to). So, it is possible that the
repo was fetched automatically in the time between when changes were
pushed to the repo, and when this runner was executed. When in doubt,
simply refresh pillar data using :py:func:`saltutil.refresh_pillar
<salt.modules.saltutil.refresh_pillar>` and then use
:py:func:`pillar.item <salt.modules.pillar.item>` to check if the
pillar data has changed as expected.
CLI Example:
.. code-block:: bash
# Update specific branch and repo
salt-run git_pillar.update branch='branch' repo='https://foo.com/bar.git'
# Update all repos
salt-run git_pillar.update
# Run with debug logging
salt-run git_pillar.update -l debug
'''
ret = {}
for ext_pillar in __opts__.get('ext_pillar', []):
pillar_type = next(iter(ext_pillar))
if pillar_type != 'git':
continue
pillar_conf = ext_pillar[pillar_type]
pillar = salt.utils.gitfs.GitPillar(
__opts__,
pillar_conf,
per_remote_overrides=salt.pillar.git_pillar.PER_REMOTE_OVERRIDES,
per_remote_only=salt.pillar.git_pillar.PER_REMOTE_ONLY,
global_only=salt.pillar.git_pillar.GLOBAL_ONLY)
for remote in pillar.remotes:
# Skip this remote if it doesn't match the search criteria
if branch is not None:
if branch != remote.branch:
continue
if repo is not None:
if repo != remote.url:
continue
try:
result = remote.fetch()
except Exception as exc:
log.error(
'Exception \'%s\' caught while fetching git_pillar '
'remote \'%s\'', exc, remote.id,
exc_info_on_loglevel=logging.DEBUG
)
result = False
finally:
remote.clear_lock()
ret[remote.id] = result
if not ret:
if branch is not None or repo is not None:
raise SaltRunnerError(
'Specified git branch/repo not found in ext_pillar config'
)
else:
raise SaltRunnerError('No git_pillar remotes are configured')
return ret | python | def update(branch=None, repo=None):
'''
.. versionadded:: 2014.1.0
.. versionchanged:: 2015.8.4
This runner function now supports the :ref:`git_pillar
configuration schema <git-pillar-configuration>` introduced in
2015.8.0. Additionally, the branch and repo can now be omitted to
update all git_pillar remotes. The return data has also changed to
a dictionary. The values will be ``True`` only if new commits were
fetched, and ``False`` if there were errors or no new commits were
fetched.
.. versionchanged:: 2018.3.0
The return for a given git_pillar remote will now be ``None`` when no
changes were fetched. ``False`` now is reserved only for instances in
which there were errors.
Fetch one or all configured git_pillar remotes.
.. note::
This will *not* fast-forward the git_pillar cachedir on the master. All
it does is perform a ``git fetch``. If this runner is executed with
``-l debug``, you may see a log message that says that the repo is
up-to-date. Keep in mind that Salt automatically fetches git_pillar
repos roughly every 60 seconds (or whatever
:conf_master:`loop_interval` is set to). So, it is possible that the
repo was fetched automatically in the time between when changes were
pushed to the repo, and when this runner was executed. When in doubt,
simply refresh pillar data using :py:func:`saltutil.refresh_pillar
<salt.modules.saltutil.refresh_pillar>` and then use
:py:func:`pillar.item <salt.modules.pillar.item>` to check if the
pillar data has changed as expected.
CLI Example:
.. code-block:: bash
# Update specific branch and repo
salt-run git_pillar.update branch='branch' repo='https://foo.com/bar.git'
# Update all repos
salt-run git_pillar.update
# Run with debug logging
salt-run git_pillar.update -l debug
'''
ret = {}
for ext_pillar in __opts__.get('ext_pillar', []):
pillar_type = next(iter(ext_pillar))
if pillar_type != 'git':
continue
pillar_conf = ext_pillar[pillar_type]
pillar = salt.utils.gitfs.GitPillar(
__opts__,
pillar_conf,
per_remote_overrides=salt.pillar.git_pillar.PER_REMOTE_OVERRIDES,
per_remote_only=salt.pillar.git_pillar.PER_REMOTE_ONLY,
global_only=salt.pillar.git_pillar.GLOBAL_ONLY)
for remote in pillar.remotes:
# Skip this remote if it doesn't match the search criteria
if branch is not None:
if branch != remote.branch:
continue
if repo is not None:
if repo != remote.url:
continue
try:
result = remote.fetch()
except Exception as exc:
log.error(
'Exception \'%s\' caught while fetching git_pillar '
'remote \'%s\'', exc, remote.id,
exc_info_on_loglevel=logging.DEBUG
)
result = False
finally:
remote.clear_lock()
ret[remote.id] = result
if not ret:
if branch is not None or repo is not None:
raise SaltRunnerError(
'Specified git branch/repo not found in ext_pillar config'
)
else:
raise SaltRunnerError('No git_pillar remotes are configured')
return ret | [
"def",
"update",
"(",
"branch",
"=",
"None",
",",
"repo",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"ext_pillar",
"in",
"__opts__",
".",
"get",
"(",
"'ext_pillar'",
",",
"[",
"]",
")",
":",
"pillar_type",
"=",
"next",
"(",
"iter",
"(",
... | .. versionadded:: 2014.1.0
.. versionchanged:: 2015.8.4
This runner function now supports the :ref:`git_pillar
configuration schema <git-pillar-configuration>` introduced in
2015.8.0. Additionally, the branch and repo can now be omitted to
update all git_pillar remotes. The return data has also changed to
a dictionary. The values will be ``True`` only if new commits were
fetched, and ``False`` if there were errors or no new commits were
fetched.
.. versionchanged:: 2018.3.0
The return for a given git_pillar remote will now be ``None`` when no
changes were fetched. ``False`` now is reserved only for instances in
which there were errors.
Fetch one or all configured git_pillar remotes.
.. note::
This will *not* fast-forward the git_pillar cachedir on the master. All
it does is perform a ``git fetch``. If this runner is executed with
``-l debug``, you may see a log message that says that the repo is
up-to-date. Keep in mind that Salt automatically fetches git_pillar
repos roughly every 60 seconds (or whatever
:conf_master:`loop_interval` is set to). So, it is possible that the
repo was fetched automatically in the time between when changes were
pushed to the repo, and when this runner was executed. When in doubt,
simply refresh pillar data using :py:func:`saltutil.refresh_pillar
<salt.modules.saltutil.refresh_pillar>` and then use
:py:func:`pillar.item <salt.modules.pillar.item>` to check if the
pillar data has changed as expected.
CLI Example:
.. code-block:: bash
# Update specific branch and repo
salt-run git_pillar.update branch='branch' repo='https://foo.com/bar.git'
# Update all repos
salt-run git_pillar.update
# Run with debug logging
salt-run git_pillar.update -l debug | [
"..",
"versionadded",
"::",
"2014",
".",
"1",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/git_pillar.py#L18-L104 | train |
saltstack/salt | salt/states/aptpkg.py | held | def held(name):
'''
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
state = __salt__['pkg.get_selections'](
pattern=name,
)
if not state:
ret.update(comment='Package {0} does not have a state'.format(name))
elif not salt.utils.data.is_true(state.get('hold', False)):
if not __opts__['test']:
result = __salt__['pkg.set_selections'](
selection={'hold': [name]}
)
ret.update(changes=result[name],
result=True,
comment='Package {0} is now being held'.format(name))
else:
ret.update(result=None,
comment='Package {0} is set to be held'.format(name))
else:
ret.update(result=True,
comment='Package {0} is already held'.format(name))
return ret | python | def held(name):
'''
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
state = __salt__['pkg.get_selections'](
pattern=name,
)
if not state:
ret.update(comment='Package {0} does not have a state'.format(name))
elif not salt.utils.data.is_true(state.get('hold', False)):
if not __opts__['test']:
result = __salt__['pkg.set_selections'](
selection={'hold': [name]}
)
ret.update(changes=result[name],
result=True,
comment='Package {0} is now being held'.format(name))
else:
ret.update(result=None,
comment='Package {0} is set to be held'.format(name))
else:
ret.update(result=True,
comment='Package {0} is already held'.format(name))
return ret | [
"def",
"held",
"(",
"name",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
"}",
"state",
"=",
"__salt__",
"[",
"'pkg.get_selections'",
"]",
"(",
"pattern"... | Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux' | [
"Set",
"package",
"in",
"hold",
"state",
"meaning",
"it",
"will",
"not",
"be",
"upgraded",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/aptpkg.py#L30-L58 | train |
saltstack/salt | salt/modules/openbsdservice.py | _get_rc | def _get_rc():
'''
Returns a dict where the key is the daemon's name and
the value a boolean indicating its status (True: enabled or False: disabled).
Check the daemons started by the system in /etc/rc and
configured in /etc/rc.conf and /etc/rc.conf.local.
Also add to the dict all the localy enabled daemons via $pkg_scripts.
'''
daemons_flags = {}
try:
# now read the system startup script /etc/rc
# to know what are the system enabled daemons
with salt.utils.files.fopen('/etc/rc', 'r') as handle:
lines = salt.utils.data.decode(handle.readlines())
except IOError:
log.error('Unable to read /etc/rc')
else:
for line in lines:
match = start_daemon_call_regex.match(line)
if match:
# the matched line is a call to start_daemon()
# we remove the function name
line = line[len(match.group(1)):]
# we retrieve each daemon name from the parameters of start_daemon()
for daemon in start_daemon_parameter_regex.findall(line):
# mark it as enabled
daemons_flags[daemon] = True
# this will execute rc.conf and rc.conf.local
# used in /etc/rc at boot to start the daemons
variables = __salt__['cmd.run']('(. /etc/rc.conf && set)',
clean_env=True,
output_loglevel='quiet',
python_shell=True).split('\n')
for var in variables:
match = service_flags_regex.match(var)
if match:
# the matched var look like daemon_name_flags=, we test its assigned value
# NO: disabled, everything else: enabled
# do not create a new key if the service hasn't been found in /etc/rc, see $pkg_scripts
if match.group(2) == 'NO':
daemons_flags[match.group(1)] = False
else:
match = pkg_scripts_regex.match(var)
if match:
# the matched var is pkg_scripts
# we can retrieve the name of each localy enabled daemon that wasn't hand started via /etc/rc
for daemon in match.group(1).split():
# create a new key and mark it as enabled
daemons_flags[daemon] = True
return daemons_flags | python | def _get_rc():
'''
Returns a dict where the key is the daemon's name and
the value a boolean indicating its status (True: enabled or False: disabled).
Check the daemons started by the system in /etc/rc and
configured in /etc/rc.conf and /etc/rc.conf.local.
Also add to the dict all the localy enabled daemons via $pkg_scripts.
'''
daemons_flags = {}
try:
# now read the system startup script /etc/rc
# to know what are the system enabled daemons
with salt.utils.files.fopen('/etc/rc', 'r') as handle:
lines = salt.utils.data.decode(handle.readlines())
except IOError:
log.error('Unable to read /etc/rc')
else:
for line in lines:
match = start_daemon_call_regex.match(line)
if match:
# the matched line is a call to start_daemon()
# we remove the function name
line = line[len(match.group(1)):]
# we retrieve each daemon name from the parameters of start_daemon()
for daemon in start_daemon_parameter_regex.findall(line):
# mark it as enabled
daemons_flags[daemon] = True
# this will execute rc.conf and rc.conf.local
# used in /etc/rc at boot to start the daemons
variables = __salt__['cmd.run']('(. /etc/rc.conf && set)',
clean_env=True,
output_loglevel='quiet',
python_shell=True).split('\n')
for var in variables:
match = service_flags_regex.match(var)
if match:
# the matched var look like daemon_name_flags=, we test its assigned value
# NO: disabled, everything else: enabled
# do not create a new key if the service hasn't been found in /etc/rc, see $pkg_scripts
if match.group(2) == 'NO':
daemons_flags[match.group(1)] = False
else:
match = pkg_scripts_regex.match(var)
if match:
# the matched var is pkg_scripts
# we can retrieve the name of each localy enabled daemon that wasn't hand started via /etc/rc
for daemon in match.group(1).split():
# create a new key and mark it as enabled
daemons_flags[daemon] = True
return daemons_flags | [
"def",
"_get_rc",
"(",
")",
":",
"daemons_flags",
"=",
"{",
"}",
"try",
":",
"# now read the system startup script /etc/rc",
"# to know what are the system enabled daemons",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"'/etc/rc'",
",",
"'r'",
")",... | Returns a dict where the key is the daemon's name and
the value a boolean indicating its status (True: enabled or False: disabled).
Check the daemons started by the system in /etc/rc and
configured in /etc/rc.conf and /etc/rc.conf.local.
Also add to the dict all the localy enabled daemons via $pkg_scripts. | [
"Returns",
"a",
"dict",
"where",
"the",
"key",
"is",
"the",
"daemon",
"s",
"name",
"and",
"the",
"value",
"a",
"boolean",
"indicating",
"its",
"status",
"(",
"True",
":",
"enabled",
"or",
"False",
":",
"disabled",
")",
".",
"Check",
"the",
"daemons",
"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/openbsdservice.py#L159-L211 | train |
saltstack/salt | salt/modules/openbsdservice.py | available | def available(name):
'''
.. versionadded:: 2014.7.0
Returns ``True`` if the specified service is available, otherwise returns
``False``.
CLI Example:
.. code-block:: bash
salt '*' service.available sshd
'''
path = '/etc/rc.d/{0}'.format(name)
return os.path.isfile(path) and os.access(path, os.X_OK) | python | def available(name):
'''
.. versionadded:: 2014.7.0
Returns ``True`` if the specified service is available, otherwise returns
``False``.
CLI Example:
.. code-block:: bash
salt '*' service.available sshd
'''
path = '/etc/rc.d/{0}'.format(name)
return os.path.isfile(path) and os.access(path, os.X_OK) | [
"def",
"available",
"(",
"name",
")",
":",
"path",
"=",
"'/etc/rc.d/{0}'",
".",
"format",
"(",
"name",
")",
"return",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
"and",
"os",
".",
"access",
"(",
"path",
",",
"os",
".",
"X_OK",
")"
] | .. versionadded:: 2014.7.0
Returns ``True`` if the specified service is available, otherwise returns
``False``.
CLI Example:
.. code-block:: bash
salt '*' service.available sshd | [
"..",
"versionadded",
"::",
"2014",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/openbsdservice.py#L214-L228 | train |
saltstack/salt | salt/modules/openbsdservice.py | get_all | def get_all():
'''
.. versionadded:: 2014.7.0
Return all available boot services
CLI Example:
.. code-block:: bash
salt '*' service.get_all
'''
services = []
if not os.path.isdir('/etc/rc.d'):
return services
for service in os.listdir('/etc/rc.d'):
# this will remove rc.subr and all non executable files
if available(service):
services.append(service)
return sorted(services) | python | def get_all():
'''
.. versionadded:: 2014.7.0
Return all available boot services
CLI Example:
.. code-block:: bash
salt '*' service.get_all
'''
services = []
if not os.path.isdir('/etc/rc.d'):
return services
for service in os.listdir('/etc/rc.d'):
# this will remove rc.subr and all non executable files
if available(service):
services.append(service)
return sorted(services) | [
"def",
"get_all",
"(",
")",
":",
"services",
"=",
"[",
"]",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"'/etc/rc.d'",
")",
":",
"return",
"services",
"for",
"service",
"in",
"os",
".",
"listdir",
"(",
"'/etc/rc.d'",
")",
":",
"# this will remov... | .. versionadded:: 2014.7.0
Return all available boot services
CLI Example:
.. code-block:: bash
salt '*' service.get_all | [
"..",
"versionadded",
"::",
"2014",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/openbsdservice.py#L248-L267 | train |
saltstack/salt | salt/modules/openbsdservice.py | get_disabled | def get_disabled():
'''
.. versionadded:: 2014.7.0
Return a set of services that are installed but disabled
CLI Example:
.. code-block:: bash
salt '*' service.get_disabled
'''
services = []
for daemon, is_enabled in six.iteritems(_get_rc()):
if not is_enabled:
services.append(daemon)
return sorted(set(get_all()) & set(services)) | python | def get_disabled():
'''
.. versionadded:: 2014.7.0
Return a set of services that are installed but disabled
CLI Example:
.. code-block:: bash
salt '*' service.get_disabled
'''
services = []
for daemon, is_enabled in six.iteritems(_get_rc()):
if not is_enabled:
services.append(daemon)
return sorted(set(get_all()) & set(services)) | [
"def",
"get_disabled",
"(",
")",
":",
"services",
"=",
"[",
"]",
"for",
"daemon",
",",
"is_enabled",
"in",
"six",
".",
"iteritems",
"(",
"_get_rc",
"(",
")",
")",
":",
"if",
"not",
"is_enabled",
":",
"services",
".",
"append",
"(",
"daemon",
")",
"re... | .. versionadded:: 2014.7.0
Return a set of services that are installed but disabled
CLI Example:
.. code-block:: bash
salt '*' service.get_disabled | [
"..",
"versionadded",
"::",
"2014",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/openbsdservice.py#L304-L320 | train |
saltstack/salt | salt/states/mysql_user.py | present | def present(name,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Ensure that the named user is present with the specified properties. A
passwordless user can be configured by omitting ``password`` and
``password_hash``, and setting ``allow_passwordless`` to ``True``.
name
The name of the user to manage
host
Host for which this user/password combo applies
password
The password to use for this user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted to
permit a passwordless login.
.. versionadded:: 0.16.2
unix_socket
If ``True`` and allow_passwordless is ``True``, the unix_socket auth
plugin will be used.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': 'User {0}@{1} is already present'.format(name, host)}
passwordless = not any((password, password_hash))
# check if user exists with the same password (or passwordless login)
if passwordless:
if not salt.utils.data.is_true(allow_passwordless):
ret['comment'] = 'Either password or password_hash must be ' \
'specified, unless allow_passwordless is True'
ret['result'] = False
return ret
else:
if __salt__['mysql.user_exists'](name, host, passwordless=True, unix_socket=unix_socket, password_column=password_column,
**connection_args):
ret['comment'] += ' with passwordless login'
return ret
else:
err = _get_mysql_error()
if err is not None:
ret['comment'] = err
ret['result'] = False
return ret
else:
if __salt__['mysql.user_exists'](name, host, password, password_hash, unix_socket=unix_socket, password_column=password_column,
**connection_args):
ret['comment'] += ' with the desired password'
if password_hash and not password:
ret['comment'] += ' hash'
return ret
else:
err = _get_mysql_error()
if err is not None:
ret['comment'] = err
ret['result'] = False
return ret
# check if user exists with a different password
if __salt__['mysql.user_exists'](name, host, unix_socket=unix_socket, **connection_args):
# The user is present, change the password
if __opts__['test']:
ret['comment'] = \
'Password for user {0}@{1} is set to be '.format(name, host)
ret['result'] = None
if passwordless:
ret['comment'] += 'cleared'
if not salt.utils.data.is_true(allow_passwordless):
ret['comment'] += ', but allow_passwordless != True'
ret['result'] = False
else:
ret['comment'] += 'changed'
return ret
if __salt__['mysql.user_chpass'](name, host,
password, password_hash,
allow_passwordless, unix_socket,
**connection_args):
ret['comment'] = \
'Password for user {0}@{1} has been ' \
'{2}'.format(name, host,
'cleared' if passwordless else 'changed')
ret['changes'][name] = 'Updated'
else:
ret['comment'] = \
'Failed to {0} password for user ' \
'{1}@{2}'.format('clear' if passwordless else 'change',
name, host)
err = _get_mysql_error()
if err is not None:
ret['comment'] += ' ({0})'.format(err)
if passwordless and not salt.utils.data.is_true(allow_passwordless):
ret['comment'] += '. Note: allow_passwordless must be True ' \
'to permit passwordless login.'
ret['result'] = False
else:
err = _get_mysql_error()
if err is not None:
ret['comment'] = err
ret['result'] = False
return ret
# The user is not present, make it!
if __opts__['test']:
ret['comment'] = \
'User {0}@{1} is set to be added'.format(name, host)
ret['result'] = None
if passwordless:
ret['comment'] += ' with passwordless login'
if not salt.utils.data.is_true(allow_passwordless):
ret['comment'] += ', but allow_passwordless != True'
ret['result'] = False
return ret
if __salt__['mysql.user_create'](name, host,
password, password_hash,
allow_passwordless, unix_socket=unix_socket, password_column=password_column,
**connection_args):
ret['comment'] = \
'The user {0}@{1} has been added'.format(name, host)
if passwordless:
ret['comment'] += ' with passwordless login'
ret['changes'][name] = 'Present'
else:
ret['comment'] = 'Failed to create user {0}@{1}'.format(name, host)
err = _get_mysql_error()
if err is not None:
ret['comment'] += ' ({0})'.format(err)
ret['result'] = False
return ret | python | def present(name,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Ensure that the named user is present with the specified properties. A
passwordless user can be configured by omitting ``password`` and
``password_hash``, and setting ``allow_passwordless`` to ``True``.
name
The name of the user to manage
host
Host for which this user/password combo applies
password
The password to use for this user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted to
permit a passwordless login.
.. versionadded:: 0.16.2
unix_socket
If ``True`` and allow_passwordless is ``True``, the unix_socket auth
plugin will be used.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': 'User {0}@{1} is already present'.format(name, host)}
passwordless = not any((password, password_hash))
# check if user exists with the same password (or passwordless login)
if passwordless:
if not salt.utils.data.is_true(allow_passwordless):
ret['comment'] = 'Either password or password_hash must be ' \
'specified, unless allow_passwordless is True'
ret['result'] = False
return ret
else:
if __salt__['mysql.user_exists'](name, host, passwordless=True, unix_socket=unix_socket, password_column=password_column,
**connection_args):
ret['comment'] += ' with passwordless login'
return ret
else:
err = _get_mysql_error()
if err is not None:
ret['comment'] = err
ret['result'] = False
return ret
else:
if __salt__['mysql.user_exists'](name, host, password, password_hash, unix_socket=unix_socket, password_column=password_column,
**connection_args):
ret['comment'] += ' with the desired password'
if password_hash and not password:
ret['comment'] += ' hash'
return ret
else:
err = _get_mysql_error()
if err is not None:
ret['comment'] = err
ret['result'] = False
return ret
# check if user exists with a different password
if __salt__['mysql.user_exists'](name, host, unix_socket=unix_socket, **connection_args):
# The user is present, change the password
if __opts__['test']:
ret['comment'] = \
'Password for user {0}@{1} is set to be '.format(name, host)
ret['result'] = None
if passwordless:
ret['comment'] += 'cleared'
if not salt.utils.data.is_true(allow_passwordless):
ret['comment'] += ', but allow_passwordless != True'
ret['result'] = False
else:
ret['comment'] += 'changed'
return ret
if __salt__['mysql.user_chpass'](name, host,
password, password_hash,
allow_passwordless, unix_socket,
**connection_args):
ret['comment'] = \
'Password for user {0}@{1} has been ' \
'{2}'.format(name, host,
'cleared' if passwordless else 'changed')
ret['changes'][name] = 'Updated'
else:
ret['comment'] = \
'Failed to {0} password for user ' \
'{1}@{2}'.format('clear' if passwordless else 'change',
name, host)
err = _get_mysql_error()
if err is not None:
ret['comment'] += ' ({0})'.format(err)
if passwordless and not salt.utils.data.is_true(allow_passwordless):
ret['comment'] += '. Note: allow_passwordless must be True ' \
'to permit passwordless login.'
ret['result'] = False
else:
err = _get_mysql_error()
if err is not None:
ret['comment'] = err
ret['result'] = False
return ret
# The user is not present, make it!
if __opts__['test']:
ret['comment'] = \
'User {0}@{1} is set to be added'.format(name, host)
ret['result'] = None
if passwordless:
ret['comment'] += ' with passwordless login'
if not salt.utils.data.is_true(allow_passwordless):
ret['comment'] += ', but allow_passwordless != True'
ret['result'] = False
return ret
if __salt__['mysql.user_create'](name, host,
password, password_hash,
allow_passwordless, unix_socket=unix_socket, password_column=password_column,
**connection_args):
ret['comment'] = \
'The user {0}@{1} has been added'.format(name, host)
if passwordless:
ret['comment'] += ' with passwordless login'
ret['changes'][name] = 'Present'
else:
ret['comment'] = 'Failed to create user {0}@{1}'.format(name, host)
err = _get_mysql_error()
if err is not None:
ret['comment'] += ' ({0})'.format(err)
ret['result'] = False
return ret | [
"def",
"present",
"(",
"name",
",",
"host",
"=",
"'localhost'",
",",
"password",
"=",
"None",
",",
"password_hash",
"=",
"None",
",",
"allow_passwordless",
"=",
"False",
",",
"unix_socket",
"=",
"False",
",",
"password_column",
"=",
"None",
",",
"*",
"*",
... | Ensure that the named user is present with the specified properties. A
passwordless user can be configured by omitting ``password`` and
``password_hash``, and setting ``allow_passwordless`` to ``True``.
name
The name of the user to manage
host
Host for which this user/password combo applies
password
The password to use for this user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted to
permit a passwordless login.
.. versionadded:: 0.16.2
unix_socket
If ``True`` and allow_passwordless is ``True``, the unix_socket auth
plugin will be used. | [
"Ensure",
"that",
"the",
"named",
"user",
"is",
"present",
"with",
"the",
"specified",
"properties",
".",
"A",
"passwordless",
"user",
"can",
"be",
"configured",
"by",
"omitting",
"password",
"and",
"password_hash",
"and",
"setting",
"allow_passwordless",
"to",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/mysql_user.py#L69-L228 | train |
saltstack/salt | salt/modules/ini_manage.py | set_option | def set_option(file_name, sections=None, separator='='):
'''
Edit an ini file, replacing one or more sections. Returns a dictionary
containing the changes made.
file_name
path of ini_file
sections : None
A dictionary representing the sections to be edited ini file
The keys are the section names and the values are the dictionary
containing the options
If the ini file does not contain sections the keys and values represent
the options
separator : =
A character used to separate keys and values. Standard ini files use
the "=" character.
.. versionadded:: 2016.11.0
API Example:
.. code-block:: python
import salt
sc = salt.client.get_local_client()
sc.cmd('target', 'ini.set_option',
['path_to_ini_file', '{"section_to_change": {"key": "value"}}'])
CLI Example:
.. code-block:: bash
salt '*' ini.set_option /path/to/ini '{section_foo: {key: value}}'
'''
sections = sections or {}
changes = {}
inifile = _Ini.get_ini_file(file_name, separator=separator)
changes = inifile.update(sections)
if changes:
inifile.flush()
return changes | python | def set_option(file_name, sections=None, separator='='):
'''
Edit an ini file, replacing one or more sections. Returns a dictionary
containing the changes made.
file_name
path of ini_file
sections : None
A dictionary representing the sections to be edited ini file
The keys are the section names and the values are the dictionary
containing the options
If the ini file does not contain sections the keys and values represent
the options
separator : =
A character used to separate keys and values. Standard ini files use
the "=" character.
.. versionadded:: 2016.11.0
API Example:
.. code-block:: python
import salt
sc = salt.client.get_local_client()
sc.cmd('target', 'ini.set_option',
['path_to_ini_file', '{"section_to_change": {"key": "value"}}'])
CLI Example:
.. code-block:: bash
salt '*' ini.set_option /path/to/ini '{section_foo: {key: value}}'
'''
sections = sections or {}
changes = {}
inifile = _Ini.get_ini_file(file_name, separator=separator)
changes = inifile.update(sections)
if changes:
inifile.flush()
return changes | [
"def",
"set_option",
"(",
"file_name",
",",
"sections",
"=",
"None",
",",
"separator",
"=",
"'='",
")",
":",
"sections",
"=",
"sections",
"or",
"{",
"}",
"changes",
"=",
"{",
"}",
"inifile",
"=",
"_Ini",
".",
"get_ini_file",
"(",
"file_name",
",",
"sep... | Edit an ini file, replacing one or more sections. Returns a dictionary
containing the changes made.
file_name
path of ini_file
sections : None
A dictionary representing the sections to be edited ini file
The keys are the section names and the values are the dictionary
containing the options
If the ini file does not contain sections the keys and values represent
the options
separator : =
A character used to separate keys and values. Standard ini files use
the "=" character.
.. versionadded:: 2016.11.0
API Example:
.. code-block:: python
import salt
sc = salt.client.get_local_client()
sc.cmd('target', 'ini.set_option',
['path_to_ini_file', '{"section_to_change": {"key": "value"}}'])
CLI Example:
.. code-block:: bash
salt '*' ini.set_option /path/to/ini '{section_foo: {key: value}}' | [
"Edit",
"an",
"ini",
"file",
"replacing",
"one",
"or",
"more",
"sections",
".",
"Returns",
"a",
"dictionary",
"containing",
"the",
"changes",
"made",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ini_manage.py#L46-L88 | train |
saltstack/salt | salt/modules/ini_manage.py | get_option | def get_option(file_name, section, option, separator='='):
'''
Get value of a key from a section in an ini file. Returns ``None`` if
no matching key was found.
API Example:
.. code-block:: python
import salt
sc = salt.client.get_local_client()
sc.cmd('target', 'ini.get_option',
[path_to_ini_file, section_name, option])
CLI Example:
.. code-block:: bash
salt '*' ini.get_option /path/to/ini section_name option_name
'''
inifile = _Ini.get_ini_file(file_name, separator=separator)
if section:
try:
return inifile.get(section, {}).get(option, None)
except AttributeError:
return None
else:
return inifile.get(option, None) | python | def get_option(file_name, section, option, separator='='):
'''
Get value of a key from a section in an ini file. Returns ``None`` if
no matching key was found.
API Example:
.. code-block:: python
import salt
sc = salt.client.get_local_client()
sc.cmd('target', 'ini.get_option',
[path_to_ini_file, section_name, option])
CLI Example:
.. code-block:: bash
salt '*' ini.get_option /path/to/ini section_name option_name
'''
inifile = _Ini.get_ini_file(file_name, separator=separator)
if section:
try:
return inifile.get(section, {}).get(option, None)
except AttributeError:
return None
else:
return inifile.get(option, None) | [
"def",
"get_option",
"(",
"file_name",
",",
"section",
",",
"option",
",",
"separator",
"=",
"'='",
")",
":",
"inifile",
"=",
"_Ini",
".",
"get_ini_file",
"(",
"file_name",
",",
"separator",
"=",
"separator",
")",
"if",
"section",
":",
"try",
":",
"retur... | Get value of a key from a section in an ini file. Returns ``None`` if
no matching key was found.
API Example:
.. code-block:: python
import salt
sc = salt.client.get_local_client()
sc.cmd('target', 'ini.get_option',
[path_to_ini_file, section_name, option])
CLI Example:
.. code-block:: bash
salt '*' ini.get_option /path/to/ini section_name option_name | [
"Get",
"value",
"of",
"a",
"key",
"from",
"a",
"section",
"in",
"an",
"ini",
"file",
".",
"Returns",
"None",
"if",
"no",
"matching",
"key",
"was",
"found",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ini_manage.py#L91-L118 | train |
saltstack/salt | salt/modules/ini_manage.py | remove_option | def remove_option(file_name, section, option, separator='='):
'''
Remove a key/value pair from a section in an ini file. Returns the value of
the removed key, or ``None`` if nothing was removed.
API Example:
.. code-block:: python
import salt
sc = salt.client.get_local_client()
sc.cmd('target', 'ini.remove_option',
[path_to_ini_file, section_name, option])
CLI Example:
.. code-block:: bash
salt '*' ini.remove_option /path/to/ini section_name option_name
'''
inifile = _Ini.get_ini_file(file_name, separator=separator)
if isinstance(inifile.get(section), (dict, OrderedDict)):
value = inifile.get(section, {}).pop(option, None)
else:
value = inifile.pop(option, None)
if value:
inifile.flush()
return value | python | def remove_option(file_name, section, option, separator='='):
'''
Remove a key/value pair from a section in an ini file. Returns the value of
the removed key, or ``None`` if nothing was removed.
API Example:
.. code-block:: python
import salt
sc = salt.client.get_local_client()
sc.cmd('target', 'ini.remove_option',
[path_to_ini_file, section_name, option])
CLI Example:
.. code-block:: bash
salt '*' ini.remove_option /path/to/ini section_name option_name
'''
inifile = _Ini.get_ini_file(file_name, separator=separator)
if isinstance(inifile.get(section), (dict, OrderedDict)):
value = inifile.get(section, {}).pop(option, None)
else:
value = inifile.pop(option, None)
if value:
inifile.flush()
return value | [
"def",
"remove_option",
"(",
"file_name",
",",
"section",
",",
"option",
",",
"separator",
"=",
"'='",
")",
":",
"inifile",
"=",
"_Ini",
".",
"get_ini_file",
"(",
"file_name",
",",
"separator",
"=",
"separator",
")",
"if",
"isinstance",
"(",
"inifile",
"."... | Remove a key/value pair from a section in an ini file. Returns the value of
the removed key, or ``None`` if nothing was removed.
API Example:
.. code-block:: python
import salt
sc = salt.client.get_local_client()
sc.cmd('target', 'ini.remove_option',
[path_to_ini_file, section_name, option])
CLI Example:
.. code-block:: bash
salt '*' ini.remove_option /path/to/ini section_name option_name | [
"Remove",
"a",
"key",
"/",
"value",
"pair",
"from",
"a",
"section",
"in",
"an",
"ini",
"file",
".",
"Returns",
"the",
"value",
"of",
"the",
"removed",
"key",
"or",
"None",
"if",
"nothing",
"was",
"removed",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ini_manage.py#L121-L148 | train |
saltstack/salt | salt/modules/ini_manage.py | get_section | def get_section(file_name, section, separator='='):
'''
Retrieve a section from an ini file. Returns the section as dictionary. If
the section is not found, an empty dictionary is returned.
API Example:
.. code-block:: python
import salt
sc = salt.client.get_local_client()
sc.cmd('target', 'ini.get_section',
[path_to_ini_file, section_name])
CLI Example:
.. code-block:: bash
salt '*' ini.get_section /path/to/ini section_name
'''
inifile = _Ini.get_ini_file(file_name, separator=separator)
ret = {}
for key, value in six.iteritems(inifile.get(section, {})):
if key[0] != '#':
ret.update({key: value})
return ret | python | def get_section(file_name, section, separator='='):
'''
Retrieve a section from an ini file. Returns the section as dictionary. If
the section is not found, an empty dictionary is returned.
API Example:
.. code-block:: python
import salt
sc = salt.client.get_local_client()
sc.cmd('target', 'ini.get_section',
[path_to_ini_file, section_name])
CLI Example:
.. code-block:: bash
salt '*' ini.get_section /path/to/ini section_name
'''
inifile = _Ini.get_ini_file(file_name, separator=separator)
ret = {}
for key, value in six.iteritems(inifile.get(section, {})):
if key[0] != '#':
ret.update({key: value})
return ret | [
"def",
"get_section",
"(",
"file_name",
",",
"section",
",",
"separator",
"=",
"'='",
")",
":",
"inifile",
"=",
"_Ini",
".",
"get_ini_file",
"(",
"file_name",
",",
"separator",
"=",
"separator",
")",
"ret",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"i... | Retrieve a section from an ini file. Returns the section as dictionary. If
the section is not found, an empty dictionary is returned.
API Example:
.. code-block:: python
import salt
sc = salt.client.get_local_client()
sc.cmd('target', 'ini.get_section',
[path_to_ini_file, section_name])
CLI Example:
.. code-block:: bash
salt '*' ini.get_section /path/to/ini section_name | [
"Retrieve",
"a",
"section",
"from",
"an",
"ini",
"file",
".",
"Returns",
"the",
"section",
"as",
"dictionary",
".",
"If",
"the",
"section",
"is",
"not",
"found",
"an",
"empty",
"dictionary",
"is",
"returned",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ini_manage.py#L151-L176 | train |
saltstack/salt | salt/modules/ini_manage.py | remove_section | def remove_section(file_name, section, separator='='):
'''
Remove a section in an ini file. Returns the removed section as dictionary,
or ``None`` if nothing was removed.
API Example:
.. code-block:: python
import salt
sc = salt.client.get_local_client()
sc.cmd('target', 'ini.remove_section',
[path_to_ini_file, section_name])
CLI Example:
.. code-block:: bash
salt '*' ini.remove_section /path/to/ini section_name
'''
inifile = _Ini.get_ini_file(file_name, separator=separator)
if section in inifile:
section = inifile.pop(section)
inifile.flush()
ret = {}
for key, value in six.iteritems(section):
if key[0] != '#':
ret.update({key: value})
return ret | python | def remove_section(file_name, section, separator='='):
'''
Remove a section in an ini file. Returns the removed section as dictionary,
or ``None`` if nothing was removed.
API Example:
.. code-block:: python
import salt
sc = salt.client.get_local_client()
sc.cmd('target', 'ini.remove_section',
[path_to_ini_file, section_name])
CLI Example:
.. code-block:: bash
salt '*' ini.remove_section /path/to/ini section_name
'''
inifile = _Ini.get_ini_file(file_name, separator=separator)
if section in inifile:
section = inifile.pop(section)
inifile.flush()
ret = {}
for key, value in six.iteritems(section):
if key[0] != '#':
ret.update({key: value})
return ret | [
"def",
"remove_section",
"(",
"file_name",
",",
"section",
",",
"separator",
"=",
"'='",
")",
":",
"inifile",
"=",
"_Ini",
".",
"get_ini_file",
"(",
"file_name",
",",
"separator",
"=",
"separator",
")",
"if",
"section",
"in",
"inifile",
":",
"section",
"="... | Remove a section in an ini file. Returns the removed section as dictionary,
or ``None`` if nothing was removed.
API Example:
.. code-block:: python
import salt
sc = salt.client.get_local_client()
sc.cmd('target', 'ini.remove_section',
[path_to_ini_file, section_name])
CLI Example:
.. code-block:: bash
salt '*' ini.remove_section /path/to/ini section_name | [
"Remove",
"a",
"section",
"in",
"an",
"ini",
"file",
".",
"Returns",
"the",
"removed",
"section",
"as",
"dictionary",
"or",
"None",
"if",
"nothing",
"was",
"removed",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ini_manage.py#L179-L207 | train |
saltstack/salt | salt/modules/ini_manage.py | get_ini | def get_ini(file_name, separator='='):
'''
Retrieve whole structure from an ini file and return it as dictionary.
API Example:
.. code-block:: python
import salt
sc = salt.client.get_local_client()
sc.cmd('target', 'ini.get_ini',
[path_to_ini_file])
CLI Example:
.. code-block:: bash
salt '*' ini.get_ini /path/to/ini
'''
def ini_odict2dict(odict):
'''
Transform OrderedDict to regular dict recursively
:param odict: OrderedDict
:return: regular dict
'''
ret = {}
for key, val in six.iteritems(odict):
if key[0] != '#':
if isinstance(val, (dict, OrderedDict)):
ret.update({key: ini_odict2dict(val)})
else:
ret.update({key: val})
return ret
inifile = _Ini.get_ini_file(file_name, separator=separator)
return ini_odict2dict(inifile) | python | def get_ini(file_name, separator='='):
'''
Retrieve whole structure from an ini file and return it as dictionary.
API Example:
.. code-block:: python
import salt
sc = salt.client.get_local_client()
sc.cmd('target', 'ini.get_ini',
[path_to_ini_file])
CLI Example:
.. code-block:: bash
salt '*' ini.get_ini /path/to/ini
'''
def ini_odict2dict(odict):
'''
Transform OrderedDict to regular dict recursively
:param odict: OrderedDict
:return: regular dict
'''
ret = {}
for key, val in six.iteritems(odict):
if key[0] != '#':
if isinstance(val, (dict, OrderedDict)):
ret.update({key: ini_odict2dict(val)})
else:
ret.update({key: val})
return ret
inifile = _Ini.get_ini_file(file_name, separator=separator)
return ini_odict2dict(inifile) | [
"def",
"get_ini",
"(",
"file_name",
",",
"separator",
"=",
"'='",
")",
":",
"def",
"ini_odict2dict",
"(",
"odict",
")",
":",
"'''\n Transform OrderedDict to regular dict recursively\n :param odict: OrderedDict\n :return: regular dict\n '''",
"ret",
"="... | Retrieve whole structure from an ini file and return it as dictionary.
API Example:
.. code-block:: python
import salt
sc = salt.client.get_local_client()
sc.cmd('target', 'ini.get_ini',
[path_to_ini_file])
CLI Example:
.. code-block:: bash
salt '*' ini.get_ini /path/to/ini | [
"Retrieve",
"whole",
"structure",
"from",
"an",
"ini",
"file",
"and",
"return",
"it",
"as",
"dictionary",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ini_manage.py#L210-L245 | train |
saltstack/salt | salt/renderers/py.py | render | def render(template, saltenv='base', sls='', tmplpath=None, **kws):
'''
Render the python module's components
:rtype: string
'''
template = tmplpath
if not os.path.isfile(template):
raise SaltRenderError('Template {0} is not a file!'.format(template))
tmp_data = salt.utils.templates.py(
template,
True,
__salt__=__salt__,
salt=__salt__,
__grains__=__grains__,
grains=__grains__,
__opts__=__opts__,
opts=__opts__,
__pillar__=__pillar__,
pillar=__pillar__,
__env__=saltenv,
saltenv=saltenv,
__sls__=sls,
sls=sls,
**kws)
if not tmp_data.get('result', False):
raise SaltRenderError(tmp_data.get('data',
'Unknown render error in py renderer'))
return tmp_data['data'] | python | def render(template, saltenv='base', sls='', tmplpath=None, **kws):
'''
Render the python module's components
:rtype: string
'''
template = tmplpath
if not os.path.isfile(template):
raise SaltRenderError('Template {0} is not a file!'.format(template))
tmp_data = salt.utils.templates.py(
template,
True,
__salt__=__salt__,
salt=__salt__,
__grains__=__grains__,
grains=__grains__,
__opts__=__opts__,
opts=__opts__,
__pillar__=__pillar__,
pillar=__pillar__,
__env__=saltenv,
saltenv=saltenv,
__sls__=sls,
sls=sls,
**kws)
if not tmp_data.get('result', False):
raise SaltRenderError(tmp_data.get('data',
'Unknown render error in py renderer'))
return tmp_data['data'] | [
"def",
"render",
"(",
"template",
",",
"saltenv",
"=",
"'base'",
",",
"sls",
"=",
"''",
",",
"tmplpath",
"=",
"None",
",",
"*",
"*",
"kws",
")",
":",
"template",
"=",
"tmplpath",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"template",
")",
... | Render the python module's components
:rtype: string | [
"Render",
"the",
"python",
"module",
"s",
"components"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/renderers/py.py#L123-L153 | train |
saltstack/salt | salt/states/rabbitmq_vhost.py | present | def present(name):
'''
Ensure the RabbitMQ VHost exists.
name
VHost name
user
Initial user permission to set on the VHost, if present
.. deprecated:: 2015.8.0
owner
Initial owner permission to set on the VHost, if present
.. deprecated:: 2015.8.0
conf
Initial conf string to apply to the VHost and user. Defaults to .*
.. deprecated:: 2015.8.0
write
Initial write permissions to apply to the VHost and user.
Defaults to .*
.. deprecated:: 2015.8.0
read
Initial read permissions to apply to the VHost and user.
Defaults to .*
.. deprecated:: 2015.8.0
runas
Name of the user to run the command
.. deprecated:: 2015.8.0
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
vhost_exists = __salt__['rabbitmq.vhost_exists'](name)
if vhost_exists:
ret['comment'] = 'Virtual Host \'{0}\' already exists.'.format(name)
return ret
if not __opts__['test']:
result = __salt__['rabbitmq.add_vhost'](name)
if 'Error' in result:
ret['result'] = False
ret['comment'] = result['Error']
return ret
elif 'Added' in result:
ret['comment'] = result['Added']
# If we've reached this far before returning, we have changes.
ret['changes'] = {'old': '', 'new': name}
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Virtual Host \'{0}\' will be created.'.format(name)
return ret | python | def present(name):
'''
Ensure the RabbitMQ VHost exists.
name
VHost name
user
Initial user permission to set on the VHost, if present
.. deprecated:: 2015.8.0
owner
Initial owner permission to set on the VHost, if present
.. deprecated:: 2015.8.0
conf
Initial conf string to apply to the VHost and user. Defaults to .*
.. deprecated:: 2015.8.0
write
Initial write permissions to apply to the VHost and user.
Defaults to .*
.. deprecated:: 2015.8.0
read
Initial read permissions to apply to the VHost and user.
Defaults to .*
.. deprecated:: 2015.8.0
runas
Name of the user to run the command
.. deprecated:: 2015.8.0
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
vhost_exists = __salt__['rabbitmq.vhost_exists'](name)
if vhost_exists:
ret['comment'] = 'Virtual Host \'{0}\' already exists.'.format(name)
return ret
if not __opts__['test']:
result = __salt__['rabbitmq.add_vhost'](name)
if 'Error' in result:
ret['result'] = False
ret['comment'] = result['Error']
return ret
elif 'Added' in result:
ret['comment'] = result['Added']
# If we've reached this far before returning, we have changes.
ret['changes'] = {'old': '', 'new': name}
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Virtual Host \'{0}\' will be created.'.format(name)
return ret | [
"def",
"present",
"(",
"name",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}",
"vhost_exists",
"=",
"__salt__",
"[",
"'rabbitmq.vhost_exists'",
"]",
"(",... | Ensure the RabbitMQ VHost exists.
name
VHost name
user
Initial user permission to set on the VHost, if present
.. deprecated:: 2015.8.0
owner
Initial owner permission to set on the VHost, if present
.. deprecated:: 2015.8.0
conf
Initial conf string to apply to the VHost and user. Defaults to .*
.. deprecated:: 2015.8.0
write
Initial write permissions to apply to the VHost and user.
Defaults to .*
.. deprecated:: 2015.8.0
read
Initial read permissions to apply to the VHost and user.
Defaults to .*
.. deprecated:: 2015.8.0
runas
Name of the user to run the command
.. deprecated:: 2015.8.0 | [
"Ensure",
"the",
"RabbitMQ",
"VHost",
"exists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/rabbitmq_vhost.py#L35-L93 | train |
saltstack/salt | salt/states/dracr.py | property_present | def property_present(properties, admin_username='root', admin_password='calvin', host=None, **kwargs):
'''
properties = {}
'''
ret = {'name': host,
'context': {'Host': host},
'result': True,
'changes': {},
'comment': ''}
if host is None:
output = __salt__['cmd.run_all']('ipmitool lan print')
stdout = output['stdout']
reg = re.compile(r'\s*IP Address\s*:\s*(\d+.\d+.\d+.\d+)\s*')
for line in stdout:
result = reg.match(line)
if result is not None:
# we want group(1) as this is match in parentheses
host = result.group(1)
break
if not host:
ret['result'] = False
ret['comment'] = 'Unknown host!'
return ret
properties_get = {}
for key, value in properties.items():
response = __salt__['dracr.get_property'](host, admin_username, admin_password, key)
if response is False or response['retcode'] != 0:
ret['result'] = False
ret['comment'] = 'Failed to get property from idrac'
return ret
properties_get[key] = response['stdout'].split('\n')[-1].split('=')[-1]
if __opts__['test']:
for key, value in properties.items():
if properties_get[key] == value:
ret['changes'][key] = 'Won\'t be changed'
else:
ret['changes'][key] = 'Will be changed to {0}'.format(properties_get[key])
return ret
for key, value in properties.items():
if properties_get[key] != value:
response = __salt__['dracr.set_property'](host, admin_username, admin_password, key, value)
if response is False or response['retcode'] != 0:
ret['result'] = False
ret['comment'] = 'Failed to set property from idrac'
return ret
ret['changes'][key] = 'will be changed - old value {0} , new value {1}'.format(properties_get[key], value)
return ret | python | def property_present(properties, admin_username='root', admin_password='calvin', host=None, **kwargs):
'''
properties = {}
'''
ret = {'name': host,
'context': {'Host': host},
'result': True,
'changes': {},
'comment': ''}
if host is None:
output = __salt__['cmd.run_all']('ipmitool lan print')
stdout = output['stdout']
reg = re.compile(r'\s*IP Address\s*:\s*(\d+.\d+.\d+.\d+)\s*')
for line in stdout:
result = reg.match(line)
if result is not None:
# we want group(1) as this is match in parentheses
host = result.group(1)
break
if not host:
ret['result'] = False
ret['comment'] = 'Unknown host!'
return ret
properties_get = {}
for key, value in properties.items():
response = __salt__['dracr.get_property'](host, admin_username, admin_password, key)
if response is False or response['retcode'] != 0:
ret['result'] = False
ret['comment'] = 'Failed to get property from idrac'
return ret
properties_get[key] = response['stdout'].split('\n')[-1].split('=')[-1]
if __opts__['test']:
for key, value in properties.items():
if properties_get[key] == value:
ret['changes'][key] = 'Won\'t be changed'
else:
ret['changes'][key] = 'Will be changed to {0}'.format(properties_get[key])
return ret
for key, value in properties.items():
if properties_get[key] != value:
response = __salt__['dracr.set_property'](host, admin_username, admin_password, key, value)
if response is False or response['retcode'] != 0:
ret['result'] = False
ret['comment'] = 'Failed to set property from idrac'
return ret
ret['changes'][key] = 'will be changed - old value {0} , new value {1}'.format(properties_get[key], value)
return ret | [
"def",
"property_present",
"(",
"properties",
",",
"admin_username",
"=",
"'root'",
",",
"admin_password",
"=",
"'calvin'",
",",
"host",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"host",
",",
"'context'",
":",
"{",
... | properties = {} | [
"properties",
"=",
"{}"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/dracr.py#L41-L96 | train |
saltstack/salt | salt/modules/svn.py | _run_svn | def _run_svn(cmd, cwd, user, username, password, opts, **kwargs):
'''
Execute svn
return the output of the command
cmd
The command to run.
cwd
The path to the Subversion repository
user
Run svn as a user other than what the minion runs as
username
Connect to the Subversion server as another user
password
Connect to the Subversion server with this password
.. versionadded:: 0.17.0
opts
Any additional options to add to the command line
kwargs
Additional options to pass to the run-cmd
'''
cmd = ['svn', '--non-interactive', cmd]
options = list(opts)
if username:
options.extend(['--username', username])
if password:
options.extend(['--password', password])
cmd.extend(options)
result = __salt__['cmd.run_all'](cmd, python_shell=False, cwd=cwd, runas=user, **kwargs)
retcode = result['retcode']
if retcode == 0:
return result['stdout']
raise CommandExecutionError(result['stderr'] + '\n\n' + ' '.join(cmd)) | python | def _run_svn(cmd, cwd, user, username, password, opts, **kwargs):
'''
Execute svn
return the output of the command
cmd
The command to run.
cwd
The path to the Subversion repository
user
Run svn as a user other than what the minion runs as
username
Connect to the Subversion server as another user
password
Connect to the Subversion server with this password
.. versionadded:: 0.17.0
opts
Any additional options to add to the command line
kwargs
Additional options to pass to the run-cmd
'''
cmd = ['svn', '--non-interactive', cmd]
options = list(opts)
if username:
options.extend(['--username', username])
if password:
options.extend(['--password', password])
cmd.extend(options)
result = __salt__['cmd.run_all'](cmd, python_shell=False, cwd=cwd, runas=user, **kwargs)
retcode = result['retcode']
if retcode == 0:
return result['stdout']
raise CommandExecutionError(result['stderr'] + '\n\n' + ' '.join(cmd)) | [
"def",
"_run_svn",
"(",
"cmd",
",",
"cwd",
",",
"user",
",",
"username",
",",
"password",
",",
"opts",
",",
"*",
"*",
"kwargs",
")",
":",
"cmd",
"=",
"[",
"'svn'",
",",
"'--non-interactive'",
",",
"cmd",
"]",
"options",
"=",
"list",
"(",
"opts",
")... | Execute svn
return the output of the command
cmd
The command to run.
cwd
The path to the Subversion repository
user
Run svn as a user other than what the minion runs as
username
Connect to the Subversion server as another user
password
Connect to the Subversion server with this password
.. versionadded:: 0.17.0
opts
Any additional options to add to the command line
kwargs
Additional options to pass to the run-cmd | [
"Execute",
"svn",
"return",
"the",
"output",
"of",
"the",
"command"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/svn.py#L30-L73 | train |
saltstack/salt | salt/modules/svn.py | info | def info(cwd,
targets=None,
user=None,
username=None,
password=None,
fmt='str'):
'''
Display the Subversion information from the checkout.
cwd
The path to the Subversion repository
targets : None
files, directories, and URLs to pass to the command as arguments
svn uses '.' by default
user : None
Run svn as a user other than what the minion runs as
username : None
Connect to the Subversion server as another user
password : None
Connect to the Subversion server with this password
.. versionadded:: 0.17.0
fmt : str
How to fmt the output from info.
(str, xml, list, dict)
CLI Example:
.. code-block:: bash
salt '*' svn.info /path/to/svn/repo
'''
opts = list()
if fmt == 'xml':
opts.append('--xml')
if targets:
opts += salt.utils.args.shlex_split(targets)
infos = _run_svn('info', cwd, user, username, password, opts)
if fmt in ('str', 'xml'):
return infos
info_list = []
for infosplit in infos.split('\n\n'):
info_list.append(_INI_RE.findall(infosplit))
if fmt == 'list':
return info_list
if fmt == 'dict':
return [dict(tmp) for tmp in info_list] | python | def info(cwd,
targets=None,
user=None,
username=None,
password=None,
fmt='str'):
'''
Display the Subversion information from the checkout.
cwd
The path to the Subversion repository
targets : None
files, directories, and URLs to pass to the command as arguments
svn uses '.' by default
user : None
Run svn as a user other than what the minion runs as
username : None
Connect to the Subversion server as another user
password : None
Connect to the Subversion server with this password
.. versionadded:: 0.17.0
fmt : str
How to fmt the output from info.
(str, xml, list, dict)
CLI Example:
.. code-block:: bash
salt '*' svn.info /path/to/svn/repo
'''
opts = list()
if fmt == 'xml':
opts.append('--xml')
if targets:
opts += salt.utils.args.shlex_split(targets)
infos = _run_svn('info', cwd, user, username, password, opts)
if fmt in ('str', 'xml'):
return infos
info_list = []
for infosplit in infos.split('\n\n'):
info_list.append(_INI_RE.findall(infosplit))
if fmt == 'list':
return info_list
if fmt == 'dict':
return [dict(tmp) for tmp in info_list] | [
"def",
"info",
"(",
"cwd",
",",
"targets",
"=",
"None",
",",
"user",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"fmt",
"=",
"'str'",
")",
":",
"opts",
"=",
"list",
"(",
")",
"if",
"fmt",
"==",
"'xml'",
":",
"o... | Display the Subversion information from the checkout.
cwd
The path to the Subversion repository
targets : None
files, directories, and URLs to pass to the command as arguments
svn uses '.' by default
user : None
Run svn as a user other than what the minion runs as
username : None
Connect to the Subversion server as another user
password : None
Connect to the Subversion server with this password
.. versionadded:: 0.17.0
fmt : str
How to fmt the output from info.
(str, xml, list, dict)
CLI Example:
.. code-block:: bash
salt '*' svn.info /path/to/svn/repo | [
"Display",
"the",
"Subversion",
"information",
"from",
"the",
"checkout",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/svn.py#L76-L130 | train |
saltstack/salt | salt/modules/svn.py | checkout | def checkout(cwd,
remote,
target=None,
user=None,
username=None,
password=None,
*opts):
'''
Download a working copy of the remote Subversion repository
directory or file
cwd
The path to the Subversion repository
remote : None
URL to checkout
target : None
The name to give the file or directory working copy
Default: svn uses the remote basename
user : None
Run svn as a user other than what the minion runs as
username : None
Connect to the Subversion server as another user
password : None
Connect to the Subversion server with this password
.. versionadded:: 0.17.0
CLI Example:
.. code-block:: bash
salt '*' svn.checkout /path/to/repo svn://remote/repo
'''
opts += (remote,)
if target:
opts += (target,)
return _run_svn('checkout', cwd, user, username, password, opts) | python | def checkout(cwd,
remote,
target=None,
user=None,
username=None,
password=None,
*opts):
'''
Download a working copy of the remote Subversion repository
directory or file
cwd
The path to the Subversion repository
remote : None
URL to checkout
target : None
The name to give the file or directory working copy
Default: svn uses the remote basename
user : None
Run svn as a user other than what the minion runs as
username : None
Connect to the Subversion server as another user
password : None
Connect to the Subversion server with this password
.. versionadded:: 0.17.0
CLI Example:
.. code-block:: bash
salt '*' svn.checkout /path/to/repo svn://remote/repo
'''
opts += (remote,)
if target:
opts += (target,)
return _run_svn('checkout', cwd, user, username, password, opts) | [
"def",
"checkout",
"(",
"cwd",
",",
"remote",
",",
"target",
"=",
"None",
",",
"user",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"*",
"opts",
")",
":",
"opts",
"+=",
"(",
"remote",
",",
")",
"if",
"target",
":"... | Download a working copy of the remote Subversion repository
directory or file
cwd
The path to the Subversion repository
remote : None
URL to checkout
target : None
The name to give the file or directory working copy
Default: svn uses the remote basename
user : None
Run svn as a user other than what the minion runs as
username : None
Connect to the Subversion server as another user
password : None
Connect to the Subversion server with this password
.. versionadded:: 0.17.0
CLI Example:
.. code-block:: bash
salt '*' svn.checkout /path/to/repo svn://remote/repo | [
"Download",
"a",
"working",
"copy",
"of",
"the",
"remote",
"Subversion",
"repository",
"directory",
"or",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/svn.py#L133-L174 | train |
saltstack/salt | salt/modules/svn.py | update | def update(cwd, targets=None, user=None, username=None, password=None, *opts):
'''
Update the current directory, files, or directories from
the remote Subversion repository
cwd
The path to the Subversion repository
targets : None
files and directories to pass to the command as arguments
Default: svn uses '.'
user : None
Run svn as a user other than what the minion runs as
password : None
Connect to the Subversion server with this password
.. versionadded:: 0.17.0
username : None
Connect to the Subversion server as another user
CLI Example:
.. code-block:: bash
salt '*' svn.update /path/to/repo
'''
if targets:
opts += tuple(salt.utils.args.shlex_split(targets))
return _run_svn('update', cwd, user, username, password, opts) | python | def update(cwd, targets=None, user=None, username=None, password=None, *opts):
'''
Update the current directory, files, or directories from
the remote Subversion repository
cwd
The path to the Subversion repository
targets : None
files and directories to pass to the command as arguments
Default: svn uses '.'
user : None
Run svn as a user other than what the minion runs as
password : None
Connect to the Subversion server with this password
.. versionadded:: 0.17.0
username : None
Connect to the Subversion server as another user
CLI Example:
.. code-block:: bash
salt '*' svn.update /path/to/repo
'''
if targets:
opts += tuple(salt.utils.args.shlex_split(targets))
return _run_svn('update', cwd, user, username, password, opts) | [
"def",
"update",
"(",
"cwd",
",",
"targets",
"=",
"None",
",",
"user",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"*",
"opts",
")",
":",
"if",
"targets",
":",
"opts",
"+=",
"tuple",
"(",
"salt",
".",
"utils",
".... | Update the current directory, files, or directories from
the remote Subversion repository
cwd
The path to the Subversion repository
targets : None
files and directories to pass to the command as arguments
Default: svn uses '.'
user : None
Run svn as a user other than what the minion runs as
password : None
Connect to the Subversion server with this password
.. versionadded:: 0.17.0
username : None
Connect to the Subversion server as another user
CLI Example:
.. code-block:: bash
salt '*' svn.update /path/to/repo | [
"Update",
"the",
"current",
"directory",
"files",
"or",
"directories",
"from",
"the",
"remote",
"Subversion",
"repository"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/svn.py#L216-L247 | train |
saltstack/salt | salt/modules/svn.py | export | def export(cwd,
remote,
target=None,
user=None,
username=None,
password=None,
revision='HEAD',
*opts):
'''
Create an unversioned copy of a tree.
cwd
The path to the Subversion repository
remote : None
URL and path to file or directory checkout
target : None
The name to give the file or directory working copy
Default: svn uses the remote basename
user : None
Run svn as a user other than what the minion runs as
username : None
Connect to the Subversion server as another user
password : None
Connect to the Subversion server with this password
.. versionadded:: 0.17.0
CLI Example:
.. code-block:: bash
salt '*' svn.export /path/to/repo svn://remote/repo
'''
opts += (remote,)
if target:
opts += (target,)
revision_args = '-r'
opts += (revision_args, six.text_type(revision),)
return _run_svn('export', cwd, user, username, password, opts) | python | def export(cwd,
remote,
target=None,
user=None,
username=None,
password=None,
revision='HEAD',
*opts):
'''
Create an unversioned copy of a tree.
cwd
The path to the Subversion repository
remote : None
URL and path to file or directory checkout
target : None
The name to give the file or directory working copy
Default: svn uses the remote basename
user : None
Run svn as a user other than what the minion runs as
username : None
Connect to the Subversion server as another user
password : None
Connect to the Subversion server with this password
.. versionadded:: 0.17.0
CLI Example:
.. code-block:: bash
salt '*' svn.export /path/to/repo svn://remote/repo
'''
opts += (remote,)
if target:
opts += (target,)
revision_args = '-r'
opts += (revision_args, six.text_type(revision),)
return _run_svn('export', cwd, user, username, password, opts) | [
"def",
"export",
"(",
"cwd",
",",
"remote",
",",
"target",
"=",
"None",
",",
"user",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"revision",
"=",
"'HEAD'",
",",
"*",
"opts",
")",
":",
"opts",
"+=",
"(",
"remote",
... | Create an unversioned copy of a tree.
cwd
The path to the Subversion repository
remote : None
URL and path to file or directory checkout
target : None
The name to give the file or directory working copy
Default: svn uses the remote basename
user : None
Run svn as a user other than what the minion runs as
username : None
Connect to the Subversion server as another user
password : None
Connect to the Subversion server with this password
.. versionadded:: 0.17.0
CLI Example:
.. code-block:: bash
salt '*' svn.export /path/to/repo svn://remote/repo | [
"Create",
"an",
"unversioned",
"copy",
"of",
"a",
"tree",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/svn.py#L438-L481 | train |
saltstack/salt | salt/utils/stringutils.py | to_bytes | def to_bytes(s, encoding=None, errors='strict'):
'''
Given bytes, bytearray, str, or unicode (python 2), return bytes (str for
python 2)
'''
if encoding is None:
# Try utf-8 first, and fall back to detected encoding
encoding = ('utf-8', __salt_system_encoding__)
if not isinstance(encoding, (tuple, list)):
encoding = (encoding,)
if not encoding:
raise ValueError('encoding cannot be empty')
exc = None
if six.PY3:
if isinstance(s, bytes):
return s
if isinstance(s, bytearray):
return bytes(s)
if isinstance(s, six.string_types):
for enc in encoding:
try:
return s.encode(enc, errors)
except UnicodeEncodeError as err:
exc = err
continue
# The only way we get this far is if a UnicodeEncodeError was
# raised, otherwise we would have already returned (or raised some
# other exception).
raise exc # pylint: disable=raising-bad-type
raise TypeError('expected bytes, bytearray, or str')
else:
return to_str(s, encoding, errors) | python | def to_bytes(s, encoding=None, errors='strict'):
'''
Given bytes, bytearray, str, or unicode (python 2), return bytes (str for
python 2)
'''
if encoding is None:
# Try utf-8 first, and fall back to detected encoding
encoding = ('utf-8', __salt_system_encoding__)
if not isinstance(encoding, (tuple, list)):
encoding = (encoding,)
if not encoding:
raise ValueError('encoding cannot be empty')
exc = None
if six.PY3:
if isinstance(s, bytes):
return s
if isinstance(s, bytearray):
return bytes(s)
if isinstance(s, six.string_types):
for enc in encoding:
try:
return s.encode(enc, errors)
except UnicodeEncodeError as err:
exc = err
continue
# The only way we get this far is if a UnicodeEncodeError was
# raised, otherwise we would have already returned (or raised some
# other exception).
raise exc # pylint: disable=raising-bad-type
raise TypeError('expected bytes, bytearray, or str')
else:
return to_str(s, encoding, errors) | [
"def",
"to_bytes",
"(",
"s",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"'strict'",
")",
":",
"if",
"encoding",
"is",
"None",
":",
"# Try utf-8 first, and fall back to detected encoding",
"encoding",
"=",
"(",
"'utf-8'",
",",
"__salt_system_encoding__",
")"... | Given bytes, bytearray, str, or unicode (python 2), return bytes (str for
python 2) | [
"Given",
"bytes",
"bytearray",
"str",
"or",
"unicode",
"(",
"python",
"2",
")",
"return",
"bytes",
"(",
"str",
"for",
"python",
"2",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/stringutils.py#L30-L63 | train |
saltstack/salt | salt/utils/stringutils.py | to_str | def to_str(s, encoding=None, errors='strict', normalize=False):
'''
Given str, bytes, bytearray, or unicode (py2), return str
'''
def _normalize(s):
try:
return unicodedata.normalize('NFC', s) if normalize else s
except TypeError:
return s
if encoding is None:
# Try utf-8 first, and fall back to detected encoding
encoding = ('utf-8', __salt_system_encoding__)
if not isinstance(encoding, (tuple, list)):
encoding = (encoding,)
if not encoding:
raise ValueError('encoding cannot be empty')
# This shouldn't be six.string_types because if we're on PY2 and we already
# have a string, we should just return it.
if isinstance(s, str):
return _normalize(s)
exc = None
if six.PY3:
if isinstance(s, (bytes, bytearray)):
for enc in encoding:
try:
return _normalize(s.decode(enc, errors))
except UnicodeDecodeError as err:
exc = err
continue
# The only way we get this far is if a UnicodeDecodeError was
# raised, otherwise we would have already returned (or raised some
# other exception).
raise exc # pylint: disable=raising-bad-type
raise TypeError('expected str, bytes, or bytearray not {}'.format(type(s)))
else:
if isinstance(s, bytearray):
return str(s) # future lint: disable=blacklisted-function
if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable
for enc in encoding:
try:
return _normalize(s).encode(enc, errors)
except UnicodeEncodeError as err:
exc = err
continue
# The only way we get this far is if a UnicodeDecodeError was
# raised, otherwise we would have already returned (or raised some
# other exception).
raise exc # pylint: disable=raising-bad-type
raise TypeError('expected str, bytearray, or unicode') | python | def to_str(s, encoding=None, errors='strict', normalize=False):
'''
Given str, bytes, bytearray, or unicode (py2), return str
'''
def _normalize(s):
try:
return unicodedata.normalize('NFC', s) if normalize else s
except TypeError:
return s
if encoding is None:
# Try utf-8 first, and fall back to detected encoding
encoding = ('utf-8', __salt_system_encoding__)
if not isinstance(encoding, (tuple, list)):
encoding = (encoding,)
if not encoding:
raise ValueError('encoding cannot be empty')
# This shouldn't be six.string_types because if we're on PY2 and we already
# have a string, we should just return it.
if isinstance(s, str):
return _normalize(s)
exc = None
if six.PY3:
if isinstance(s, (bytes, bytearray)):
for enc in encoding:
try:
return _normalize(s.decode(enc, errors))
except UnicodeDecodeError as err:
exc = err
continue
# The only way we get this far is if a UnicodeDecodeError was
# raised, otherwise we would have already returned (or raised some
# other exception).
raise exc # pylint: disable=raising-bad-type
raise TypeError('expected str, bytes, or bytearray not {}'.format(type(s)))
else:
if isinstance(s, bytearray):
return str(s) # future lint: disable=blacklisted-function
if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable
for enc in encoding:
try:
return _normalize(s).encode(enc, errors)
except UnicodeEncodeError as err:
exc = err
continue
# The only way we get this far is if a UnicodeDecodeError was
# raised, otherwise we would have already returned (or raised some
# other exception).
raise exc # pylint: disable=raising-bad-type
raise TypeError('expected str, bytearray, or unicode') | [
"def",
"to_str",
"(",
"s",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"'strict'",
",",
"normalize",
"=",
"False",
")",
":",
"def",
"_normalize",
"(",
"s",
")",
":",
"try",
":",
"return",
"unicodedata",
".",
"normalize",
"(",
"'NFC'",
",",
"s",... | Given str, bytes, bytearray, or unicode (py2), return str | [
"Given",
"str",
"bytes",
"bytearray",
"or",
"unicode",
"(",
"py2",
")",
"return",
"str"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/stringutils.py#L66-L118 | train |
saltstack/salt | salt/utils/stringutils.py | to_bool | def to_bool(text):
'''
Convert the string name of a boolean to that boolean value.
'''
downcased_text = six.text_type(text).strip().lower()
if downcased_text == 'false':
return False
elif downcased_text == 'true':
return True
return text | python | def to_bool(text):
'''
Convert the string name of a boolean to that boolean value.
'''
downcased_text = six.text_type(text).strip().lower()
if downcased_text == 'false':
return False
elif downcased_text == 'true':
return True
return text | [
"def",
"to_bool",
"(",
"text",
")",
":",
"downcased_text",
"=",
"six",
".",
"text_type",
"(",
"text",
")",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"if",
"downcased_text",
"==",
"'false'",
":",
"return",
"False",
"elif",
"downcased_text",
"==",
... | Convert the string name of a boolean to that boolean value. | [
"Convert",
"the",
"string",
"name",
"of",
"a",
"boolean",
"to",
"that",
"boolean",
"value",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/stringutils.py#L182-L192 | train |
saltstack/salt | salt/utils/stringutils.py | is_quoted | def is_quoted(value):
'''
Return a single or double quote, if a string is wrapped in extra quotes.
Otherwise return an empty string.
'''
ret = ''
if isinstance(value, six.string_types) \
and value[0] == value[-1] \
and value.startswith(('\'', '"')):
ret = value[0]
return ret | python | def is_quoted(value):
'''
Return a single or double quote, if a string is wrapped in extra quotes.
Otherwise return an empty string.
'''
ret = ''
if isinstance(value, six.string_types) \
and value[0] == value[-1] \
and value.startswith(('\'', '"')):
ret = value[0]
return ret | [
"def",
"is_quoted",
"(",
"value",
")",
":",
"ret",
"=",
"''",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
"and",
"value",
"[",
"0",
"]",
"==",
"value",
"[",
"-",
"1",
"]",
"and",
"value",
".",
"startswith",
"(",
"(",
"... | Return a single or double quote, if a string is wrapped in extra quotes.
Otherwise return an empty string. | [
"Return",
"a",
"single",
"or",
"double",
"quote",
"if",
"a",
"string",
"is",
"wrapped",
"in",
"extra",
"quotes",
".",
"Otherwise",
"return",
"an",
"empty",
"string",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/stringutils.py#L204-L214 | train |
saltstack/salt | salt/utils/stringutils.py | is_binary | def is_binary(data):
'''
Detects if the passed string of data is binary or text
'''
if not data or not isinstance(data, (six.string_types, six.binary_type)):
return False
if isinstance(data, six.binary_type):
if b'\0' in data:
return True
elif str('\0') in data:
return True
text_characters = ''.join([chr(x) for x in range(32, 127)] + list('\n\r\t\b'))
# Get the non-text characters (map each character to itself then use the
# 'remove' option to get rid of the text characters.)
if six.PY3:
if isinstance(data, six.binary_type):
import salt.utils.data
nontext = data.translate(None, salt.utils.data.encode(text_characters))
else:
trans = ''.maketrans('', '', text_characters)
nontext = data.translate(trans)
else:
if isinstance(data, six.text_type):
trans_args = ({ord(x): None for x in text_characters},)
else:
trans_args = (None, str(text_characters)) # future lint: blacklisted-function
nontext = data.translate(*trans_args)
# If more than 30% non-text characters, then
# this is considered binary data
if float(len(nontext)) / len(data) > 0.30:
return True
return False | python | def is_binary(data):
'''
Detects if the passed string of data is binary or text
'''
if not data or not isinstance(data, (six.string_types, six.binary_type)):
return False
if isinstance(data, six.binary_type):
if b'\0' in data:
return True
elif str('\0') in data:
return True
text_characters = ''.join([chr(x) for x in range(32, 127)] + list('\n\r\t\b'))
# Get the non-text characters (map each character to itself then use the
# 'remove' option to get rid of the text characters.)
if six.PY3:
if isinstance(data, six.binary_type):
import salt.utils.data
nontext = data.translate(None, salt.utils.data.encode(text_characters))
else:
trans = ''.maketrans('', '', text_characters)
nontext = data.translate(trans)
else:
if isinstance(data, six.text_type):
trans_args = ({ord(x): None for x in text_characters},)
else:
trans_args = (None, str(text_characters)) # future lint: blacklisted-function
nontext = data.translate(*trans_args)
# If more than 30% non-text characters, then
# this is considered binary data
if float(len(nontext)) / len(data) > 0.30:
return True
return False | [
"def",
"is_binary",
"(",
"data",
")",
":",
"if",
"not",
"data",
"or",
"not",
"isinstance",
"(",
"data",
",",
"(",
"six",
".",
"string_types",
",",
"six",
".",
"binary_type",
")",
")",
":",
"return",
"False",
"if",
"isinstance",
"(",
"data",
",",
"six... | Detects if the passed string of data is binary or text | [
"Detects",
"if",
"the",
"passed",
"string",
"of",
"data",
"is",
"binary",
"or",
"text"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/stringutils.py#L238-L272 | train |
saltstack/salt | salt/utils/stringutils.py | human_to_bytes | def human_to_bytes(size):
'''
Given a human-readable byte string (e.g. 2G, 30M),
return the number of bytes. Will return 0 if the argument has
unexpected form.
.. versionadded:: 2018.3.0
'''
sbytes = size[:-1]
unit = size[-1]
if sbytes.isdigit():
sbytes = int(sbytes)
if unit == 'P':
sbytes *= 1125899906842624
elif unit == 'T':
sbytes *= 1099511627776
elif unit == 'G':
sbytes *= 1073741824
elif unit == 'M':
sbytes *= 1048576
else:
sbytes = 0
else:
sbytes = 0
return sbytes | python | def human_to_bytes(size):
'''
Given a human-readable byte string (e.g. 2G, 30M),
return the number of bytes. Will return 0 if the argument has
unexpected form.
.. versionadded:: 2018.3.0
'''
sbytes = size[:-1]
unit = size[-1]
if sbytes.isdigit():
sbytes = int(sbytes)
if unit == 'P':
sbytes *= 1125899906842624
elif unit == 'T':
sbytes *= 1099511627776
elif unit == 'G':
sbytes *= 1073741824
elif unit == 'M':
sbytes *= 1048576
else:
sbytes = 0
else:
sbytes = 0
return sbytes | [
"def",
"human_to_bytes",
"(",
"size",
")",
":",
"sbytes",
"=",
"size",
"[",
":",
"-",
"1",
"]",
"unit",
"=",
"size",
"[",
"-",
"1",
"]",
"if",
"sbytes",
".",
"isdigit",
"(",
")",
":",
"sbytes",
"=",
"int",
"(",
"sbytes",
")",
"if",
"unit",
"=="... | Given a human-readable byte string (e.g. 2G, 30M),
return the number of bytes. Will return 0 if the argument has
unexpected form.
.. versionadded:: 2018.3.0 | [
"Given",
"a",
"human",
"-",
"readable",
"byte",
"string",
"(",
"e",
".",
"g",
".",
"2G",
"30M",
")",
"return",
"the",
"number",
"of",
"bytes",
".",
"Will",
"return",
"0",
"if",
"the",
"argument",
"has",
"unexpected",
"form",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/stringutils.py#L289-L313 | train |
saltstack/salt | salt/utils/stringutils.py | build_whitespace_split_regex | def build_whitespace_split_regex(text):
'''
Create a regular expression at runtime which should match ignoring the
addition or deletion of white space or line breaks, unless between commas
Example:
.. code-block:: python
>>> import re
>>> import salt.utils.stringutils
>>> regex = salt.utils.stringutils.build_whitespace_split_regex(
... """if [ -z "$debian_chroot" ] && [ -r /etc/debian_chroot ]; then"""
... )
>>> regex
'(?:[\\s]+)?if(?:[\\s]+)?\\[(?:[\\s]+)?\\-z(?:[\\s]+)?\\"\\$debian'
'\\_chroot\\"(?:[\\s]+)?\\](?:[\\s]+)?\\&\\&(?:[\\s]+)?\\[(?:[\\s]+)?'
'\\-r(?:[\\s]+)?\\/etc\\/debian\\_chroot(?:[\\s]+)?\\]\\;(?:[\\s]+)?'
'then(?:[\\s]+)?'
>>> re.search(
... regex,
... """if [ -z "$debian_chroot" ] && [ -r /etc/debian_chroot ]; then"""
... )
<_sre.SRE_Match object at 0xb70639c0>
>>>
'''
def __build_parts(text):
lexer = shlex.shlex(text)
lexer.whitespace_split = True
lexer.commenters = ''
if r"'\"" in text:
lexer.quotes = ''
elif '\'' in text:
lexer.quotes = '"'
elif '"' in text:
lexer.quotes = '\''
return list(lexer)
regex = r''
for line in text.splitlines():
parts = [re.escape(s) for s in __build_parts(line)]
regex += r'(?:[\s]+)?{0}(?:[\s]+)?'.format(r'(?:[\s]+)?'.join(parts))
return r'(?m)^{0}$'.format(regex) | python | def build_whitespace_split_regex(text):
'''
Create a regular expression at runtime which should match ignoring the
addition or deletion of white space or line breaks, unless between commas
Example:
.. code-block:: python
>>> import re
>>> import salt.utils.stringutils
>>> regex = salt.utils.stringutils.build_whitespace_split_regex(
... """if [ -z "$debian_chroot" ] && [ -r /etc/debian_chroot ]; then"""
... )
>>> regex
'(?:[\\s]+)?if(?:[\\s]+)?\\[(?:[\\s]+)?\\-z(?:[\\s]+)?\\"\\$debian'
'\\_chroot\\"(?:[\\s]+)?\\](?:[\\s]+)?\\&\\&(?:[\\s]+)?\\[(?:[\\s]+)?'
'\\-r(?:[\\s]+)?\\/etc\\/debian\\_chroot(?:[\\s]+)?\\]\\;(?:[\\s]+)?'
'then(?:[\\s]+)?'
>>> re.search(
... regex,
... """if [ -z "$debian_chroot" ] && [ -r /etc/debian_chroot ]; then"""
... )
<_sre.SRE_Match object at 0xb70639c0>
>>>
'''
def __build_parts(text):
lexer = shlex.shlex(text)
lexer.whitespace_split = True
lexer.commenters = ''
if r"'\"" in text:
lexer.quotes = ''
elif '\'' in text:
lexer.quotes = '"'
elif '"' in text:
lexer.quotes = '\''
return list(lexer)
regex = r''
for line in text.splitlines():
parts = [re.escape(s) for s in __build_parts(line)]
regex += r'(?:[\s]+)?{0}(?:[\s]+)?'.format(r'(?:[\s]+)?'.join(parts))
return r'(?m)^{0}$'.format(regex) | [
"def",
"build_whitespace_split_regex",
"(",
"text",
")",
":",
"def",
"__build_parts",
"(",
"text",
")",
":",
"lexer",
"=",
"shlex",
".",
"shlex",
"(",
"text",
")",
"lexer",
".",
"whitespace_split",
"=",
"True",
"lexer",
".",
"commenters",
"=",
"''",
"if",
... | Create a regular expression at runtime which should match ignoring the
addition or deletion of white space or line breaks, unless between commas
Example:
.. code-block:: python
>>> import re
>>> import salt.utils.stringutils
>>> regex = salt.utils.stringutils.build_whitespace_split_regex(
... """if [ -z "$debian_chroot" ] && [ -r /etc/debian_chroot ]; then"""
... )
>>> regex
'(?:[\\s]+)?if(?:[\\s]+)?\\[(?:[\\s]+)?\\-z(?:[\\s]+)?\\"\\$debian'
'\\_chroot\\"(?:[\\s]+)?\\](?:[\\s]+)?\\&\\&(?:[\\s]+)?\\[(?:[\\s]+)?'
'\\-r(?:[\\s]+)?\\/etc\\/debian\\_chroot(?:[\\s]+)?\\]\\;(?:[\\s]+)?'
'then(?:[\\s]+)?'
>>> re.search(
... regex,
... """if [ -z "$debian_chroot" ] && [ -r /etc/debian_chroot ]; then"""
... )
<_sre.SRE_Match object at 0xb70639c0>
>>> | [
"Create",
"a",
"regular",
"expression",
"at",
"runtime",
"which",
"should",
"match",
"ignoring",
"the",
"addition",
"or",
"deletion",
"of",
"white",
"space",
"or",
"line",
"breaks",
"unless",
"between",
"commas"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/stringutils.py#L316-L361 | train |
saltstack/salt | salt/utils/stringutils.py | expr_match | def expr_match(line, expr):
'''
Checks whether or not the passed value matches the specified expression.
Tries to match expr first as a glob using fnmatch.fnmatch(), and then tries
to match expr as a regular expression. Originally designed to match minion
IDs for whitelists/blacklists.
Note that this also does exact matches, as fnmatch.fnmatch() will return
``True`` when no glob characters are used and the string is an exact match:
.. code-block:: python
>>> fnmatch.fnmatch('foo', 'foo')
True
'''
try:
if fnmatch.fnmatch(line, expr):
return True
try:
if re.match(r'\A{0}\Z'.format(expr), line):
return True
except re.error:
pass
except TypeError:
log.exception('Value %r or expression %r is not a string', line, expr)
return False | python | def expr_match(line, expr):
'''
Checks whether or not the passed value matches the specified expression.
Tries to match expr first as a glob using fnmatch.fnmatch(), and then tries
to match expr as a regular expression. Originally designed to match minion
IDs for whitelists/blacklists.
Note that this also does exact matches, as fnmatch.fnmatch() will return
``True`` when no glob characters are used and the string is an exact match:
.. code-block:: python
>>> fnmatch.fnmatch('foo', 'foo')
True
'''
try:
if fnmatch.fnmatch(line, expr):
return True
try:
if re.match(r'\A{0}\Z'.format(expr), line):
return True
except re.error:
pass
except TypeError:
log.exception('Value %r or expression %r is not a string', line, expr)
return False | [
"def",
"expr_match",
"(",
"line",
",",
"expr",
")",
":",
"try",
":",
"if",
"fnmatch",
".",
"fnmatch",
"(",
"line",
",",
"expr",
")",
":",
"return",
"True",
"try",
":",
"if",
"re",
".",
"match",
"(",
"r'\\A{0}\\Z'",
".",
"format",
"(",
"expr",
")",
... | Checks whether or not the passed value matches the specified expression.
Tries to match expr first as a glob using fnmatch.fnmatch(), and then tries
to match expr as a regular expression. Originally designed to match minion
IDs for whitelists/blacklists.
Note that this also does exact matches, as fnmatch.fnmatch() will return
``True`` when no glob characters are used and the string is an exact match:
.. code-block:: python
>>> fnmatch.fnmatch('foo', 'foo')
True | [
"Checks",
"whether",
"or",
"not",
"the",
"passed",
"value",
"matches",
"the",
"specified",
"expression",
".",
"Tries",
"to",
"match",
"expr",
"first",
"as",
"a",
"glob",
"using",
"fnmatch",
".",
"fnmatch",
"()",
"and",
"then",
"tries",
"to",
"match",
"expr... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/stringutils.py#L364-L389 | train |
saltstack/salt | salt/utils/stringutils.py | check_whitelist_blacklist | def check_whitelist_blacklist(value, whitelist=None, blacklist=None):
'''
Check a whitelist and/or blacklist to see if the value matches it.
value
The item to check the whitelist and/or blacklist against.
whitelist
The list of items that are white-listed. If ``value`` is found
in the whitelist, then the function returns ``True``. Otherwise,
it returns ``False``.
blacklist
The list of items that are black-listed. If ``value`` is found
in the blacklist, then the function returns ``False``. Otherwise,
it returns ``True``.
If both a whitelist and a blacklist are provided, value membership
in the blacklist will be examined first. If the value is not found
in the blacklist, then the whitelist is checked. If the value isn't
found in the whitelist, the function returns ``False``.
'''
# Normalize the input so that we have a list
if blacklist:
if isinstance(blacklist, six.string_types):
blacklist = [blacklist]
if not hasattr(blacklist, '__iter__'):
raise TypeError(
'Expecting iterable blacklist, but got {0} ({1})'.format(
type(blacklist).__name__, blacklist
)
)
else:
blacklist = []
if whitelist:
if isinstance(whitelist, six.string_types):
whitelist = [whitelist]
if not hasattr(whitelist, '__iter__'):
raise TypeError(
'Expecting iterable whitelist, but got {0} ({1})'.format(
type(whitelist).__name__, whitelist
)
)
else:
whitelist = []
_blacklist_match = any(expr_match(value, expr) for expr in blacklist)
_whitelist_match = any(expr_match(value, expr) for expr in whitelist)
if blacklist and not whitelist:
# Blacklist but no whitelist
return not _blacklist_match
elif whitelist and not blacklist:
# Whitelist but no blacklist
return _whitelist_match
elif blacklist and whitelist:
# Both whitelist and blacklist
return not _blacklist_match and _whitelist_match
else:
# No blacklist or whitelist passed
return True | python | def check_whitelist_blacklist(value, whitelist=None, blacklist=None):
'''
Check a whitelist and/or blacklist to see if the value matches it.
value
The item to check the whitelist and/or blacklist against.
whitelist
The list of items that are white-listed. If ``value`` is found
in the whitelist, then the function returns ``True``. Otherwise,
it returns ``False``.
blacklist
The list of items that are black-listed. If ``value`` is found
in the blacklist, then the function returns ``False``. Otherwise,
it returns ``True``.
If both a whitelist and a blacklist are provided, value membership
in the blacklist will be examined first. If the value is not found
in the blacklist, then the whitelist is checked. If the value isn't
found in the whitelist, the function returns ``False``.
'''
# Normalize the input so that we have a list
if blacklist:
if isinstance(blacklist, six.string_types):
blacklist = [blacklist]
if not hasattr(blacklist, '__iter__'):
raise TypeError(
'Expecting iterable blacklist, but got {0} ({1})'.format(
type(blacklist).__name__, blacklist
)
)
else:
blacklist = []
if whitelist:
if isinstance(whitelist, six.string_types):
whitelist = [whitelist]
if not hasattr(whitelist, '__iter__'):
raise TypeError(
'Expecting iterable whitelist, but got {0} ({1})'.format(
type(whitelist).__name__, whitelist
)
)
else:
whitelist = []
_blacklist_match = any(expr_match(value, expr) for expr in blacklist)
_whitelist_match = any(expr_match(value, expr) for expr in whitelist)
if blacklist and not whitelist:
# Blacklist but no whitelist
return not _blacklist_match
elif whitelist and not blacklist:
# Whitelist but no blacklist
return _whitelist_match
elif blacklist and whitelist:
# Both whitelist and blacklist
return not _blacklist_match and _whitelist_match
else:
# No blacklist or whitelist passed
return True | [
"def",
"check_whitelist_blacklist",
"(",
"value",
",",
"whitelist",
"=",
"None",
",",
"blacklist",
"=",
"None",
")",
":",
"# Normalize the input so that we have a list",
"if",
"blacklist",
":",
"if",
"isinstance",
"(",
"blacklist",
",",
"six",
".",
"string_types",
... | Check a whitelist and/or blacklist to see if the value matches it.
value
The item to check the whitelist and/or blacklist against.
whitelist
The list of items that are white-listed. If ``value`` is found
in the whitelist, then the function returns ``True``. Otherwise,
it returns ``False``.
blacklist
The list of items that are black-listed. If ``value`` is found
in the blacklist, then the function returns ``False``. Otherwise,
it returns ``True``.
If both a whitelist and a blacklist are provided, value membership
in the blacklist will be examined first. If the value is not found
in the blacklist, then the whitelist is checked. If the value isn't
found in the whitelist, the function returns ``False``. | [
"Check",
"a",
"whitelist",
"and",
"/",
"or",
"blacklist",
"to",
"see",
"if",
"the",
"value",
"matches",
"it",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/stringutils.py#L393-L454 | train |
saltstack/salt | salt/utils/stringutils.py | check_include_exclude | def check_include_exclude(path_str, include_pat=None, exclude_pat=None):
'''
Check for glob or regexp patterns for include_pat and exclude_pat in the
'path_str' string and return True/False conditions as follows.
- Default: return 'True' if no include_pat or exclude_pat patterns are
supplied
- If only include_pat or exclude_pat is supplied: return 'True' if string
passes the include_pat test or fails exclude_pat test respectively
- If both include_pat and exclude_pat are supplied: return 'True' if
include_pat matches AND exclude_pat does not match
'''
def _pat_check(path_str, check_pat):
if re.match('E@', check_pat):
return True if re.search(
check_pat[2:],
path_str
) else False
else:
return True if fnmatch.fnmatch(
path_str,
check_pat
) else False
ret = True # -- default true
# Before pattern match, check if it is regexp (E@'') or glob(default)
if include_pat:
if isinstance(include_pat, list):
for include_line in include_pat:
retchk_include = _pat_check(path_str, include_line)
if retchk_include:
break
else:
retchk_include = _pat_check(path_str, include_pat)
if exclude_pat:
if isinstance(exclude_pat, list):
for exclude_line in exclude_pat:
retchk_exclude = not _pat_check(path_str, exclude_line)
if not retchk_exclude:
break
else:
retchk_exclude = not _pat_check(path_str, exclude_pat)
# Now apply include/exclude conditions
if include_pat and not exclude_pat:
ret = retchk_include
elif exclude_pat and not include_pat:
ret = retchk_exclude
elif include_pat and exclude_pat:
ret = retchk_include and retchk_exclude
else:
ret = True
return ret | python | def check_include_exclude(path_str, include_pat=None, exclude_pat=None):
'''
Check for glob or regexp patterns for include_pat and exclude_pat in the
'path_str' string and return True/False conditions as follows.
- Default: return 'True' if no include_pat or exclude_pat patterns are
supplied
- If only include_pat or exclude_pat is supplied: return 'True' if string
passes the include_pat test or fails exclude_pat test respectively
- If both include_pat and exclude_pat are supplied: return 'True' if
include_pat matches AND exclude_pat does not match
'''
def _pat_check(path_str, check_pat):
if re.match('E@', check_pat):
return True if re.search(
check_pat[2:],
path_str
) else False
else:
return True if fnmatch.fnmatch(
path_str,
check_pat
) else False
ret = True # -- default true
# Before pattern match, check if it is regexp (E@'') or glob(default)
if include_pat:
if isinstance(include_pat, list):
for include_line in include_pat:
retchk_include = _pat_check(path_str, include_line)
if retchk_include:
break
else:
retchk_include = _pat_check(path_str, include_pat)
if exclude_pat:
if isinstance(exclude_pat, list):
for exclude_line in exclude_pat:
retchk_exclude = not _pat_check(path_str, exclude_line)
if not retchk_exclude:
break
else:
retchk_exclude = not _pat_check(path_str, exclude_pat)
# Now apply include/exclude conditions
if include_pat and not exclude_pat:
ret = retchk_include
elif exclude_pat and not include_pat:
ret = retchk_exclude
elif include_pat and exclude_pat:
ret = retchk_include and retchk_exclude
else:
ret = True
return ret | [
"def",
"check_include_exclude",
"(",
"path_str",
",",
"include_pat",
"=",
"None",
",",
"exclude_pat",
"=",
"None",
")",
":",
"def",
"_pat_check",
"(",
"path_str",
",",
"check_pat",
")",
":",
"if",
"re",
".",
"match",
"(",
"'E@'",
",",
"check_pat",
")",
"... | Check for glob or regexp patterns for include_pat and exclude_pat in the
'path_str' string and return True/False conditions as follows.
- Default: return 'True' if no include_pat or exclude_pat patterns are
supplied
- If only include_pat or exclude_pat is supplied: return 'True' if string
passes the include_pat test or fails exclude_pat test respectively
- If both include_pat and exclude_pat are supplied: return 'True' if
include_pat matches AND exclude_pat does not match | [
"Check",
"for",
"glob",
"or",
"regexp",
"patterns",
"for",
"include_pat",
"and",
"exclude_pat",
"in",
"the",
"path_str",
"string",
"and",
"return",
"True",
"/",
"False",
"conditions",
"as",
"follows",
".",
"-",
"Default",
":",
"return",
"True",
"if",
"no",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/stringutils.py#L457-L510 | train |
saltstack/salt | salt/utils/stringutils.py | print_cli | def print_cli(msg, retries=10, step=0.01):
'''
Wrapper around print() that suppresses tracebacks on broken pipes (i.e.
when salt output is piped to less and less is stopped prematurely).
'''
while retries:
try:
try:
print(msg)
except UnicodeEncodeError:
print(msg.encode('utf-8'))
except IOError as exc:
err = "{0}".format(exc)
if exc.errno != errno.EPIPE:
if (
("temporarily unavailable" in err or
exc.errno in (errno.EAGAIN,)) and
retries
):
time.sleep(step)
retries -= 1
continue
else:
raise
break | python | def print_cli(msg, retries=10, step=0.01):
'''
Wrapper around print() that suppresses tracebacks on broken pipes (i.e.
when salt output is piped to less and less is stopped prematurely).
'''
while retries:
try:
try:
print(msg)
except UnicodeEncodeError:
print(msg.encode('utf-8'))
except IOError as exc:
err = "{0}".format(exc)
if exc.errno != errno.EPIPE:
if (
("temporarily unavailable" in err or
exc.errno in (errno.EAGAIN,)) and
retries
):
time.sleep(step)
retries -= 1
continue
else:
raise
break | [
"def",
"print_cli",
"(",
"msg",
",",
"retries",
"=",
"10",
",",
"step",
"=",
"0.01",
")",
":",
"while",
"retries",
":",
"try",
":",
"try",
":",
"print",
"(",
"msg",
")",
"except",
"UnicodeEncodeError",
":",
"print",
"(",
"msg",
".",
"encode",
"(",
... | Wrapper around print() that suppresses tracebacks on broken pipes (i.e.
when salt output is piped to less and less is stopped prematurely). | [
"Wrapper",
"around",
"print",
"()",
"that",
"suppresses",
"tracebacks",
"on",
"broken",
"pipes",
"(",
"i",
".",
"e",
".",
"when",
"salt",
"output",
"is",
"piped",
"to",
"less",
"and",
"less",
"is",
"stopped",
"prematurely",
")",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/stringutils.py#L513-L537 | train |
saltstack/salt | salt/utils/stringutils.py | get_context | def get_context(template, line, num_lines=5, marker=None):
'''
Returns debugging context around a line in a given string
Returns:: string
'''
template_lines = template.splitlines()
num_template_lines = len(template_lines)
# In test mode, a single line template would return a crazy line number like,
# 357. Do this sanity check and if the given line is obviously wrong, just
# return the entire template
if line > num_template_lines:
return template
context_start = max(0, line - num_lines - 1) # subt 1 for 0-based indexing
context_end = min(num_template_lines, line + num_lines)
error_line_in_context = line - context_start - 1 # subtr 1 for 0-based idx
buf = []
if context_start > 0:
buf.append('[...]')
error_line_in_context += 1
buf.extend(template_lines[context_start:context_end])
if context_end < num_template_lines:
buf.append('[...]')
if marker:
buf[error_line_in_context] += marker
return '---\n{0}\n---'.format('\n'.join(buf)) | python | def get_context(template, line, num_lines=5, marker=None):
'''
Returns debugging context around a line in a given string
Returns:: string
'''
template_lines = template.splitlines()
num_template_lines = len(template_lines)
# In test mode, a single line template would return a crazy line number like,
# 357. Do this sanity check and if the given line is obviously wrong, just
# return the entire template
if line > num_template_lines:
return template
context_start = max(0, line - num_lines - 1) # subt 1 for 0-based indexing
context_end = min(num_template_lines, line + num_lines)
error_line_in_context = line - context_start - 1 # subtr 1 for 0-based idx
buf = []
if context_start > 0:
buf.append('[...]')
error_line_in_context += 1
buf.extend(template_lines[context_start:context_end])
if context_end < num_template_lines:
buf.append('[...]')
if marker:
buf[error_line_in_context] += marker
return '---\n{0}\n---'.format('\n'.join(buf)) | [
"def",
"get_context",
"(",
"template",
",",
"line",
",",
"num_lines",
"=",
"5",
",",
"marker",
"=",
"None",
")",
":",
"template_lines",
"=",
"template",
".",
"splitlines",
"(",
")",
"num_template_lines",
"=",
"len",
"(",
"template_lines",
")",
"# In test mod... | Returns debugging context around a line in a given string
Returns:: string | [
"Returns",
"debugging",
"context",
"around",
"a",
"line",
"in",
"a",
"given",
"string"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/stringutils.py#L540-L572 | train |
saltstack/salt | salt/utils/stringutils.py | get_diff | def get_diff(a, b, *args, **kwargs):
'''
Perform diff on two iterables containing lines from two files, and return
the diff as as string. Lines are normalized to str types to avoid issues
with unicode on PY2.
'''
encoding = ('utf-8', 'latin-1', __salt_system_encoding__)
# Late import to avoid circular import
import salt.utils.data
return ''.join(
difflib.unified_diff(
salt.utils.data.decode_list(a, encoding=encoding),
salt.utils.data.decode_list(b, encoding=encoding),
*args, **kwargs
)
) | python | def get_diff(a, b, *args, **kwargs):
'''
Perform diff on two iterables containing lines from two files, and return
the diff as as string. Lines are normalized to str types to avoid issues
with unicode on PY2.
'''
encoding = ('utf-8', 'latin-1', __salt_system_encoding__)
# Late import to avoid circular import
import salt.utils.data
return ''.join(
difflib.unified_diff(
salt.utils.data.decode_list(a, encoding=encoding),
salt.utils.data.decode_list(b, encoding=encoding),
*args, **kwargs
)
) | [
"def",
"get_diff",
"(",
"a",
",",
"b",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"encoding",
"=",
"(",
"'utf-8'",
",",
"'latin-1'",
",",
"__salt_system_encoding__",
")",
"# Late import to avoid circular import",
"import",
"salt",
".",
"utils",
"."... | Perform diff on two iterables containing lines from two files, and return
the diff as as string. Lines are normalized to str types to avoid issues
with unicode on PY2. | [
"Perform",
"diff",
"on",
"two",
"iterables",
"containing",
"lines",
"from",
"two",
"files",
"and",
"return",
"the",
"diff",
"as",
"as",
"string",
".",
"Lines",
"are",
"normalized",
"to",
"str",
"types",
"to",
"avoid",
"issues",
"with",
"unicode",
"on",
"PY... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/stringutils.py#L575-L590 | train |
saltstack/salt | salt/utils/stringutils.py | camel_to_snake_case | def camel_to_snake_case(camel_input):
'''
Converts camelCase (or CamelCase) to snake_case.
From https://codereview.stackexchange.com/questions/185966/functions-to-convert-camelcase-strings-to-snake-case
:param str camel_input: The camelcase or CamelCase string to convert to snake_case
:return str
'''
res = camel_input[0].lower()
for i, letter in enumerate(camel_input[1:], 1):
if letter.isupper():
if camel_input[i-1].islower() or (i != len(camel_input)-1 and camel_input[i+1].islower()):
res += '_'
res += letter.lower()
return res | python | def camel_to_snake_case(camel_input):
'''
Converts camelCase (or CamelCase) to snake_case.
From https://codereview.stackexchange.com/questions/185966/functions-to-convert-camelcase-strings-to-snake-case
:param str camel_input: The camelcase or CamelCase string to convert to snake_case
:return str
'''
res = camel_input[0].lower()
for i, letter in enumerate(camel_input[1:], 1):
if letter.isupper():
if camel_input[i-1].islower() or (i != len(camel_input)-1 and camel_input[i+1].islower()):
res += '_'
res += letter.lower()
return res | [
"def",
"camel_to_snake_case",
"(",
"camel_input",
")",
":",
"res",
"=",
"camel_input",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"for",
"i",
",",
"letter",
"in",
"enumerate",
"(",
"camel_input",
"[",
"1",
":",
"]",
",",
"1",
")",
":",
"if",
"letter",
... | Converts camelCase (or CamelCase) to snake_case.
From https://codereview.stackexchange.com/questions/185966/functions-to-convert-camelcase-strings-to-snake-case
:param str camel_input: The camelcase or CamelCase string to convert to snake_case
:return str | [
"Converts",
"camelCase",
"(",
"or",
"CamelCase",
")",
"to",
"snake_case",
".",
"From",
"https",
":",
"//",
"codereview",
".",
"stackexchange",
".",
"com",
"/",
"questions",
"/",
"185966",
"/",
"functions",
"-",
"to",
"-",
"convert",
"-",
"camelcase",
"-",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/stringutils.py#L594-L609 | train |
saltstack/salt | salt/utils/stringutils.py | snake_to_camel_case | def snake_to_camel_case(snake_input, uppercamel=False):
'''
Converts snake_case to camelCase (or CamelCase if uppercamel is ``True``).
Inspired by https://codereview.stackexchange.com/questions/85311/transform-snake-case-to-camelcase
:param str snake_input: The input snake_case string to convert to camelCase
:param bool uppercamel: Whether or not to convert to CamelCase instead
:return str
'''
words = snake_input.split('_')
if uppercamel:
words[0] = words[0].capitalize()
return words[0] + ''.join(word.capitalize() for word in words[1:]) | python | def snake_to_camel_case(snake_input, uppercamel=False):
'''
Converts snake_case to camelCase (or CamelCase if uppercamel is ``True``).
Inspired by https://codereview.stackexchange.com/questions/85311/transform-snake-case-to-camelcase
:param str snake_input: The input snake_case string to convert to camelCase
:param bool uppercamel: Whether or not to convert to CamelCase instead
:return str
'''
words = snake_input.split('_')
if uppercamel:
words[0] = words[0].capitalize()
return words[0] + ''.join(word.capitalize() for word in words[1:]) | [
"def",
"snake_to_camel_case",
"(",
"snake_input",
",",
"uppercamel",
"=",
"False",
")",
":",
"words",
"=",
"snake_input",
".",
"split",
"(",
"'_'",
")",
"if",
"uppercamel",
":",
"words",
"[",
"0",
"]",
"=",
"words",
"[",
"0",
"]",
".",
"capitalize",
"(... | Converts snake_case to camelCase (or CamelCase if uppercamel is ``True``).
Inspired by https://codereview.stackexchange.com/questions/85311/transform-snake-case-to-camelcase
:param str snake_input: The input snake_case string to convert to camelCase
:param bool uppercamel: Whether or not to convert to CamelCase instead
:return str | [
"Converts",
"snake_case",
"to",
"camelCase",
"(",
"or",
"CamelCase",
"if",
"uppercamel",
"is",
"True",
")",
".",
"Inspired",
"by",
"https",
":",
"//",
"codereview",
".",
"stackexchange",
".",
"com",
"/",
"questions",
"/",
"85311",
"/",
"transform",
"-",
"s... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/stringutils.py#L613-L626 | train |
saltstack/salt | salt/modules/ethtool.py | show_ring | def show_ring(devname):
'''
Queries the specified network device for rx/tx ring parameter information
CLI Example:
.. code-block:: bash
salt '*' ethtool.show_ring <devname>
'''
try:
ring = ethtool.get_ringparam(devname)
except IOError:
log.error('Ring parameters not supported on %s', devname)
return 'Not supported'
ret = {}
for key, value in ring.items():
ret[ethtool_ring_remap[key]] = ring[key]
return ret | python | def show_ring(devname):
'''
Queries the specified network device for rx/tx ring parameter information
CLI Example:
.. code-block:: bash
salt '*' ethtool.show_ring <devname>
'''
try:
ring = ethtool.get_ringparam(devname)
except IOError:
log.error('Ring parameters not supported on %s', devname)
return 'Not supported'
ret = {}
for key, value in ring.items():
ret[ethtool_ring_remap[key]] = ring[key]
return ret | [
"def",
"show_ring",
"(",
"devname",
")",
":",
"try",
":",
"ring",
"=",
"ethtool",
".",
"get_ringparam",
"(",
"devname",
")",
"except",
"IOError",
":",
"log",
".",
"error",
"(",
"'Ring parameters not supported on %s'",
",",
"devname",
")",
"return",
"'Not suppo... | Queries the specified network device for rx/tx ring parameter information
CLI Example:
.. code-block:: bash
salt '*' ethtool.show_ring <devname> | [
"Queries",
"the",
"specified",
"network",
"device",
"for",
"rx",
"/",
"tx",
"ring",
"parameter",
"information"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ethtool.py#L85-L106 | train |
saltstack/salt | salt/modules/ethtool.py | show_coalesce | def show_coalesce(devname):
'''
Queries the specified network device for coalescing information
CLI Example:
.. code-block:: bash
salt '*' ethtool.show_coalesce <devname>
'''
try:
coalesce = ethtool.get_coalesce(devname)
except IOError:
log.error('Interrupt coalescing not supported on %s', devname)
return 'Not supported'
ret = {}
for key, value in coalesce.items():
ret[ethtool_coalesce_remap[key]] = coalesce[key]
return ret | python | def show_coalesce(devname):
'''
Queries the specified network device for coalescing information
CLI Example:
.. code-block:: bash
salt '*' ethtool.show_coalesce <devname>
'''
try:
coalesce = ethtool.get_coalesce(devname)
except IOError:
log.error('Interrupt coalescing not supported on %s', devname)
return 'Not supported'
ret = {}
for key, value in coalesce.items():
ret[ethtool_coalesce_remap[key]] = coalesce[key]
return ret | [
"def",
"show_coalesce",
"(",
"devname",
")",
":",
"try",
":",
"coalesce",
"=",
"ethtool",
".",
"get_coalesce",
"(",
"devname",
")",
"except",
"IOError",
":",
"log",
".",
"error",
"(",
"'Interrupt coalescing not supported on %s'",
",",
"devname",
")",
"return",
... | Queries the specified network device for coalescing information
CLI Example:
.. code-block:: bash
salt '*' ethtool.show_coalesce <devname> | [
"Queries",
"the",
"specified",
"network",
"device",
"for",
"coalescing",
"information"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ethtool.py#L109-L130 | train |
saltstack/salt | salt/modules/ethtool.py | show_driver | def show_driver(devname):
'''
Queries the specified network device for associated driver information
CLI Example:
.. code-block:: bash
salt '*' ethtool.show_driver <devname>
'''
try:
module = ethtool.get_module(devname)
except IOError:
log.error('Driver information not implemented on %s', devname)
return 'Not implemented'
try:
businfo = ethtool.get_businfo(devname)
except IOError:
log.error('Bus information no available on %s', devname)
return 'Not available'
ret = {
'driver': module,
'bus_info': businfo,
}
return ret | python | def show_driver(devname):
'''
Queries the specified network device for associated driver information
CLI Example:
.. code-block:: bash
salt '*' ethtool.show_driver <devname>
'''
try:
module = ethtool.get_module(devname)
except IOError:
log.error('Driver information not implemented on %s', devname)
return 'Not implemented'
try:
businfo = ethtool.get_businfo(devname)
except IOError:
log.error('Bus information no available on %s', devname)
return 'Not available'
ret = {
'driver': module,
'bus_info': businfo,
}
return ret | [
"def",
"show_driver",
"(",
"devname",
")",
":",
"try",
":",
"module",
"=",
"ethtool",
".",
"get_module",
"(",
"devname",
")",
"except",
"IOError",
":",
"log",
".",
"error",
"(",
"'Driver information not implemented on %s'",
",",
"devname",
")",
"return",
"'Not... | Queries the specified network device for associated driver information
CLI Example:
.. code-block:: bash
salt '*' ethtool.show_driver <devname> | [
"Queries",
"the",
"specified",
"network",
"device",
"for",
"associated",
"driver",
"information"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ethtool.py#L133-L161 | train |
saltstack/salt | salt/modules/ethtool.py | set_ring | def set_ring(devname, **kwargs):
'''
Changes the rx/tx ring parameters of the specified network device
CLI Example:
.. code-block:: bash
salt '*' ethtool.set_ring <devname> [rx=N] [rx_mini=N] [rx_jumbo=N] [tx=N]
'''
try:
ring = ethtool.get_ringparam(devname)
except IOError:
log.error('Ring parameters not supported on %s', devname)
return 'Not supported'
changed = False
for param, value in kwargs.items():
if param in ethtool_ring_map:
param = ethtool_ring_map[param]
if param in ring:
if ring[param] != value:
ring[param] = value
changed = True
try:
if changed:
ethtool.set_ringparam(devname, ring)
return show_ring(devname)
except IOError:
log.error('Invalid ring arguments on %s: %s', devname, ring)
return 'Invalid arguments' | python | def set_ring(devname, **kwargs):
'''
Changes the rx/tx ring parameters of the specified network device
CLI Example:
.. code-block:: bash
salt '*' ethtool.set_ring <devname> [rx=N] [rx_mini=N] [rx_jumbo=N] [tx=N]
'''
try:
ring = ethtool.get_ringparam(devname)
except IOError:
log.error('Ring parameters not supported on %s', devname)
return 'Not supported'
changed = False
for param, value in kwargs.items():
if param in ethtool_ring_map:
param = ethtool_ring_map[param]
if param in ring:
if ring[param] != value:
ring[param] = value
changed = True
try:
if changed:
ethtool.set_ringparam(devname, ring)
return show_ring(devname)
except IOError:
log.error('Invalid ring arguments on %s: %s', devname, ring)
return 'Invalid arguments' | [
"def",
"set_ring",
"(",
"devname",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"ring",
"=",
"ethtool",
".",
"get_ringparam",
"(",
"devname",
")",
"except",
"IOError",
":",
"log",
".",
"error",
"(",
"'Ring parameters not supported on %s'",
",",
"devname",
... | Changes the rx/tx ring parameters of the specified network device
CLI Example:
.. code-block:: bash
salt '*' ethtool.set_ring <devname> [rx=N] [rx_mini=N] [rx_jumbo=N] [tx=N] | [
"Changes",
"the",
"rx",
"/",
"tx",
"ring",
"parameters",
"of",
"the",
"specified",
"network",
"device"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ethtool.py#L164-L196 | train |
saltstack/salt | salt/modules/ethtool.py | set_coalesce | def set_coalesce(devname, **kwargs):
'''
Changes the coalescing settings of the specified network device
CLI Example:
.. code-block:: bash
salt '*' ethtool.set_coalesce <devname> [adaptive_rx=on|off] [adaptive_tx=on|off] [rx_usecs=N] [rx_frames=N]
[rx_usecs_irq=N] [rx_frames_irq=N] [tx_usecs=N] [tx_frames=N] [tx_usecs_irq=N] [tx_frames_irq=N]
[stats_block_usecs=N] [pkt_rate_low=N] [rx_usecs_low=N] [rx_frames_low=N] [tx_usecs_low=N] [tx_frames_low=N]
[pkt_rate_high=N] [rx_usecs_high=N] [rx_frames_high=N] [tx_usecs_high=N] [tx_frames_high=N]
[sample_interval=N]
'''
try:
coalesce = ethtool.get_coalesce(devname)
except IOError:
log.error('Interrupt coalescing not supported on %s', devname)
return 'Not supported'
changed = False
for param, value in kwargs.items():
if param in ethtool_coalesce_map:
param = ethtool_coalesce_map[param]
if param in coalesce:
if coalesce[param] != value:
coalesce[param] = value
changed = True
try:
if changed:
ethtool.set_coalesce(devname, coalesce)
return show_coalesce(devname)
except IOError:
log.error('Invalid coalesce arguments on %s: %s', devname, coalesce)
return 'Invalid arguments' | python | def set_coalesce(devname, **kwargs):
'''
Changes the coalescing settings of the specified network device
CLI Example:
.. code-block:: bash
salt '*' ethtool.set_coalesce <devname> [adaptive_rx=on|off] [adaptive_tx=on|off] [rx_usecs=N] [rx_frames=N]
[rx_usecs_irq=N] [rx_frames_irq=N] [tx_usecs=N] [tx_frames=N] [tx_usecs_irq=N] [tx_frames_irq=N]
[stats_block_usecs=N] [pkt_rate_low=N] [rx_usecs_low=N] [rx_frames_low=N] [tx_usecs_low=N] [tx_frames_low=N]
[pkt_rate_high=N] [rx_usecs_high=N] [rx_frames_high=N] [tx_usecs_high=N] [tx_frames_high=N]
[sample_interval=N]
'''
try:
coalesce = ethtool.get_coalesce(devname)
except IOError:
log.error('Interrupt coalescing not supported on %s', devname)
return 'Not supported'
changed = False
for param, value in kwargs.items():
if param in ethtool_coalesce_map:
param = ethtool_coalesce_map[param]
if param in coalesce:
if coalesce[param] != value:
coalesce[param] = value
changed = True
try:
if changed:
ethtool.set_coalesce(devname, coalesce)
return show_coalesce(devname)
except IOError:
log.error('Invalid coalesce arguments on %s: %s', devname, coalesce)
return 'Invalid arguments' | [
"def",
"set_coalesce",
"(",
"devname",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"coalesce",
"=",
"ethtool",
".",
"get_coalesce",
"(",
"devname",
")",
"except",
"IOError",
":",
"log",
".",
"error",
"(",
"'Interrupt coalescing not supported on %s'",
",",
... | Changes the coalescing settings of the specified network device
CLI Example:
.. code-block:: bash
salt '*' ethtool.set_coalesce <devname> [adaptive_rx=on|off] [adaptive_tx=on|off] [rx_usecs=N] [rx_frames=N]
[rx_usecs_irq=N] [rx_frames_irq=N] [tx_usecs=N] [tx_frames=N] [tx_usecs_irq=N] [tx_frames_irq=N]
[stats_block_usecs=N] [pkt_rate_low=N] [rx_usecs_low=N] [rx_frames_low=N] [tx_usecs_low=N] [tx_frames_low=N]
[pkt_rate_high=N] [rx_usecs_high=N] [rx_frames_high=N] [tx_usecs_high=N] [tx_frames_high=N]
[sample_interval=N] | [
"Changes",
"the",
"coalescing",
"settings",
"of",
"the",
"specified",
"network",
"device"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ethtool.py#L199-L235 | train |
saltstack/salt | salt/modules/ethtool.py | show_offload | def show_offload(devname):
'''
Queries the specified network device for the state of protocol offload and other features
CLI Example:
.. code-block:: bash
salt '*' ethtool.show_offload <devname>
'''
try:
sg = ethtool.get_sg(devname) and "on" or "off"
except IOError:
sg = "not supported"
try:
tso = ethtool.get_tso(devname) and "on" or "off"
except IOError:
tso = "not supported"
try:
ufo = ethtool.get_ufo(devname) and "on" or "off"
except IOError:
ufo = "not supported"
try:
gso = ethtool.get_gso(devname) and "on" or "off"
except IOError:
gso = "not supported"
offload = {
'scatter_gather': sg,
'tcp_segmentation_offload': tso,
'udp_fragmentation_offload': ufo,
'generic_segmentation_offload': gso,
}
return offload | python | def show_offload(devname):
'''
Queries the specified network device for the state of protocol offload and other features
CLI Example:
.. code-block:: bash
salt '*' ethtool.show_offload <devname>
'''
try:
sg = ethtool.get_sg(devname) and "on" or "off"
except IOError:
sg = "not supported"
try:
tso = ethtool.get_tso(devname) and "on" or "off"
except IOError:
tso = "not supported"
try:
ufo = ethtool.get_ufo(devname) and "on" or "off"
except IOError:
ufo = "not supported"
try:
gso = ethtool.get_gso(devname) and "on" or "off"
except IOError:
gso = "not supported"
offload = {
'scatter_gather': sg,
'tcp_segmentation_offload': tso,
'udp_fragmentation_offload': ufo,
'generic_segmentation_offload': gso,
}
return offload | [
"def",
"show_offload",
"(",
"devname",
")",
":",
"try",
":",
"sg",
"=",
"ethtool",
".",
"get_sg",
"(",
"devname",
")",
"and",
"\"on\"",
"or",
"\"off\"",
"except",
"IOError",
":",
"sg",
"=",
"\"not supported\"",
"try",
":",
"tso",
"=",
"ethtool",
".",
"... | Queries the specified network device for the state of protocol offload and other features
CLI Example:
.. code-block:: bash
salt '*' ethtool.show_offload <devname> | [
"Queries",
"the",
"specified",
"network",
"device",
"for",
"the",
"state",
"of",
"protocol",
"offload",
"and",
"other",
"features"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ethtool.py#L238-L276 | train |
saltstack/salt | salt/modules/ethtool.py | set_offload | def set_offload(devname, **kwargs):
'''
Changes the offload parameters and other features of the specified network device
CLI Example:
.. code-block:: bash
salt '*' ethtool.set_offload <devname> tcp_segmentation_offload=on
'''
for param, value in kwargs.items():
if param == 'tcp_segmentation_offload':
value = value == "on" and 1 or 0
try:
ethtool.set_tso(devname, value)
except IOError:
return 'Not supported'
return show_offload(devname) | python | def set_offload(devname, **kwargs):
'''
Changes the offload parameters and other features of the specified network device
CLI Example:
.. code-block:: bash
salt '*' ethtool.set_offload <devname> tcp_segmentation_offload=on
'''
for param, value in kwargs.items():
if param == 'tcp_segmentation_offload':
value = value == "on" and 1 or 0
try:
ethtool.set_tso(devname, value)
except IOError:
return 'Not supported'
return show_offload(devname) | [
"def",
"set_offload",
"(",
"devname",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"param",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"param",
"==",
"'tcp_segmentation_offload'",
":",
"value",
"=",
"value",
"==",
"\"on\"",
"and",
"1... | Changes the offload parameters and other features of the specified network device
CLI Example:
.. code-block:: bash
salt '*' ethtool.set_offload <devname> tcp_segmentation_offload=on | [
"Changes",
"the",
"offload",
"parameters",
"and",
"other",
"features",
"of",
"the",
"specified",
"network",
"device"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ethtool.py#L279-L298 | train |
saltstack/salt | salt/modules/tls.py | _microtime | def _microtime():
'''
Return a Unix timestamp as a string of digits
:return:
'''
val1, val2 = math.modf(time.time())
val2 = int(val2)
return '{0:f}{1}'.format(val1, val2) | python | def _microtime():
'''
Return a Unix timestamp as a string of digits
:return:
'''
val1, val2 = math.modf(time.time())
val2 = int(val2)
return '{0:f}{1}'.format(val1, val2) | [
"def",
"_microtime",
"(",
")",
":",
"val1",
",",
"val2",
"=",
"math",
".",
"modf",
"(",
"time",
".",
"time",
"(",
")",
")",
"val2",
"=",
"int",
"(",
"val2",
")",
"return",
"'{0:f}{1}'",
".",
"format",
"(",
"val1",
",",
"val2",
")"
] | Return a Unix timestamp as a string of digits
:return: | [
"Return",
"a",
"Unix",
"timestamp",
"as",
"a",
"string",
"of",
"digits",
":",
"return",
":"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tls.py#L164-L171 | train |
saltstack/salt | salt/modules/tls.py | cert_base_path | def cert_base_path(cacert_path=None):
'''
Return the base path for certs from CLI or from options
cacert_path
absolute path to ca certificates root directory
CLI Example:
.. code-block:: bash
salt '*' tls.cert_base_path
'''
if not cacert_path:
cacert_path = __context__.get(
'ca.contextual_cert_base_path',
__salt__['config.option']('ca.contextual_cert_base_path'))
if not cacert_path:
cacert_path = __context__.get(
'ca.cert_base_path',
__salt__['config.option']('ca.cert_base_path'))
return cacert_path | python | def cert_base_path(cacert_path=None):
'''
Return the base path for certs from CLI or from options
cacert_path
absolute path to ca certificates root directory
CLI Example:
.. code-block:: bash
salt '*' tls.cert_base_path
'''
if not cacert_path:
cacert_path = __context__.get(
'ca.contextual_cert_base_path',
__salt__['config.option']('ca.contextual_cert_base_path'))
if not cacert_path:
cacert_path = __context__.get(
'ca.cert_base_path',
__salt__['config.option']('ca.cert_base_path'))
return cacert_path | [
"def",
"cert_base_path",
"(",
"cacert_path",
"=",
"None",
")",
":",
"if",
"not",
"cacert_path",
":",
"cacert_path",
"=",
"__context__",
".",
"get",
"(",
"'ca.contextual_cert_base_path'",
",",
"__salt__",
"[",
"'config.option'",
"]",
"(",
"'ca.contextual_cert_base_pa... | Return the base path for certs from CLI or from options
cacert_path
absolute path to ca certificates root directory
CLI Example:
.. code-block:: bash
salt '*' tls.cert_base_path | [
"Return",
"the",
"base",
"path",
"for",
"certs",
"from",
"CLI",
"or",
"from",
"options"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tls.py#L174-L195 | train |
saltstack/salt | salt/modules/tls.py | _new_serial | def _new_serial(ca_name):
'''
Return a serial number in hex using os.urandom() and a Unix timestamp
in microseconds.
ca_name
name of the CA
CN
common name in the request
'''
hashnum = int(
binascii.hexlify(
b'_'.join((
salt.utils.stringutils.to_bytes(_microtime()),
os.urandom(5) if six.PY3 else os.urandom(5).encode('hex')
))
),
16
)
log.debug('Hashnum: %s', hashnum)
# record the hash somewhere
cachedir = __opts__['cachedir']
log.debug('cachedir: %s', cachedir)
serial_file = '{0}/{1}.serial'.format(cachedir, ca_name)
if not os.path.exists(cachedir):
os.makedirs(cachedir)
if not os.path.exists(serial_file):
mode = 'w'
else:
mode = 'a+'
with salt.utils.files.fopen(serial_file, mode) as ofile:
ofile.write(str(hashnum)) # future lint: disable=blacklisted-function
return hashnum | python | def _new_serial(ca_name):
'''
Return a serial number in hex using os.urandom() and a Unix timestamp
in microseconds.
ca_name
name of the CA
CN
common name in the request
'''
hashnum = int(
binascii.hexlify(
b'_'.join((
salt.utils.stringutils.to_bytes(_microtime()),
os.urandom(5) if six.PY3 else os.urandom(5).encode('hex')
))
),
16
)
log.debug('Hashnum: %s', hashnum)
# record the hash somewhere
cachedir = __opts__['cachedir']
log.debug('cachedir: %s', cachedir)
serial_file = '{0}/{1}.serial'.format(cachedir, ca_name)
if not os.path.exists(cachedir):
os.makedirs(cachedir)
if not os.path.exists(serial_file):
mode = 'w'
else:
mode = 'a+'
with salt.utils.files.fopen(serial_file, mode) as ofile:
ofile.write(str(hashnum)) # future lint: disable=blacklisted-function
return hashnum | [
"def",
"_new_serial",
"(",
"ca_name",
")",
":",
"hashnum",
"=",
"int",
"(",
"binascii",
".",
"hexlify",
"(",
"b'_'",
".",
"join",
"(",
"(",
"salt",
".",
"utils",
".",
"stringutils",
".",
"to_bytes",
"(",
"_microtime",
"(",
")",
")",
",",
"os",
".",
... | Return a serial number in hex using os.urandom() and a Unix timestamp
in microseconds.
ca_name
name of the CA
CN
common name in the request | [
"Return",
"a",
"serial",
"number",
"in",
"hex",
"using",
"os",
".",
"urandom",
"()",
"and",
"a",
"Unix",
"timestamp",
"in",
"microseconds",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tls.py#L221-L255 | train |
saltstack/salt | salt/modules/tls.py | _get_basic_info | def _get_basic_info(ca_name, cert, ca_dir=None):
'''
Get basic info to write out to the index.txt
'''
if ca_dir is None:
ca_dir = '{0}/{1}'.format(_cert_base_path(), ca_name)
index_file = "{0}/index.txt".format(ca_dir)
cert = _read_cert(cert)
expire_date = _four_digit_year_to_two_digit(_get_expiration_date(cert))
serial_number = format(cert.get_serial_number(), 'X')
# gotta prepend a /
subject = '/'
# then we can add the rest of the subject
subject += '/'.join(
['{0}={1}'.format(
x, y
) for x, y in cert.get_subject().get_components()]
)
subject += '\n'
return (index_file, expire_date, serial_number, subject) | python | def _get_basic_info(ca_name, cert, ca_dir=None):
'''
Get basic info to write out to the index.txt
'''
if ca_dir is None:
ca_dir = '{0}/{1}'.format(_cert_base_path(), ca_name)
index_file = "{0}/index.txt".format(ca_dir)
cert = _read_cert(cert)
expire_date = _four_digit_year_to_two_digit(_get_expiration_date(cert))
serial_number = format(cert.get_serial_number(), 'X')
# gotta prepend a /
subject = '/'
# then we can add the rest of the subject
subject += '/'.join(
['{0}={1}'.format(
x, y
) for x, y in cert.get_subject().get_components()]
)
subject += '\n'
return (index_file, expire_date, serial_number, subject) | [
"def",
"_get_basic_info",
"(",
"ca_name",
",",
"cert",
",",
"ca_dir",
"=",
"None",
")",
":",
"if",
"ca_dir",
"is",
"None",
":",
"ca_dir",
"=",
"'{0}/{1}'",
".",
"format",
"(",
"_cert_base_path",
"(",
")",
",",
"ca_name",
")",
"index_file",
"=",
"\"{0}/in... | Get basic info to write out to the index.txt | [
"Get",
"basic",
"info",
"to",
"write",
"out",
"to",
"the",
"index",
".",
"txt"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tls.py#L262-L286 | train |
saltstack/salt | salt/modules/tls.py | _write_cert_to_database | def _write_cert_to_database(ca_name, cert, cacert_path=None, status='V'):
'''
write out the index.txt database file in the appropriate directory to
track certificates
ca_name
name of the CA
cert
certificate to be recorded
'''
set_ca_path(cacert_path)
ca_dir = '{0}/{1}'.format(cert_base_path(), ca_name)
index_file, expire_date, serial_number, subject = _get_basic_info(
ca_name,
cert,
ca_dir)
index_data = '{0}\t{1}\t\t{2}\tunknown\t{3}'.format(
status,
expire_date,
serial_number,
subject
)
with salt.utils.files.fopen(index_file, 'a+') as ofile:
ofile.write(salt.utils.stringutils.to_str(index_data)) | python | def _write_cert_to_database(ca_name, cert, cacert_path=None, status='V'):
'''
write out the index.txt database file in the appropriate directory to
track certificates
ca_name
name of the CA
cert
certificate to be recorded
'''
set_ca_path(cacert_path)
ca_dir = '{0}/{1}'.format(cert_base_path(), ca_name)
index_file, expire_date, serial_number, subject = _get_basic_info(
ca_name,
cert,
ca_dir)
index_data = '{0}\t{1}\t\t{2}\tunknown\t{3}'.format(
status,
expire_date,
serial_number,
subject
)
with salt.utils.files.fopen(index_file, 'a+') as ofile:
ofile.write(salt.utils.stringutils.to_str(index_data)) | [
"def",
"_write_cert_to_database",
"(",
"ca_name",
",",
"cert",
",",
"cacert_path",
"=",
"None",
",",
"status",
"=",
"'V'",
")",
":",
"set_ca_path",
"(",
"cacert_path",
")",
"ca_dir",
"=",
"'{0}/{1}'",
".",
"format",
"(",
"cert_base_path",
"(",
")",
",",
"c... | write out the index.txt database file in the appropriate directory to
track certificates
ca_name
name of the CA
cert
certificate to be recorded | [
"write",
"out",
"the",
"index",
".",
"txt",
"database",
"file",
"in",
"the",
"appropriate",
"directory",
"to",
"track",
"certificates"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tls.py#L289-L314 | train |
saltstack/salt | salt/modules/tls.py | maybe_fix_ssl_version | def maybe_fix_ssl_version(ca_name, cacert_path=None, ca_filename=None):
'''
Check that the X509 version is correct
(was incorrectly set in previous salt versions).
This will fix the version if needed.
ca_name
ca authority name
cacert_path
absolute path to ca certificates root directory
ca_filename
alternative filename for the CA
.. versionadded:: 2015.5.3
CLI Example:
.. code-block:: bash
salt '*' tls.maybe_fix_ssl_version test_ca /etc/certs
'''
set_ca_path(cacert_path)
if not ca_filename:
ca_filename = '{0}_ca_cert'.format(ca_name)
certp = '{0}/{1}/{2}.crt'.format(
cert_base_path(),
ca_name,
ca_filename)
ca_keyp = '{0}/{1}/{2}.key'.format(
cert_base_path(),
ca_name,
ca_filename)
with salt.utils.files.fopen(certp) as fic:
cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
fic.read())
if cert.get_version() == 3:
log.info('Regenerating wrong x509 version '
'for certificate %s', certp)
with salt.utils.files.fopen(ca_keyp) as fic2:
try:
# try to determine the key bits
key = OpenSSL.crypto.load_privatekey(
OpenSSL.crypto.FILETYPE_PEM, fic2.read())
bits = key.bits()
except Exception:
bits = 2048
try:
days = (datetime.strptime(
cert.get_notAfter(),
'%Y%m%d%H%M%SZ') - datetime.utcnow()).days
except (ValueError, TypeError):
days = 365
subj = cert.get_subject()
create_ca(
ca_name,
bits=bits,
days=days,
CN=subj.CN,
C=subj.C,
ST=subj.ST,
L=subj.L,
O=subj.O,
OU=subj.OU,
emailAddress=subj.emailAddress,
fixmode=True) | python | def maybe_fix_ssl_version(ca_name, cacert_path=None, ca_filename=None):
'''
Check that the X509 version is correct
(was incorrectly set in previous salt versions).
This will fix the version if needed.
ca_name
ca authority name
cacert_path
absolute path to ca certificates root directory
ca_filename
alternative filename for the CA
.. versionadded:: 2015.5.3
CLI Example:
.. code-block:: bash
salt '*' tls.maybe_fix_ssl_version test_ca /etc/certs
'''
set_ca_path(cacert_path)
if not ca_filename:
ca_filename = '{0}_ca_cert'.format(ca_name)
certp = '{0}/{1}/{2}.crt'.format(
cert_base_path(),
ca_name,
ca_filename)
ca_keyp = '{0}/{1}/{2}.key'.format(
cert_base_path(),
ca_name,
ca_filename)
with salt.utils.files.fopen(certp) as fic:
cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
fic.read())
if cert.get_version() == 3:
log.info('Regenerating wrong x509 version '
'for certificate %s', certp)
with salt.utils.files.fopen(ca_keyp) as fic2:
try:
# try to determine the key bits
key = OpenSSL.crypto.load_privatekey(
OpenSSL.crypto.FILETYPE_PEM, fic2.read())
bits = key.bits()
except Exception:
bits = 2048
try:
days = (datetime.strptime(
cert.get_notAfter(),
'%Y%m%d%H%M%SZ') - datetime.utcnow()).days
except (ValueError, TypeError):
days = 365
subj = cert.get_subject()
create_ca(
ca_name,
bits=bits,
days=days,
CN=subj.CN,
C=subj.C,
ST=subj.ST,
L=subj.L,
O=subj.O,
OU=subj.OU,
emailAddress=subj.emailAddress,
fixmode=True) | [
"def",
"maybe_fix_ssl_version",
"(",
"ca_name",
",",
"cacert_path",
"=",
"None",
",",
"ca_filename",
"=",
"None",
")",
":",
"set_ca_path",
"(",
"cacert_path",
")",
"if",
"not",
"ca_filename",
":",
"ca_filename",
"=",
"'{0}_ca_cert'",
".",
"format",
"(",
"ca_na... | Check that the X509 version is correct
(was incorrectly set in previous salt versions).
This will fix the version if needed.
ca_name
ca authority name
cacert_path
absolute path to ca certificates root directory
ca_filename
alternative filename for the CA
.. versionadded:: 2015.5.3
CLI Example:
.. code-block:: bash
salt '*' tls.maybe_fix_ssl_version test_ca /etc/certs | [
"Check",
"that",
"the",
"X509",
"version",
"is",
"correct",
"(",
"was",
"incorrectly",
"set",
"in",
"previous",
"salt",
"versions",
")",
".",
"This",
"will",
"fix",
"the",
"version",
"if",
"needed",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tls.py#L317-L382 | train |
saltstack/salt | salt/modules/tls.py | ca_exists | def ca_exists(ca_name, cacert_path=None, ca_filename=None):
'''
Verify whether a Certificate Authority (CA) already exists
ca_name
name of the CA
cacert_path
absolute path to ca certificates root directory
ca_filename
alternative filename for the CA
.. versionadded:: 2015.5.3
CLI Example:
.. code-block:: bash
salt '*' tls.ca_exists test_ca /etc/certs
'''
set_ca_path(cacert_path)
if not ca_filename:
ca_filename = '{0}_ca_cert'.format(ca_name)
certp = '{0}/{1}/{2}.crt'.format(
cert_base_path(),
ca_name,
ca_filename)
if os.path.exists(certp):
maybe_fix_ssl_version(ca_name,
cacert_path=cacert_path,
ca_filename=ca_filename)
return True
return False | python | def ca_exists(ca_name, cacert_path=None, ca_filename=None):
'''
Verify whether a Certificate Authority (CA) already exists
ca_name
name of the CA
cacert_path
absolute path to ca certificates root directory
ca_filename
alternative filename for the CA
.. versionadded:: 2015.5.3
CLI Example:
.. code-block:: bash
salt '*' tls.ca_exists test_ca /etc/certs
'''
set_ca_path(cacert_path)
if not ca_filename:
ca_filename = '{0}_ca_cert'.format(ca_name)
certp = '{0}/{1}/{2}.crt'.format(
cert_base_path(),
ca_name,
ca_filename)
if os.path.exists(certp):
maybe_fix_ssl_version(ca_name,
cacert_path=cacert_path,
ca_filename=ca_filename)
return True
return False | [
"def",
"ca_exists",
"(",
"ca_name",
",",
"cacert_path",
"=",
"None",
",",
"ca_filename",
"=",
"None",
")",
":",
"set_ca_path",
"(",
"cacert_path",
")",
"if",
"not",
"ca_filename",
":",
"ca_filename",
"=",
"'{0}_ca_cert'",
".",
"format",
"(",
"ca_name",
")",
... | Verify whether a Certificate Authority (CA) already exists
ca_name
name of the CA
cacert_path
absolute path to ca certificates root directory
ca_filename
alternative filename for the CA
.. versionadded:: 2015.5.3
CLI Example:
.. code-block:: bash
salt '*' tls.ca_exists test_ca /etc/certs | [
"Verify",
"whether",
"a",
"Certificate",
"Authority",
"(",
"CA",
")",
"already",
"exists"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tls.py#L385-L417 | train |
saltstack/salt | salt/modules/tls.py | get_ca | def get_ca(ca_name, as_text=False, cacert_path=None):
'''
Get the certificate path or content
ca_name
name of the CA
as_text
if true, return the certificate content instead of the path
cacert_path
absolute path to ca certificates root directory
CLI Example:
.. code-block:: bash
salt '*' tls.get_ca test_ca as_text=False cacert_path=/etc/certs
'''
set_ca_path(cacert_path)
certp = '{0}/{1}/{1}_ca_cert.crt'.format(cert_base_path(), ca_name)
if not os.path.exists(certp):
raise ValueError('Certificate does not exist for {0}'.format(ca_name))
else:
if as_text:
with salt.utils.files.fopen(certp) as fic:
certp = salt.utils.stringutils.to_unicode(fic.read())
return certp | python | def get_ca(ca_name, as_text=False, cacert_path=None):
'''
Get the certificate path or content
ca_name
name of the CA
as_text
if true, return the certificate content instead of the path
cacert_path
absolute path to ca certificates root directory
CLI Example:
.. code-block:: bash
salt '*' tls.get_ca test_ca as_text=False cacert_path=/etc/certs
'''
set_ca_path(cacert_path)
certp = '{0}/{1}/{1}_ca_cert.crt'.format(cert_base_path(), ca_name)
if not os.path.exists(certp):
raise ValueError('Certificate does not exist for {0}'.format(ca_name))
else:
if as_text:
with salt.utils.files.fopen(certp) as fic:
certp = salt.utils.stringutils.to_unicode(fic.read())
return certp | [
"def",
"get_ca",
"(",
"ca_name",
",",
"as_text",
"=",
"False",
",",
"cacert_path",
"=",
"None",
")",
":",
"set_ca_path",
"(",
"cacert_path",
")",
"certp",
"=",
"'{0}/{1}/{1}_ca_cert.crt'",
".",
"format",
"(",
"cert_base_path",
"(",
")",
",",
"ca_name",
")",
... | Get the certificate path or content
ca_name
name of the CA
as_text
if true, return the certificate content instead of the path
cacert_path
absolute path to ca certificates root directory
CLI Example:
.. code-block:: bash
salt '*' tls.get_ca test_ca as_text=False cacert_path=/etc/certs | [
"Get",
"the",
"certificate",
"path",
"or",
"content"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tls.py#L425-L450 | train |
saltstack/salt | salt/modules/tls.py | get_ca_signed_key | def get_ca_signed_key(ca_name,
CN='localhost',
as_text=False,
cacert_path=None,
key_filename=None):
'''
Get the certificate path or content
ca_name
name of the CA
CN
common name of the certificate
as_text
if true, return the certificate content instead of the path
cacert_path
absolute path to certificates root directory
key_filename
alternative filename for the key, useful when using special characters
.. versionadded:: 2015.5.3
in the CN
CLI Example:
.. code-block:: bash
salt '*' tls.get_ca_signed_key \
test_ca CN=localhost \
as_text=False \
cacert_path=/etc/certs
'''
set_ca_path(cacert_path)
if not key_filename:
key_filename = CN
keyp = '{0}/{1}/certs/{2}.key'.format(
cert_base_path(),
ca_name,
key_filename)
if not os.path.exists(keyp):
raise ValueError('Certificate does not exists for {0}'.format(CN))
else:
if as_text:
with salt.utils.files.fopen(keyp) as fic:
keyp = salt.utils.stringutils.to_unicode(fic.read())
return keyp | python | def get_ca_signed_key(ca_name,
CN='localhost',
as_text=False,
cacert_path=None,
key_filename=None):
'''
Get the certificate path or content
ca_name
name of the CA
CN
common name of the certificate
as_text
if true, return the certificate content instead of the path
cacert_path
absolute path to certificates root directory
key_filename
alternative filename for the key, useful when using special characters
.. versionadded:: 2015.5.3
in the CN
CLI Example:
.. code-block:: bash
salt '*' tls.get_ca_signed_key \
test_ca CN=localhost \
as_text=False \
cacert_path=/etc/certs
'''
set_ca_path(cacert_path)
if not key_filename:
key_filename = CN
keyp = '{0}/{1}/certs/{2}.key'.format(
cert_base_path(),
ca_name,
key_filename)
if not os.path.exists(keyp):
raise ValueError('Certificate does not exists for {0}'.format(CN))
else:
if as_text:
with salt.utils.files.fopen(keyp) as fic:
keyp = salt.utils.stringutils.to_unicode(fic.read())
return keyp | [
"def",
"get_ca_signed_key",
"(",
"ca_name",
",",
"CN",
"=",
"'localhost'",
",",
"as_text",
"=",
"False",
",",
"cacert_path",
"=",
"None",
",",
"key_filename",
"=",
"None",
")",
":",
"set_ca_path",
"(",
"cacert_path",
")",
"if",
"not",
"key_filename",
":",
... | Get the certificate path or content
ca_name
name of the CA
CN
common name of the certificate
as_text
if true, return the certificate content instead of the path
cacert_path
absolute path to certificates root directory
key_filename
alternative filename for the key, useful when using special characters
.. versionadded:: 2015.5.3
in the CN
CLI Example:
.. code-block:: bash
salt '*' tls.get_ca_signed_key \
test_ca CN=localhost \
as_text=False \
cacert_path=/etc/certs | [
"Get",
"the",
"certificate",
"path",
"or",
"content"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tls.py#L498-L544 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.