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/modules/smartos_vmadm.py
stop
def stop(vm, force=False, key='uuid'): ''' Stop a vm vm : string vm to be stopped force : boolean force stop of vm if true key : string [uuid|alias|hostname] value type of 'vm' parameter CLI Example: .. code-block:: bash salt '*' vmadm.stop 186da9ab-7392-4f55-91a5-b8f1fe770543 salt '*' vmadm.stop 186da9ab-7392-4f55-91a5-b8f1fe770543 True salt '*' vmadm.stop vm=nacl key=alias salt '*' vmadm.stop vm=nina.example.org key=hostname ''' ret = {} if key not in ['uuid', 'alias', 'hostname']: ret['Error'] = 'Key must be either uuid, alias or hostname' return ret vm = lookup('{0}={1}'.format(key, vm), one=True) if 'Error' in vm: return vm # vmadm stop <uuid> [-F] cmd = 'vmadm stop {force} {uuid}'.format( force='-F' if force else '', uuid=vm ) res = __salt__['cmd.run_all'](cmd) retcode = res['retcode'] if retcode != 0: ret['Error'] = _exit_status(retcode) return ret return True
python
def stop(vm, force=False, key='uuid'): ''' Stop a vm vm : string vm to be stopped force : boolean force stop of vm if true key : string [uuid|alias|hostname] value type of 'vm' parameter CLI Example: .. code-block:: bash salt '*' vmadm.stop 186da9ab-7392-4f55-91a5-b8f1fe770543 salt '*' vmadm.stop 186da9ab-7392-4f55-91a5-b8f1fe770543 True salt '*' vmadm.stop vm=nacl key=alias salt '*' vmadm.stop vm=nina.example.org key=hostname ''' ret = {} if key not in ['uuid', 'alias', 'hostname']: ret['Error'] = 'Key must be either uuid, alias or hostname' return ret vm = lookup('{0}={1}'.format(key, vm), one=True) if 'Error' in vm: return vm # vmadm stop <uuid> [-F] cmd = 'vmadm stop {force} {uuid}'.format( force='-F' if force else '', uuid=vm ) res = __salt__['cmd.run_all'](cmd) retcode = res['retcode'] if retcode != 0: ret['Error'] = _exit_status(retcode) return ret return True
[ "def", "stop", "(", "vm", ",", "force", "=", "False", ",", "key", "=", "'uuid'", ")", ":", "ret", "=", "{", "}", "if", "key", "not", "in", "[", "'uuid'", ",", "'alias'", ",", "'hostname'", "]", ":", "ret", "[", "'Error'", "]", "=", "'Key must be ...
Stop a vm vm : string vm to be stopped force : boolean force stop of vm if true key : string [uuid|alias|hostname] value type of 'vm' parameter CLI Example: .. code-block:: bash salt '*' vmadm.stop 186da9ab-7392-4f55-91a5-b8f1fe770543 salt '*' vmadm.stop 186da9ab-7392-4f55-91a5-b8f1fe770543 True salt '*' vmadm.stop vm=nacl key=alias salt '*' vmadm.stop vm=nina.example.org key=hostname
[ "Stop", "a", "vm" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smartos_vmadm.py#L204-L241
train
saltstack/salt
salt/modules/smartos_vmadm.py
list_vms
def list_vms(search=None, sort=None, order='uuid,type,ram,state,alias', keyed=True): ''' Return a list of VMs search : string vmadm filter property sort : string vmadm sort (-s) property order : string vmadm order (-o) property -- Default: uuid,type,ram,state,alias keyed : boolean specified if the output should be an array (False) or dict (True) For a dict the key is the first item from the order parameter. Note: If key is not unique last vm wins. CLI Example: .. code-block:: bash salt '*' vmadm.list salt '*' vmadm.list order=alias,ram,cpu_cap sort=-ram,-cpu_cap salt '*' vmadm.list search='type=KVM' ''' ret = {} # vmadm list [-p] [-H] [-o field,...] [-s field,...] [field=value ...] cmd = 'vmadm list -p -H {order} {sort} {search}'.format( order='-o {0}'.format(order) if order else '', sort='-s {0}'.format(sort) if sort else '', search=search if search else '' ) res = __salt__['cmd.run_all'](cmd) retcode = res['retcode'] result = OrderedDict() if keyed else [] if retcode != 0: ret['Error'] = res['stderr'] if 'stderr' in res else _exit_status(retcode) return ret fields = order.split(',') for vm in res['stdout'].splitlines(): vm_data = OrderedDict() vm = vm.split(':') if keyed: for field in fields: if fields.index(field) == 0: continue vm_data[field.strip()] = vm[fields.index(field)].strip() result[vm[0]] = vm_data else: if len(vm) > 1: for field in fields: vm_data[field.strip()] = vm[fields.index(field)].strip() else: vm_data = vm[0] result.append(vm_data) return result
python
def list_vms(search=None, sort=None, order='uuid,type,ram,state,alias', keyed=True): ''' Return a list of VMs search : string vmadm filter property sort : string vmadm sort (-s) property order : string vmadm order (-o) property -- Default: uuid,type,ram,state,alias keyed : boolean specified if the output should be an array (False) or dict (True) For a dict the key is the first item from the order parameter. Note: If key is not unique last vm wins. CLI Example: .. code-block:: bash salt '*' vmadm.list salt '*' vmadm.list order=alias,ram,cpu_cap sort=-ram,-cpu_cap salt '*' vmadm.list search='type=KVM' ''' ret = {} # vmadm list [-p] [-H] [-o field,...] [-s field,...] [field=value ...] cmd = 'vmadm list -p -H {order} {sort} {search}'.format( order='-o {0}'.format(order) if order else '', sort='-s {0}'.format(sort) if sort else '', search=search if search else '' ) res = __salt__['cmd.run_all'](cmd) retcode = res['retcode'] result = OrderedDict() if keyed else [] if retcode != 0: ret['Error'] = res['stderr'] if 'stderr' in res else _exit_status(retcode) return ret fields = order.split(',') for vm in res['stdout'].splitlines(): vm_data = OrderedDict() vm = vm.split(':') if keyed: for field in fields: if fields.index(field) == 0: continue vm_data[field.strip()] = vm[fields.index(field)].strip() result[vm[0]] = vm_data else: if len(vm) > 1: for field in fields: vm_data[field.strip()] = vm[fields.index(field)].strip() else: vm_data = vm[0] result.append(vm_data) return result
[ "def", "list_vms", "(", "search", "=", "None", ",", "sort", "=", "None", ",", "order", "=", "'uuid,type,ram,state,alias'", ",", "keyed", "=", "True", ")", ":", "ret", "=", "{", "}", "# vmadm list [-p] [-H] [-o field,...] [-s field,...] [field=value ...]", "cmd", "...
Return a list of VMs search : string vmadm filter property sort : string vmadm sort (-s) property order : string vmadm order (-o) property -- Default: uuid,type,ram,state,alias keyed : boolean specified if the output should be an array (False) or dict (True) For a dict the key is the first item from the order parameter. Note: If key is not unique last vm wins. CLI Example: .. code-block:: bash salt '*' vmadm.list salt '*' vmadm.list order=alias,ram,cpu_cap sort=-ram,-cpu_cap salt '*' vmadm.list search='type=KVM'
[ "Return", "a", "list", "of", "VMs" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smartos_vmadm.py#L284-L339
train
saltstack/salt
salt/modules/smartos_vmadm.py
lookup
def lookup(search=None, order=None, one=False): ''' Return a list of VMs using lookup search : string vmadm filter property order : string vmadm order (-o) property -- Default: uuid,type,ram,state,alias one : boolean return only one result (vmadm's -1) CLI Example: .. code-block:: bash salt '*' vmadm.lookup search='state=running' salt '*' vmadm.lookup search='state=running' order=uuid,alias,hostname salt '*' vmadm.lookup search='alias=nacl' one=True ''' ret = {} # vmadm lookup [-j|-1] [-o field,...] [field=value ...] cmd = 'vmadm lookup {one} {order} {search}'.format( one='-1' if one else '-j', order='-o {0}'.format(order) if order else '', search=search if search else '' ) res = __salt__['cmd.run_all'](cmd) retcode = res['retcode'] result = [] if retcode != 0: ret['Error'] = res['stderr'] if 'stderr' in res else _exit_status(retcode) return ret if one: result = res['stdout'] else: for vm in salt.utils.json.loads(res['stdout']): result.append(vm) return result
python
def lookup(search=None, order=None, one=False): ''' Return a list of VMs using lookup search : string vmadm filter property order : string vmadm order (-o) property -- Default: uuid,type,ram,state,alias one : boolean return only one result (vmadm's -1) CLI Example: .. code-block:: bash salt '*' vmadm.lookup search='state=running' salt '*' vmadm.lookup search='state=running' order=uuid,alias,hostname salt '*' vmadm.lookup search='alias=nacl' one=True ''' ret = {} # vmadm lookup [-j|-1] [-o field,...] [field=value ...] cmd = 'vmadm lookup {one} {order} {search}'.format( one='-1' if one else '-j', order='-o {0}'.format(order) if order else '', search=search if search else '' ) res = __salt__['cmd.run_all'](cmd) retcode = res['retcode'] result = [] if retcode != 0: ret['Error'] = res['stderr'] if 'stderr' in res else _exit_status(retcode) return ret if one: result = res['stdout'] else: for vm in salt.utils.json.loads(res['stdout']): result.append(vm) return result
[ "def", "lookup", "(", "search", "=", "None", ",", "order", "=", "None", ",", "one", "=", "False", ")", ":", "ret", "=", "{", "}", "# vmadm lookup [-j|-1] [-o field,...] [field=value ...]", "cmd", "=", "'vmadm lookup {one} {order} {search}'", ".", "format", "(", ...
Return a list of VMs using lookup search : string vmadm filter property order : string vmadm order (-o) property -- Default: uuid,type,ram,state,alias one : boolean return only one result (vmadm's -1) CLI Example: .. code-block:: bash salt '*' vmadm.lookup search='state=running' salt '*' vmadm.lookup search='state=running' order=uuid,alias,hostname salt '*' vmadm.lookup search='alias=nacl' one=True
[ "Return", "a", "list", "of", "VMs", "using", "lookup" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smartos_vmadm.py#L342-L381
train
saltstack/salt
salt/modules/smartos_vmadm.py
sysrq
def sysrq(vm, action='nmi', key='uuid'): ''' Send non-maskable interrupt to vm or capture a screenshot vm : string vm to be targeted action : string nmi or screenshot -- Default: nmi key : string [uuid|alias|hostname] value type of 'vm' parameter CLI Example: .. code-block:: bash salt '*' vmadm.sysrq 186da9ab-7392-4f55-91a5-b8f1fe770543 nmi salt '*' vmadm.sysrq 186da9ab-7392-4f55-91a5-b8f1fe770543 screenshot salt '*' vmadm.sysrq nacl nmi key=alias ''' ret = {} if key not in ['uuid', 'alias', 'hostname']: ret['Error'] = 'Key must be either uuid, alias or hostname' return ret if action not in ['nmi', 'screenshot']: ret['Error'] = 'Action must be either nmi or screenshot' return ret vm = lookup('{0}={1}'.format(key, vm), one=True) if 'Error' in vm: return vm # vmadm sysrq <uuid> <nmi|screenshot> cmd = 'vmadm sysrq {uuid} {action}'.format( uuid=vm, action=action ) res = __salt__['cmd.run_all'](cmd) retcode = res['retcode'] if retcode != 0: ret['Error'] = res['stderr'] if 'stderr' in res else _exit_status(retcode) return ret return True
python
def sysrq(vm, action='nmi', key='uuid'): ''' Send non-maskable interrupt to vm or capture a screenshot vm : string vm to be targeted action : string nmi or screenshot -- Default: nmi key : string [uuid|alias|hostname] value type of 'vm' parameter CLI Example: .. code-block:: bash salt '*' vmadm.sysrq 186da9ab-7392-4f55-91a5-b8f1fe770543 nmi salt '*' vmadm.sysrq 186da9ab-7392-4f55-91a5-b8f1fe770543 screenshot salt '*' vmadm.sysrq nacl nmi key=alias ''' ret = {} if key not in ['uuid', 'alias', 'hostname']: ret['Error'] = 'Key must be either uuid, alias or hostname' return ret if action not in ['nmi', 'screenshot']: ret['Error'] = 'Action must be either nmi or screenshot' return ret vm = lookup('{0}={1}'.format(key, vm), one=True) if 'Error' in vm: return vm # vmadm sysrq <uuid> <nmi|screenshot> cmd = 'vmadm sysrq {uuid} {action}'.format( uuid=vm, action=action ) res = __salt__['cmd.run_all'](cmd) retcode = res['retcode'] if retcode != 0: ret['Error'] = res['stderr'] if 'stderr' in res else _exit_status(retcode) return ret return True
[ "def", "sysrq", "(", "vm", ",", "action", "=", "'nmi'", ",", "key", "=", "'uuid'", ")", ":", "ret", "=", "{", "}", "if", "key", "not", "in", "[", "'uuid'", ",", "'alias'", ",", "'hostname'", "]", ":", "ret", "[", "'Error'", "]", "=", "'Key must b...
Send non-maskable interrupt to vm or capture a screenshot vm : string vm to be targeted action : string nmi or screenshot -- Default: nmi key : string [uuid|alias|hostname] value type of 'vm' parameter CLI Example: .. code-block:: bash salt '*' vmadm.sysrq 186da9ab-7392-4f55-91a5-b8f1fe770543 nmi salt '*' vmadm.sysrq 186da9ab-7392-4f55-91a5-b8f1fe770543 screenshot salt '*' vmadm.sysrq nacl nmi key=alias
[ "Send", "non", "-", "maskable", "interrupt", "to", "vm", "or", "capture", "a", "screenshot" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smartos_vmadm.py#L384-L423
train
saltstack/salt
salt/modules/smartos_vmadm.py
delete
def delete(vm, key='uuid'): ''' Delete a vm vm : string vm to be deleted key : string [uuid|alias|hostname] value type of 'vm' parameter CLI Example: .. code-block:: bash salt '*' vmadm.delete 186da9ab-7392-4f55-91a5-b8f1fe770543 salt '*' vmadm.delete nacl key=alias ''' ret = {} if key not in ['uuid', 'alias', 'hostname']: ret['Error'] = 'Key must be either uuid, alias or hostname' return ret vm = lookup('{0}={1}'.format(key, vm), one=True) if 'Error' in vm: return vm # vmadm delete <uuid> cmd = 'vmadm delete {0}'.format(vm) res = __salt__['cmd.run_all'](cmd) retcode = res['retcode'] if retcode != 0: ret['Error'] = res['stderr'] if 'stderr' in res else _exit_status(retcode) return ret return True
python
def delete(vm, key='uuid'): ''' Delete a vm vm : string vm to be deleted key : string [uuid|alias|hostname] value type of 'vm' parameter CLI Example: .. code-block:: bash salt '*' vmadm.delete 186da9ab-7392-4f55-91a5-b8f1fe770543 salt '*' vmadm.delete nacl key=alias ''' ret = {} if key not in ['uuid', 'alias', 'hostname']: ret['Error'] = 'Key must be either uuid, alias or hostname' return ret vm = lookup('{0}={1}'.format(key, vm), one=True) if 'Error' in vm: return vm # vmadm delete <uuid> cmd = 'vmadm delete {0}'.format(vm) res = __salt__['cmd.run_all'](cmd) retcode = res['retcode'] if retcode != 0: ret['Error'] = res['stderr'] if 'stderr' in res else _exit_status(retcode) return ret return True
[ "def", "delete", "(", "vm", ",", "key", "=", "'uuid'", ")", ":", "ret", "=", "{", "}", "if", "key", "not", "in", "[", "'uuid'", ",", "'alias'", ",", "'hostname'", "]", ":", "ret", "[", "'Error'", "]", "=", "'Key must be either uuid, alias or hostname'", ...
Delete a vm vm : string vm to be deleted key : string [uuid|alias|hostname] value type of 'vm' parameter CLI Example: .. code-block:: bash salt '*' vmadm.delete 186da9ab-7392-4f55-91a5-b8f1fe770543 salt '*' vmadm.delete nacl key=alias
[ "Delete", "a", "vm" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smartos_vmadm.py#L426-L456
train
saltstack/salt
salt/modules/smartos_vmadm.py
get
def get(vm, key='uuid'): ''' Output the JSON object describing a VM vm : string vm to be targeted key : string [uuid|alias|hostname] value type of 'vm' parameter CLI Example: .. code-block:: bash salt '*' vmadm.get 186da9ab-7392-4f55-91a5-b8f1fe770543 salt '*' vmadm.get nacl key=alias ''' ret = {} if key not in ['uuid', 'alias', 'hostname']: ret['Error'] = 'Key must be either uuid, alias or hostname' return ret vm = lookup('{0}={1}'.format(key, vm), one=True) if 'Error' in vm: return vm # vmadm get <uuid> cmd = 'vmadm get {0}'.format(vm) res = __salt__['cmd.run_all'](cmd) retcode = res['retcode'] if retcode != 0: ret['Error'] = res['stderr'] if 'stderr' in res else _exit_status(retcode) return ret return salt.utils.json.loads(res['stdout'])
python
def get(vm, key='uuid'): ''' Output the JSON object describing a VM vm : string vm to be targeted key : string [uuid|alias|hostname] value type of 'vm' parameter CLI Example: .. code-block:: bash salt '*' vmadm.get 186da9ab-7392-4f55-91a5-b8f1fe770543 salt '*' vmadm.get nacl key=alias ''' ret = {} if key not in ['uuid', 'alias', 'hostname']: ret['Error'] = 'Key must be either uuid, alias or hostname' return ret vm = lookup('{0}={1}'.format(key, vm), one=True) if 'Error' in vm: return vm # vmadm get <uuid> cmd = 'vmadm get {0}'.format(vm) res = __salt__['cmd.run_all'](cmd) retcode = res['retcode'] if retcode != 0: ret['Error'] = res['stderr'] if 'stderr' in res else _exit_status(retcode) return ret return salt.utils.json.loads(res['stdout'])
[ "def", "get", "(", "vm", ",", "key", "=", "'uuid'", ")", ":", "ret", "=", "{", "}", "if", "key", "not", "in", "[", "'uuid'", ",", "'alias'", ",", "'hostname'", "]", ":", "ret", "[", "'Error'", "]", "=", "'Key must be either uuid, alias or hostname'", "...
Output the JSON object describing a VM vm : string vm to be targeted key : string [uuid|alias|hostname] value type of 'vm' parameter CLI Example: .. code-block:: bash salt '*' vmadm.get 186da9ab-7392-4f55-91a5-b8f1fe770543 salt '*' vmadm.get nacl key=alias
[ "Output", "the", "JSON", "object", "describing", "a", "VM" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smartos_vmadm.py#L459-L489
train
saltstack/salt
salt/modules/smartos_vmadm.py
info
def info(vm, info_type='all', key='uuid'): ''' Lookup info on running kvm vm : string vm to be targeted info_type : string [all|block|blockstats|chardev|cpus|kvm|pci|spice|version|vnc] info type to return key : string [uuid|alias|hostname] value type of 'vm' parameter CLI Example: .. code-block:: bash salt '*' vmadm.info 186da9ab-7392-4f55-91a5-b8f1fe770543 salt '*' vmadm.info 186da9ab-7392-4f55-91a5-b8f1fe770543 vnc salt '*' vmadm.info nacl key=alias salt '*' vmadm.info nacl vnc key=alias ''' ret = {} if info_type not in ['all', 'block', 'blockstats', 'chardev', 'cpus', 'kvm', 'pci', 'spice', 'version', 'vnc']: ret['Error'] = 'Requested info_type is not available' return ret if key not in ['uuid', 'alias', 'hostname']: ret['Error'] = 'Key must be either uuid, alias or hostname' return ret vm = lookup('{0}={1}'.format(key, vm), one=True) if 'Error' in vm: return vm # vmadm info <uuid> [type,...] cmd = 'vmadm info {uuid} {type}'.format( uuid=vm, type=info_type ) res = __salt__['cmd.run_all'](cmd) retcode = res['retcode'] if retcode != 0: ret['Error'] = res['stderr'] if 'stderr' in res else _exit_status(retcode) return ret return salt.utils.json.loads(res['stdout'])
python
def info(vm, info_type='all', key='uuid'): ''' Lookup info on running kvm vm : string vm to be targeted info_type : string [all|block|blockstats|chardev|cpus|kvm|pci|spice|version|vnc] info type to return key : string [uuid|alias|hostname] value type of 'vm' parameter CLI Example: .. code-block:: bash salt '*' vmadm.info 186da9ab-7392-4f55-91a5-b8f1fe770543 salt '*' vmadm.info 186da9ab-7392-4f55-91a5-b8f1fe770543 vnc salt '*' vmadm.info nacl key=alias salt '*' vmadm.info nacl vnc key=alias ''' ret = {} if info_type not in ['all', 'block', 'blockstats', 'chardev', 'cpus', 'kvm', 'pci', 'spice', 'version', 'vnc']: ret['Error'] = 'Requested info_type is not available' return ret if key not in ['uuid', 'alias', 'hostname']: ret['Error'] = 'Key must be either uuid, alias or hostname' return ret vm = lookup('{0}={1}'.format(key, vm), one=True) if 'Error' in vm: return vm # vmadm info <uuid> [type,...] cmd = 'vmadm info {uuid} {type}'.format( uuid=vm, type=info_type ) res = __salt__['cmd.run_all'](cmd) retcode = res['retcode'] if retcode != 0: ret['Error'] = res['stderr'] if 'stderr' in res else _exit_status(retcode) return ret return salt.utils.json.loads(res['stdout'])
[ "def", "info", "(", "vm", ",", "info_type", "=", "'all'", ",", "key", "=", "'uuid'", ")", ":", "ret", "=", "{", "}", "if", "info_type", "not", "in", "[", "'all'", ",", "'block'", ",", "'blockstats'", ",", "'chardev'", ",", "'cpus'", ",", "'kvm'", "...
Lookup info on running kvm vm : string vm to be targeted info_type : string [all|block|blockstats|chardev|cpus|kvm|pci|spice|version|vnc] info type to return key : string [uuid|alias|hostname] value type of 'vm' parameter CLI Example: .. code-block:: bash salt '*' vmadm.info 186da9ab-7392-4f55-91a5-b8f1fe770543 salt '*' vmadm.info 186da9ab-7392-4f55-91a5-b8f1fe770543 vnc salt '*' vmadm.info nacl key=alias salt '*' vmadm.info nacl vnc key=alias
[ "Lookup", "info", "on", "running", "kvm" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smartos_vmadm.py#L492-L532
train
saltstack/salt
salt/modules/smartos_vmadm.py
create_snapshot
def create_snapshot(vm, name, key='uuid'): ''' Create snapshot of a vm vm : string vm to be targeted name : string snapshot name The snapname must be 64 characters or less and must only contain alphanumeric characters and characters in the set [-_.:%] to comply with ZFS restrictions. key : string [uuid|alias|hostname] value type of 'vm' parameter CLI Example: .. code-block:: bash salt '*' vmadm.create_snapshot 186da9ab-7392-4f55-91a5-b8f1fe770543 baseline salt '*' vmadm.create_snapshot nacl baseline key=alias ''' ret = {} if key not in ['uuid', 'alias', 'hostname']: ret['Error'] = 'Key must be either uuid, alias or hostname' return ret vm = lookup('{0}={1}'.format(key, vm), one=True) if 'Error' in vm: return vm vmobj = get(vm) if 'datasets' in vmobj: ret['Error'] = 'VM cannot have datasets' return ret if vmobj['brand'] in ['kvm']: ret['Error'] = 'VM must be of type OS' return ret if vmobj['zone_state'] not in ['running']: # work around a vmadm bug ret['Error'] = 'VM must be running to take a snapshot' return ret # vmadm create-snapshot <uuid> <snapname> cmd = 'vmadm create-snapshot {uuid} {snapshot}'.format( snapshot=name, uuid=vm ) res = __salt__['cmd.run_all'](cmd) retcode = res['retcode'] if retcode != 0: ret['Error'] = res['stderr'] if 'stderr' in res else _exit_status(retcode) return ret return True
python
def create_snapshot(vm, name, key='uuid'): ''' Create snapshot of a vm vm : string vm to be targeted name : string snapshot name The snapname must be 64 characters or less and must only contain alphanumeric characters and characters in the set [-_.:%] to comply with ZFS restrictions. key : string [uuid|alias|hostname] value type of 'vm' parameter CLI Example: .. code-block:: bash salt '*' vmadm.create_snapshot 186da9ab-7392-4f55-91a5-b8f1fe770543 baseline salt '*' vmadm.create_snapshot nacl baseline key=alias ''' ret = {} if key not in ['uuid', 'alias', 'hostname']: ret['Error'] = 'Key must be either uuid, alias or hostname' return ret vm = lookup('{0}={1}'.format(key, vm), one=True) if 'Error' in vm: return vm vmobj = get(vm) if 'datasets' in vmobj: ret['Error'] = 'VM cannot have datasets' return ret if vmobj['brand'] in ['kvm']: ret['Error'] = 'VM must be of type OS' return ret if vmobj['zone_state'] not in ['running']: # work around a vmadm bug ret['Error'] = 'VM must be running to take a snapshot' return ret # vmadm create-snapshot <uuid> <snapname> cmd = 'vmadm create-snapshot {uuid} {snapshot}'.format( snapshot=name, uuid=vm ) res = __salt__['cmd.run_all'](cmd) retcode = res['retcode'] if retcode != 0: ret['Error'] = res['stderr'] if 'stderr' in res else _exit_status(retcode) return ret return True
[ "def", "create_snapshot", "(", "vm", ",", "name", ",", "key", "=", "'uuid'", ")", ":", "ret", "=", "{", "}", "if", "key", "not", "in", "[", "'uuid'", ",", "'alias'", ",", "'hostname'", "]", ":", "ret", "[", "'Error'", "]", "=", "'Key must be either u...
Create snapshot of a vm vm : string vm to be targeted name : string snapshot name The snapname must be 64 characters or less and must only contain alphanumeric characters and characters in the set [-_.:%] to comply with ZFS restrictions. key : string [uuid|alias|hostname] value type of 'vm' parameter CLI Example: .. code-block:: bash salt '*' vmadm.create_snapshot 186da9ab-7392-4f55-91a5-b8f1fe770543 baseline salt '*' vmadm.create_snapshot nacl baseline key=alias
[ "Create", "snapshot", "of", "a", "vm" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smartos_vmadm.py#L535-L583
train
saltstack/salt
salt/modules/smartos_vmadm.py
reprovision
def reprovision(vm, image, key='uuid'): ''' Reprovision a vm vm : string vm to be reprovisioned image : string uuid of new image key : string [uuid|alias|hostname] value type of 'vm' parameter CLI Example: .. code-block:: bash salt '*' vmadm.reprovision 186da9ab-7392-4f55-91a5-b8f1fe770543 c02a2044-c1bd-11e4-bd8c-dfc1db8b0182 salt '*' vmadm.reprovision nacl c02a2044-c1bd-11e4-bd8c-dfc1db8b0182 key=alias ''' ret = {} if key not in ['uuid', 'alias', 'hostname']: ret['Error'] = 'Key must be either uuid, alias or hostname' return ret vm = lookup('{0}={1}'.format(key, vm), one=True) if 'Error' in vm: return vm if image not in __salt__['imgadm.list'](): ret['Error'] = 'Image ({0}) is not present on this host'.format(image) return ret # vmadm reprovision <uuid> [-f <filename>] cmd = six.text_type('echo {image} | vmadm reprovision {uuid}').format( uuid=salt.utils.stringutils.to_unicode(vm), image=_quote_args(salt.utils.json.dumps({'image_uuid': image})) ) res = __salt__['cmd.run_all'](cmd, python_shell=True) retcode = res['retcode'] if retcode != 0: ret['Error'] = res['stderr'] if 'stderr' in res else _exit_status(retcode) return ret return True
python
def reprovision(vm, image, key='uuid'): ''' Reprovision a vm vm : string vm to be reprovisioned image : string uuid of new image key : string [uuid|alias|hostname] value type of 'vm' parameter CLI Example: .. code-block:: bash salt '*' vmadm.reprovision 186da9ab-7392-4f55-91a5-b8f1fe770543 c02a2044-c1bd-11e4-bd8c-dfc1db8b0182 salt '*' vmadm.reprovision nacl c02a2044-c1bd-11e4-bd8c-dfc1db8b0182 key=alias ''' ret = {} if key not in ['uuid', 'alias', 'hostname']: ret['Error'] = 'Key must be either uuid, alias or hostname' return ret vm = lookup('{0}={1}'.format(key, vm), one=True) if 'Error' in vm: return vm if image not in __salt__['imgadm.list'](): ret['Error'] = 'Image ({0}) is not present on this host'.format(image) return ret # vmadm reprovision <uuid> [-f <filename>] cmd = six.text_type('echo {image} | vmadm reprovision {uuid}').format( uuid=salt.utils.stringutils.to_unicode(vm), image=_quote_args(salt.utils.json.dumps({'image_uuid': image})) ) res = __salt__['cmd.run_all'](cmd, python_shell=True) retcode = res['retcode'] if retcode != 0: ret['Error'] = res['stderr'] if 'stderr' in res else _exit_status(retcode) return ret return True
[ "def", "reprovision", "(", "vm", ",", "image", ",", "key", "=", "'uuid'", ")", ":", "ret", "=", "{", "}", "if", "key", "not", "in", "[", "'uuid'", ",", "'alias'", ",", "'hostname'", "]", ":", "ret", "[", "'Error'", "]", "=", "'Key must be either uuid...
Reprovision a vm vm : string vm to be reprovisioned image : string uuid of new image key : string [uuid|alias|hostname] value type of 'vm' parameter CLI Example: .. code-block:: bash salt '*' vmadm.reprovision 186da9ab-7392-4f55-91a5-b8f1fe770543 c02a2044-c1bd-11e4-bd8c-dfc1db8b0182 salt '*' vmadm.reprovision nacl c02a2044-c1bd-11e4-bd8c-dfc1db8b0182 key=alias
[ "Reprovision", "a", "vm" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smartos_vmadm.py#L682-L720
train
saltstack/salt
salt/modules/smartos_vmadm.py
create
def create(from_file=None, **kwargs): ''' Create a new vm from_file : string json file to create the vm from -- if present, all other options will be ignored kwargs : string|int|... options to set for the vm CLI Example: .. code-block:: bash salt '*' vmadm.create from_file=/tmp/new_vm.json salt '*' vmadm.create image_uuid='...' alias='...' nics='[{ "nic_tag": "admin", "ip": "198.51.100.123", ...}, {...}]' [...] ''' ret = {} # prepare vmcfg vmcfg = {} kwargs = salt.utils.args.clean_kwargs(**kwargs) for k, v in six.iteritems(kwargs): vmcfg[k] = v if from_file: return _create_update_from_file('create', path=from_file) else: return _create_update_from_cfg('create', vmcfg=vmcfg)
python
def create(from_file=None, **kwargs): ''' Create a new vm from_file : string json file to create the vm from -- if present, all other options will be ignored kwargs : string|int|... options to set for the vm CLI Example: .. code-block:: bash salt '*' vmadm.create from_file=/tmp/new_vm.json salt '*' vmadm.create image_uuid='...' alias='...' nics='[{ "nic_tag": "admin", "ip": "198.51.100.123", ...}, {...}]' [...] ''' ret = {} # prepare vmcfg vmcfg = {} kwargs = salt.utils.args.clean_kwargs(**kwargs) for k, v in six.iteritems(kwargs): vmcfg[k] = v if from_file: return _create_update_from_file('create', path=from_file) else: return _create_update_from_cfg('create', vmcfg=vmcfg)
[ "def", "create", "(", "from_file", "=", "None", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "}", "# prepare vmcfg", "vmcfg", "=", "{", "}", "kwargs", "=", "salt", ".", "utils", ".", "args", ".", "clean_kwargs", "(", "*", "*", "kwargs", ")",...
Create a new vm from_file : string json file to create the vm from -- if present, all other options will be ignored kwargs : string|int|... options to set for the vm CLI Example: .. code-block:: bash salt '*' vmadm.create from_file=/tmp/new_vm.json salt '*' vmadm.create image_uuid='...' alias='...' nics='[{ "nic_tag": "admin", "ip": "198.51.100.123", ...}, {...}]' [...]
[ "Create", "a", "new", "vm" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smartos_vmadm.py#L723-L749
train
saltstack/salt
salt/modules/smartos_vmadm.py
update
def update(vm, from_file=None, key='uuid', **kwargs): ''' Update a new vm vm : string vm to be updated from_file : string json file to update the vm with -- if present, all other options will be ignored key : string [uuid|alias|hostname] value type of 'vm' parameter kwargs : string|int|... options to update for the vm CLI Example: .. code-block:: bash salt '*' vmadm.update vm=186da9ab-7392-4f55-91a5-b8f1fe770543 from_file=/tmp/new_vm.json salt '*' vmadm.update vm=nacl key=alias from_file=/tmp/new_vm.json salt '*' vmadm.update vm=186da9ab-7392-4f55-91a5-b8f1fe770543 max_physical_memory=1024 ''' ret = {} # prepare vmcfg vmcfg = {} kwargs = salt.utils.args.clean_kwargs(**kwargs) for k, v in six.iteritems(kwargs): vmcfg[k] = v if key not in ['uuid', 'alias', 'hostname']: ret['Error'] = 'Key must be either uuid, alias or hostname' return ret uuid = lookup('{0}={1}'.format(key, vm), one=True) if 'Error' in uuid: return uuid if from_file: return _create_update_from_file('update', uuid, path=from_file) else: return _create_update_from_cfg('update', uuid, vmcfg=vmcfg)
python
def update(vm, from_file=None, key='uuid', **kwargs): ''' Update a new vm vm : string vm to be updated from_file : string json file to update the vm with -- if present, all other options will be ignored key : string [uuid|alias|hostname] value type of 'vm' parameter kwargs : string|int|... options to update for the vm CLI Example: .. code-block:: bash salt '*' vmadm.update vm=186da9ab-7392-4f55-91a5-b8f1fe770543 from_file=/tmp/new_vm.json salt '*' vmadm.update vm=nacl key=alias from_file=/tmp/new_vm.json salt '*' vmadm.update vm=186da9ab-7392-4f55-91a5-b8f1fe770543 max_physical_memory=1024 ''' ret = {} # prepare vmcfg vmcfg = {} kwargs = salt.utils.args.clean_kwargs(**kwargs) for k, v in six.iteritems(kwargs): vmcfg[k] = v if key not in ['uuid', 'alias', 'hostname']: ret['Error'] = 'Key must be either uuid, alias or hostname' return ret uuid = lookup('{0}={1}'.format(key, vm), one=True) if 'Error' in uuid: return uuid if from_file: return _create_update_from_file('update', uuid, path=from_file) else: return _create_update_from_cfg('update', uuid, vmcfg=vmcfg)
[ "def", "update", "(", "vm", ",", "from_file", "=", "None", ",", "key", "=", "'uuid'", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "}", "# prepare vmcfg", "vmcfg", "=", "{", "}", "kwargs", "=", "salt", ".", "utils", ".", "args", ".", "clea...
Update a new vm vm : string vm to be updated from_file : string json file to update the vm with -- if present, all other options will be ignored key : string [uuid|alias|hostname] value type of 'vm' parameter kwargs : string|int|... options to update for the vm CLI Example: .. code-block:: bash salt '*' vmadm.update vm=186da9ab-7392-4f55-91a5-b8f1fe770543 from_file=/tmp/new_vm.json salt '*' vmadm.update vm=nacl key=alias from_file=/tmp/new_vm.json salt '*' vmadm.update vm=186da9ab-7392-4f55-91a5-b8f1fe770543 max_physical_memory=1024
[ "Update", "a", "new", "vm" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smartos_vmadm.py#L752-L790
train
saltstack/salt
salt/modules/smartos_vmadm.py
send
def send(vm, target, key='uuid'): ''' Send a vm to a directory vm : string vm to be sent target : string target directory key : string [uuid|alias|hostname] value type of 'vm' parameter CLI Example: .. code-block:: bash salt '*' vmadm.send 186da9ab-7392-4f55-91a5-b8f1fe770543 /opt/backups salt '*' vmadm.send vm=nacl target=/opt/backups key=alias ''' ret = {} if key not in ['uuid', 'alias', 'hostname']: ret['Error'] = 'Key must be either uuid, alias or hostname' return ret if not os.path.isdir(target): ret['Error'] = 'Target must be a directory or host' return ret vm = lookup('{0}={1}'.format(key, vm), one=True) if 'Error' in vm: return vm # vmadm send <uuid> [target] cmd = 'vmadm send {uuid} > {target}'.format( uuid=vm, target=os.path.join(target, '{0}.vmdata'.format(vm)) ) res = __salt__['cmd.run_all'](cmd, python_shell=True) retcode = res['retcode'] if retcode != 0: ret['Error'] = res['stderr'] if 'stderr' in res else _exit_status(retcode) return ret vmobj = get(vm) if 'datasets' not in vmobj: return True log.warning('one or more datasets detected, this is not supported!') log.warning('trying to zfs send datasets...') for dataset in vmobj['datasets']: name = dataset.split('/') name = name[-1] cmd = 'zfs send {dataset} > {target}'.format( dataset=dataset, target=os.path.join(target, '{0}-{1}.zfsds'.format(vm, name)) ) res = __salt__['cmd.run_all'](cmd, python_shell=True) retcode = res['retcode'] if retcode != 0: ret['Error'] = res['stderr'] if 'stderr' in res else _exit_status(retcode) return ret return True
python
def send(vm, target, key='uuid'): ''' Send a vm to a directory vm : string vm to be sent target : string target directory key : string [uuid|alias|hostname] value type of 'vm' parameter CLI Example: .. code-block:: bash salt '*' vmadm.send 186da9ab-7392-4f55-91a5-b8f1fe770543 /opt/backups salt '*' vmadm.send vm=nacl target=/opt/backups key=alias ''' ret = {} if key not in ['uuid', 'alias', 'hostname']: ret['Error'] = 'Key must be either uuid, alias or hostname' return ret if not os.path.isdir(target): ret['Error'] = 'Target must be a directory or host' return ret vm = lookup('{0}={1}'.format(key, vm), one=True) if 'Error' in vm: return vm # vmadm send <uuid> [target] cmd = 'vmadm send {uuid} > {target}'.format( uuid=vm, target=os.path.join(target, '{0}.vmdata'.format(vm)) ) res = __salt__['cmd.run_all'](cmd, python_shell=True) retcode = res['retcode'] if retcode != 0: ret['Error'] = res['stderr'] if 'stderr' in res else _exit_status(retcode) return ret vmobj = get(vm) if 'datasets' not in vmobj: return True log.warning('one or more datasets detected, this is not supported!') log.warning('trying to zfs send datasets...') for dataset in vmobj['datasets']: name = dataset.split('/') name = name[-1] cmd = 'zfs send {dataset} > {target}'.format( dataset=dataset, target=os.path.join(target, '{0}-{1}.zfsds'.format(vm, name)) ) res = __salt__['cmd.run_all'](cmd, python_shell=True) retcode = res['retcode'] if retcode != 0: ret['Error'] = res['stderr'] if 'stderr' in res else _exit_status(retcode) return ret return True
[ "def", "send", "(", "vm", ",", "target", ",", "key", "=", "'uuid'", ")", ":", "ret", "=", "{", "}", "if", "key", "not", "in", "[", "'uuid'", ",", "'alias'", ",", "'hostname'", "]", ":", "ret", "[", "'Error'", "]", "=", "'Key must be either uuid, alia...
Send a vm to a directory vm : string vm to be sent target : string target directory key : string [uuid|alias|hostname] value type of 'vm' parameter CLI Example: .. code-block:: bash salt '*' vmadm.send 186da9ab-7392-4f55-91a5-b8f1fe770543 /opt/backups salt '*' vmadm.send vm=nacl target=/opt/backups key=alias
[ "Send", "a", "vm", "to", "a", "directory" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smartos_vmadm.py#L793-L848
train
saltstack/salt
salt/modules/smartos_vmadm.py
receive
def receive(uuid, source): ''' Receive a vm from a directory uuid : string uuid of vm to be received source : string source directory CLI Example: .. code-block:: bash salt '*' vmadm.receive 186da9ab-7392-4f55-91a5-b8f1fe770543 /opt/backups ''' ret = {} if not os.path.isdir(source): ret['Error'] = 'Source must be a directory or host' return ret if not os.path.exists(os.path.join(source, '{0}.vmdata'.format(uuid))): ret['Error'] = 'Unknow vm with uuid in {0}'.format(source) return ret # vmadm receive cmd = 'vmadm receive < {source}'.format( source=os.path.join(source, '{0}.vmdata'.format(uuid)) ) res = __salt__['cmd.run_all'](cmd, python_shell=True) retcode = res['retcode'] if retcode != 0 and not res['stderr'].endswith('datasets'): ret['Error'] = res['stderr'] if 'stderr' in res else _exit_status(retcode) return ret vmobj = get(uuid) if 'datasets' not in vmobj: return True log.warning('one or more datasets detected, this is not supported!') log.warning('trying to restore datasets, mountpoints will need to be set again...') for dataset in vmobj['datasets']: name = dataset.split('/') name = name[-1] cmd = 'zfs receive {dataset} < {source}'.format( dataset=dataset, source=os.path.join(source, '{0}-{1}.zfsds'.format(uuid, name)) ) res = __salt__['cmd.run_all'](cmd, python_shell=True) retcode = res['retcode'] if retcode != 0: ret['Error'] = res['stderr'] if 'stderr' in res else _exit_status(retcode) return ret cmd = 'vmadm install {0}'.format(uuid) res = __salt__['cmd.run_all'](cmd, python_shell=True) retcode = res['retcode'] if retcode != 0 and not res['stderr'].endswith('datasets'): ret['Error'] = res['stderr'] if 'stderr' in res else _exit_status(retcode) return ret return True
python
def receive(uuid, source): ''' Receive a vm from a directory uuid : string uuid of vm to be received source : string source directory CLI Example: .. code-block:: bash salt '*' vmadm.receive 186da9ab-7392-4f55-91a5-b8f1fe770543 /opt/backups ''' ret = {} if not os.path.isdir(source): ret['Error'] = 'Source must be a directory or host' return ret if not os.path.exists(os.path.join(source, '{0}.vmdata'.format(uuid))): ret['Error'] = 'Unknow vm with uuid in {0}'.format(source) return ret # vmadm receive cmd = 'vmadm receive < {source}'.format( source=os.path.join(source, '{0}.vmdata'.format(uuid)) ) res = __salt__['cmd.run_all'](cmd, python_shell=True) retcode = res['retcode'] if retcode != 0 and not res['stderr'].endswith('datasets'): ret['Error'] = res['stderr'] if 'stderr' in res else _exit_status(retcode) return ret vmobj = get(uuid) if 'datasets' not in vmobj: return True log.warning('one or more datasets detected, this is not supported!') log.warning('trying to restore datasets, mountpoints will need to be set again...') for dataset in vmobj['datasets']: name = dataset.split('/') name = name[-1] cmd = 'zfs receive {dataset} < {source}'.format( dataset=dataset, source=os.path.join(source, '{0}-{1}.zfsds'.format(uuid, name)) ) res = __salt__['cmd.run_all'](cmd, python_shell=True) retcode = res['retcode'] if retcode != 0: ret['Error'] = res['stderr'] if 'stderr' in res else _exit_status(retcode) return ret cmd = 'vmadm install {0}'.format(uuid) res = __salt__['cmd.run_all'](cmd, python_shell=True) retcode = res['retcode'] if retcode != 0 and not res['stderr'].endswith('datasets'): ret['Error'] = res['stderr'] if 'stderr' in res else _exit_status(retcode) return ret return True
[ "def", "receive", "(", "uuid", ",", "source", ")", ":", "ret", "=", "{", "}", "if", "not", "os", ".", "path", ".", "isdir", "(", "source", ")", ":", "ret", "[", "'Error'", "]", "=", "'Source must be a directory or host'", "return", "ret", "if", "not", ...
Receive a vm from a directory uuid : string uuid of vm to be received source : string source directory CLI Example: .. code-block:: bash salt '*' vmadm.receive 186da9ab-7392-4f55-91a5-b8f1fe770543 /opt/backups
[ "Receive", "a", "vm", "from", "a", "directory" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smartos_vmadm.py#L851-L905
train
saltstack/salt
salt/modules/win_dism.py
add_capability
def add_capability(capability, source=None, limit_access=False, image=None, restart=False): ''' Install a capability Args: capability (str): The capability to install source (Optional[str]): The optional source of the capability. Default is set by group policy and can be Windows Update. limit_access (Optional[bool]): Prevent DISM from contacting Windows Update for the source package image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. restart (Optional[bool]): Reboot the machine if required by the install Raises: NotImplementedError: For all versions of Windows that are not Windows 10 and later. Server editions of Windows use ServerManager instead. Returns: dict: A dictionary containing the results of the command CLI Example: .. code-block:: bash salt '*' dism.add_capability Tools.Graphics.DirectX~~~~0.0.1.0 ''' if salt.utils.versions.version_cmp(__grains__['osversion'], '10') == -1: raise NotImplementedError( '`install_capability` is not available on this version of Windows: ' '{0}'.format(__grains__['osversion'])) cmd = ['DISM', '/Quiet', '/Image:{0}'.format(image) if image else '/Online', '/Add-Capability', '/CapabilityName:{0}'.format(capability)] if source: cmd.append('/Source:{0}'.format(source)) if limit_access: cmd.append('/LimitAccess') if not restart: cmd.append('/NoRestart') return __salt__['cmd.run_all'](cmd)
python
def add_capability(capability, source=None, limit_access=False, image=None, restart=False): ''' Install a capability Args: capability (str): The capability to install source (Optional[str]): The optional source of the capability. Default is set by group policy and can be Windows Update. limit_access (Optional[bool]): Prevent DISM from contacting Windows Update for the source package image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. restart (Optional[bool]): Reboot the machine if required by the install Raises: NotImplementedError: For all versions of Windows that are not Windows 10 and later. Server editions of Windows use ServerManager instead. Returns: dict: A dictionary containing the results of the command CLI Example: .. code-block:: bash salt '*' dism.add_capability Tools.Graphics.DirectX~~~~0.0.1.0 ''' if salt.utils.versions.version_cmp(__grains__['osversion'], '10') == -1: raise NotImplementedError( '`install_capability` is not available on this version of Windows: ' '{0}'.format(__grains__['osversion'])) cmd = ['DISM', '/Quiet', '/Image:{0}'.format(image) if image else '/Online', '/Add-Capability', '/CapabilityName:{0}'.format(capability)] if source: cmd.append('/Source:{0}'.format(source)) if limit_access: cmd.append('/LimitAccess') if not restart: cmd.append('/NoRestart') return __salt__['cmd.run_all'](cmd)
[ "def", "add_capability", "(", "capability", ",", "source", "=", "None", ",", "limit_access", "=", "False", ",", "image", "=", "None", ",", "restart", "=", "False", ")", ":", "if", "salt", ".", "utils", ".", "versions", ".", "version_cmp", "(", "__grains_...
Install a capability Args: capability (str): The capability to install source (Optional[str]): The optional source of the capability. Default is set by group policy and can be Windows Update. limit_access (Optional[bool]): Prevent DISM from contacting Windows Update for the source package image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. restart (Optional[bool]): Reboot the machine if required by the install Raises: NotImplementedError: For all versions of Windows that are not Windows 10 and later. Server editions of Windows use ServerManager instead. Returns: dict: A dictionary containing the results of the command CLI Example: .. code-block:: bash salt '*' dism.add_capability Tools.Graphics.DirectX~~~~0.0.1.0
[ "Install", "a", "capability" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dism.py#L48-L98
train
saltstack/salt
salt/modules/win_dism.py
remove_capability
def remove_capability(capability, image=None, restart=False): ''' Uninstall a capability Args: capability(str): The capability to be removed image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. restart (Optional[bool]): Reboot the machine if required by the install Raises: NotImplementedError: For all versions of Windows that are not Windows 10 and later. Server editions of Windows use ServerManager instead. Returns: dict: A dictionary containing the results of the command CLI Example: .. code-block:: bash salt '*' dism.remove_capability Tools.Graphics.DirectX~~~~0.0.1.0 ''' if salt.utils.versions.version_cmp(__grains__['osversion'], '10') == -1: raise NotImplementedError( '`uninstall_capability` is not available on this version of ' 'Windows: {0}'.format(__grains__['osversion'])) cmd = ['DISM', '/Quiet', '/Image:{0}'.format(image) if image else '/Online', '/Remove-Capability', '/CapabilityName:{0}'.format(capability)] if not restart: cmd.append('/NoRestart') return __salt__['cmd.run_all'](cmd)
python
def remove_capability(capability, image=None, restart=False): ''' Uninstall a capability Args: capability(str): The capability to be removed image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. restart (Optional[bool]): Reboot the machine if required by the install Raises: NotImplementedError: For all versions of Windows that are not Windows 10 and later. Server editions of Windows use ServerManager instead. Returns: dict: A dictionary containing the results of the command CLI Example: .. code-block:: bash salt '*' dism.remove_capability Tools.Graphics.DirectX~~~~0.0.1.0 ''' if salt.utils.versions.version_cmp(__grains__['osversion'], '10') == -1: raise NotImplementedError( '`uninstall_capability` is not available on this version of ' 'Windows: {0}'.format(__grains__['osversion'])) cmd = ['DISM', '/Quiet', '/Image:{0}'.format(image) if image else '/Online', '/Remove-Capability', '/CapabilityName:{0}'.format(capability)] if not restart: cmd.append('/NoRestart') return __salt__['cmd.run_all'](cmd)
[ "def", "remove_capability", "(", "capability", ",", "image", "=", "None", ",", "restart", "=", "False", ")", ":", "if", "salt", ".", "utils", ".", "versions", ".", "version_cmp", "(", "__grains__", "[", "'osversion'", "]", ",", "'10'", ")", "==", "-", ...
Uninstall a capability Args: capability(str): The capability to be removed image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. restart (Optional[bool]): Reboot the machine if required by the install Raises: NotImplementedError: For all versions of Windows that are not Windows 10 and later. Server editions of Windows use ServerManager instead. Returns: dict: A dictionary containing the results of the command CLI Example: .. code-block:: bash salt '*' dism.remove_capability Tools.Graphics.DirectX~~~~0.0.1.0
[ "Uninstall", "a", "capability" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dism.py#L101-L139
train
saltstack/salt
salt/modules/win_dism.py
get_capabilities
def get_capabilities(image=None): ''' List all capabilities on the system Args: image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. Raises: NotImplementedError: For all versions of Windows that are not Windows 10 and later. Server editions of Windows use ServerManager instead. Returns: list: A list of capabilities CLI Example: .. code-block:: bash salt '*' dism.get_capabilities ''' if salt.utils.versions.version_cmp(__grains__['osversion'], '10') == -1: raise NotImplementedError( '`installed_capabilities` is not available on this version of ' 'Windows: {0}'.format(__grains__['osversion'])) cmd = ['DISM', '/English', '/Image:{0}'.format(image) if image else '/Online', '/Get-Capabilities'] out = __salt__['cmd.run'](cmd) pattern = r'Capability Identity : (.*)\r\n' capabilities = re.findall(pattern, out, re.MULTILINE) capabilities.sort() return capabilities
python
def get_capabilities(image=None): ''' List all capabilities on the system Args: image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. Raises: NotImplementedError: For all versions of Windows that are not Windows 10 and later. Server editions of Windows use ServerManager instead. Returns: list: A list of capabilities CLI Example: .. code-block:: bash salt '*' dism.get_capabilities ''' if salt.utils.versions.version_cmp(__grains__['osversion'], '10') == -1: raise NotImplementedError( '`installed_capabilities` is not available on this version of ' 'Windows: {0}'.format(__grains__['osversion'])) cmd = ['DISM', '/English', '/Image:{0}'.format(image) if image else '/Online', '/Get-Capabilities'] out = __salt__['cmd.run'](cmd) pattern = r'Capability Identity : (.*)\r\n' capabilities = re.findall(pattern, out, re.MULTILINE) capabilities.sort() return capabilities
[ "def", "get_capabilities", "(", "image", "=", "None", ")", ":", "if", "salt", ".", "utils", ".", "versions", ".", "version_cmp", "(", "__grains__", "[", "'osversion'", "]", ",", "'10'", ")", "==", "-", "1", ":", "raise", "NotImplementedError", "(", "'`in...
List all capabilities on the system Args: image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. Raises: NotImplementedError: For all versions of Windows that are not Windows 10 and later. Server editions of Windows use ServerManager instead. Returns: list: A list of capabilities CLI Example: .. code-block:: bash salt '*' dism.get_capabilities
[ "List", "all", "capabilities", "on", "the", "system" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dism.py#L142-L179
train
saltstack/salt
salt/modules/win_dism.py
installed_capabilities
def installed_capabilities(image=None): ''' List the capabilities installed on the system Args: image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. Raises: NotImplementedError: For all versions of Windows that are not Windows 10 and later. Server editions of Windows use ServerManager instead. Returns: list: A list of installed capabilities CLI Example: .. code-block:: bash salt '*' dism.installed_capabilities ''' if salt.utils.versions.version_cmp(__grains__['osversion'], '10') == -1: raise NotImplementedError( '`installed_capabilities` is not available on this version of ' 'Windows: {0}'.format(__grains__['osversion'])) return _get_components("Capability Identity", "Capabilities", "Installed")
python
def installed_capabilities(image=None): ''' List the capabilities installed on the system Args: image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. Raises: NotImplementedError: For all versions of Windows that are not Windows 10 and later. Server editions of Windows use ServerManager instead. Returns: list: A list of installed capabilities CLI Example: .. code-block:: bash salt '*' dism.installed_capabilities ''' if salt.utils.versions.version_cmp(__grains__['osversion'], '10') == -1: raise NotImplementedError( '`installed_capabilities` is not available on this version of ' 'Windows: {0}'.format(__grains__['osversion'])) return _get_components("Capability Identity", "Capabilities", "Installed")
[ "def", "installed_capabilities", "(", "image", "=", "None", ")", ":", "if", "salt", ".", "utils", ".", "versions", ".", "version_cmp", "(", "__grains__", "[", "'osversion'", "]", ",", "'10'", ")", "==", "-", "1", ":", "raise", "NotImplementedError", "(", ...
List the capabilities installed on the system Args: image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. Raises: NotImplementedError: For all versions of Windows that are not Windows 10 and later. Server editions of Windows use ServerManager instead. Returns: list: A list of installed capabilities CLI Example: .. code-block:: bash salt '*' dism.installed_capabilities
[ "List", "the", "capabilities", "installed", "on", "the", "system" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dism.py#L182-L208
train
saltstack/salt
salt/modules/win_dism.py
add_feature
def add_feature(feature, package=None, source=None, limit_access=False, enable_parent=False, image=None, restart=False): ''' Install a feature using DISM Args: feature (str): The feature to install package (Optional[str]): The parent package for the feature. You do not have to specify the package if it is the Windows Foundation Package. Otherwise, use package to specify the parent package of the feature source (Optional[str]): The optional source of the capability. Default is set by group policy and can be Windows Update limit_access (Optional[bool]): Prevent DISM from contacting Windows Update for the source package enable_parent (Optional[bool]): True will enable all parent features of the specified feature image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. restart (Optional[bool]): Reboot the machine if required by the install Returns: dict: A dictionary containing the results of the command CLI Example: .. code-block:: bash salt '*' dism.add_feature NetFx3 ''' cmd = ['DISM', '/Quiet', '/Image:{0}'.format(image) if image else '/Online', '/Enable-Feature', '/FeatureName:{0}'.format(feature)] if package: cmd.append('/PackageName:{0}'.format(package)) if source: cmd.append('/Source:{0}'.format(source)) if limit_access: cmd.append('/LimitAccess') if enable_parent: cmd.append('/All') if not restart: cmd.append('/NoRestart') return __salt__['cmd.run_all'](cmd)
python
def add_feature(feature, package=None, source=None, limit_access=False, enable_parent=False, image=None, restart=False): ''' Install a feature using DISM Args: feature (str): The feature to install package (Optional[str]): The parent package for the feature. You do not have to specify the package if it is the Windows Foundation Package. Otherwise, use package to specify the parent package of the feature source (Optional[str]): The optional source of the capability. Default is set by group policy and can be Windows Update limit_access (Optional[bool]): Prevent DISM from contacting Windows Update for the source package enable_parent (Optional[bool]): True will enable all parent features of the specified feature image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. restart (Optional[bool]): Reboot the machine if required by the install Returns: dict: A dictionary containing the results of the command CLI Example: .. code-block:: bash salt '*' dism.add_feature NetFx3 ''' cmd = ['DISM', '/Quiet', '/Image:{0}'.format(image) if image else '/Online', '/Enable-Feature', '/FeatureName:{0}'.format(feature)] if package: cmd.append('/PackageName:{0}'.format(package)) if source: cmd.append('/Source:{0}'.format(source)) if limit_access: cmd.append('/LimitAccess') if enable_parent: cmd.append('/All') if not restart: cmd.append('/NoRestart') return __salt__['cmd.run_all'](cmd)
[ "def", "add_feature", "(", "feature", ",", "package", "=", "None", ",", "source", "=", "None", ",", "limit_access", "=", "False", ",", "enable_parent", "=", "False", ",", "image", "=", "None", ",", "restart", "=", "False", ")", ":", "cmd", "=", "[", ...
Install a feature using DISM Args: feature (str): The feature to install package (Optional[str]): The parent package for the feature. You do not have to specify the package if it is the Windows Foundation Package. Otherwise, use package to specify the parent package of the feature source (Optional[str]): The optional source of the capability. Default is set by group policy and can be Windows Update limit_access (Optional[bool]): Prevent DISM from contacting Windows Update for the source package enable_parent (Optional[bool]): True will enable all parent features of the specified feature image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. restart (Optional[bool]): Reboot the machine if required by the install Returns: dict: A dictionary containing the results of the command CLI Example: .. code-block:: bash salt '*' dism.add_feature NetFx3
[ "Install", "a", "feature", "using", "DISM" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dism.py#L240-L291
train
saltstack/salt
salt/modules/win_dism.py
remove_feature
def remove_feature(feature, remove_payload=False, image=None, restart=False): ''' Disables the feature. Args: feature (str): The feature to uninstall remove_payload (Optional[bool]): Remove the feature's payload. Must supply source when enabling in the future. image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. restart (Optional[bool]): Reboot the machine if required by the install Returns: dict: A dictionary containing the results of the command CLI Example: .. code-block:: bash salt '*' dism.remove_feature NetFx3 ''' cmd = ['DISM', '/Quiet', '/Image:{0}'.format(image) if image else '/Online', '/Disable-Feature', '/FeatureName:{0}'.format(feature)] if remove_payload: cmd.append('/Remove') if not restart: cmd.append('/NoRestart') return __salt__['cmd.run_all'](cmd)
python
def remove_feature(feature, remove_payload=False, image=None, restart=False): ''' Disables the feature. Args: feature (str): The feature to uninstall remove_payload (Optional[bool]): Remove the feature's payload. Must supply source when enabling in the future. image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. restart (Optional[bool]): Reboot the machine if required by the install Returns: dict: A dictionary containing the results of the command CLI Example: .. code-block:: bash salt '*' dism.remove_feature NetFx3 ''' cmd = ['DISM', '/Quiet', '/Image:{0}'.format(image) if image else '/Online', '/Disable-Feature', '/FeatureName:{0}'.format(feature)] if remove_payload: cmd.append('/Remove') if not restart: cmd.append('/NoRestart') return __salt__['cmd.run_all'](cmd)
[ "def", "remove_feature", "(", "feature", ",", "remove_payload", "=", "False", ",", "image", "=", "None", ",", "restart", "=", "False", ")", ":", "cmd", "=", "[", "'DISM'", ",", "'/Quiet'", ",", "'/Image:{0}'", ".", "format", "(", "image", ")", "if", "i...
Disables the feature. Args: feature (str): The feature to uninstall remove_payload (Optional[bool]): Remove the feature's payload. Must supply source when enabling in the future. image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. restart (Optional[bool]): Reboot the machine if required by the install Returns: dict: A dictionary containing the results of the command CLI Example: .. code-block:: bash salt '*' dism.remove_feature NetFx3
[ "Disables", "the", "feature", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dism.py#L294-L327
train
saltstack/salt
salt/modules/win_dism.py
get_features
def get_features(package=None, image=None): ''' List features on the system or in a package Args: package (Optional[str]): The full path to the package. Can be either a .cab file or a folder. Should point to the original source of the package, not to where the file is installed. You cannot use this command to get package information for .msu files This can also be the name of a package as listed in ``dism.installed_packages`` image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. Returns: list: A list of features CLI Example: .. code-block:: bash # Return all features on the system salt '*' dism.get_features # Return all features in package.cab salt '*' dism.get_features C:\\packages\\package.cab # Return all features in the calc package salt '*' dism.get_features Microsoft.Windows.Calc.Demo~6595b6144ccf1df~x86~en~1.0.0.0 ''' cmd = ['DISM', '/English', '/Image:{0}'.format(image) if image else '/Online', '/Get-Features'] if package: if '~' in package: cmd.append('/PackageName:{0}'.format(package)) else: cmd.append('/PackagePath:{0}'.format(package)) out = __salt__['cmd.run'](cmd) pattern = r'Feature Name : (.*)\r\n' features = re.findall(pattern, out, re.MULTILINE) features.sort() return features
python
def get_features(package=None, image=None): ''' List features on the system or in a package Args: package (Optional[str]): The full path to the package. Can be either a .cab file or a folder. Should point to the original source of the package, not to where the file is installed. You cannot use this command to get package information for .msu files This can also be the name of a package as listed in ``dism.installed_packages`` image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. Returns: list: A list of features CLI Example: .. code-block:: bash # Return all features on the system salt '*' dism.get_features # Return all features in package.cab salt '*' dism.get_features C:\\packages\\package.cab # Return all features in the calc package salt '*' dism.get_features Microsoft.Windows.Calc.Demo~6595b6144ccf1df~x86~en~1.0.0.0 ''' cmd = ['DISM', '/English', '/Image:{0}'.format(image) if image else '/Online', '/Get-Features'] if package: if '~' in package: cmd.append('/PackageName:{0}'.format(package)) else: cmd.append('/PackagePath:{0}'.format(package)) out = __salt__['cmd.run'](cmd) pattern = r'Feature Name : (.*)\r\n' features = re.findall(pattern, out, re.MULTILINE) features.sort() return features
[ "def", "get_features", "(", "package", "=", "None", ",", "image", "=", "None", ")", ":", "cmd", "=", "[", "'DISM'", ",", "'/English'", ",", "'/Image:{0}'", ".", "format", "(", "image", ")", "if", "image", "else", "'/Online'", ",", "'/Get-Features'", "]",...
List features on the system or in a package Args: package (Optional[str]): The full path to the package. Can be either a .cab file or a folder. Should point to the original source of the package, not to where the file is installed. You cannot use this command to get package information for .msu files This can also be the name of a package as listed in ``dism.installed_packages`` image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. Returns: list: A list of features CLI Example: .. code-block:: bash # Return all features on the system salt '*' dism.get_features # Return all features in package.cab salt '*' dism.get_features C:\\packages\\package.cab # Return all features in the calc package salt '*' dism.get_features Microsoft.Windows.Calc.Demo~6595b6144ccf1df~x86~en~1.0.0.0
[ "List", "features", "on", "the", "system", "or", "in", "a", "package" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dism.py#L330-L379
train
saltstack/salt
salt/modules/win_dism.py
add_package
def add_package(package, ignore_check=False, prevent_pending=False, image=None, restart=False): ''' Install a package using DISM Args: package (str): The package to install. Can be a .cab file, a .msu file, or a folder .. note:: An `.msu` package is supported only when the target image is offline, either mounted or applied. ignore_check (Optional[bool]): Skip installation of the package if the applicability checks fail prevent_pending (Optional[bool]): Skip the installation of the package if there are pending online actions image (Optional[str]): The path to the root directory of an offline Windows image. If ``None`` is passed, the running operating system is targeted. Default is None. restart (Optional[bool]): Reboot the machine if required by the install Returns: dict: A dictionary containing the results of the command CLI Example: .. code-block:: bash salt '*' dism.add_package C:\\Packages\\package.cab ''' cmd = ['DISM', '/Quiet', '/Image:{0}'.format(image) if image else '/Online', '/Add-Package', '/PackagePath:{0}'.format(package)] if ignore_check: cmd.append('/IgnoreCheck') if prevent_pending: cmd.append('/PreventPending') if not restart: cmd.append('/NoRestart') return __salt__['cmd.run_all'](cmd)
python
def add_package(package, ignore_check=False, prevent_pending=False, image=None, restart=False): ''' Install a package using DISM Args: package (str): The package to install. Can be a .cab file, a .msu file, or a folder .. note:: An `.msu` package is supported only when the target image is offline, either mounted or applied. ignore_check (Optional[bool]): Skip installation of the package if the applicability checks fail prevent_pending (Optional[bool]): Skip the installation of the package if there are pending online actions image (Optional[str]): The path to the root directory of an offline Windows image. If ``None`` is passed, the running operating system is targeted. Default is None. restart (Optional[bool]): Reboot the machine if required by the install Returns: dict: A dictionary containing the results of the command CLI Example: .. code-block:: bash salt '*' dism.add_package C:\\Packages\\package.cab ''' cmd = ['DISM', '/Quiet', '/Image:{0}'.format(image) if image else '/Online', '/Add-Package', '/PackagePath:{0}'.format(package)] if ignore_check: cmd.append('/IgnoreCheck') if prevent_pending: cmd.append('/PreventPending') if not restart: cmd.append('/NoRestart') return __salt__['cmd.run_all'](cmd)
[ "def", "add_package", "(", "package", ",", "ignore_check", "=", "False", ",", "prevent_pending", "=", "False", ",", "image", "=", "None", ",", "restart", "=", "False", ")", ":", "cmd", "=", "[", "'DISM'", ",", "'/Quiet'", ",", "'/Image:{0}'", ".", "forma...
Install a package using DISM Args: package (str): The package to install. Can be a .cab file, a .msu file, or a folder .. note:: An `.msu` package is supported only when the target image is offline, either mounted or applied. ignore_check (Optional[bool]): Skip installation of the package if the applicability checks fail prevent_pending (Optional[bool]): Skip the installation of the package if there are pending online actions image (Optional[str]): The path to the root directory of an offline Windows image. If ``None`` is passed, the running operating system is targeted. Default is None. restart (Optional[bool]): Reboot the machine if required by the install Returns: dict: A dictionary containing the results of the command CLI Example: .. code-block:: bash salt '*' dism.add_package C:\\Packages\\package.cab
[ "Install", "a", "package", "using", "DISM" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dism.py#L424-L477
train
saltstack/salt
salt/modules/win_dism.py
remove_package
def remove_package(package, image=None, restart=False): ''' Uninstall a package Args: package (str): The full path to the package. Can be either a .cab file or a folder. Should point to the original source of the package, not to where the file is installed. This can also be the name of a package as listed in ``dism.installed_packages`` image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. restart (Optional[bool]): Reboot the machine if required by the install Returns: dict: A dictionary containing the results of the command CLI Example: .. code-block:: bash # Remove the Calc Package salt '*' dism.remove_package Microsoft.Windows.Calc.Demo~6595b6144ccf1df~x86~en~1.0.0.0 # Remove the package.cab (does not remove C:\\packages\\package.cab) salt '*' dism.remove_package C:\\packages\\package.cab ''' cmd = ['DISM', '/Quiet', '/Image:{0}'.format(image) if image else '/Online', '/Remove-Package'] if not restart: cmd.append('/NoRestart') if '~' in package: cmd.append('/PackageName:{0}'.format(package)) else: cmd.append('/PackagePath:{0}'.format(package)) return __salt__['cmd.run_all'](cmd)
python
def remove_package(package, image=None, restart=False): ''' Uninstall a package Args: package (str): The full path to the package. Can be either a .cab file or a folder. Should point to the original source of the package, not to where the file is installed. This can also be the name of a package as listed in ``dism.installed_packages`` image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. restart (Optional[bool]): Reboot the machine if required by the install Returns: dict: A dictionary containing the results of the command CLI Example: .. code-block:: bash # Remove the Calc Package salt '*' dism.remove_package Microsoft.Windows.Calc.Demo~6595b6144ccf1df~x86~en~1.0.0.0 # Remove the package.cab (does not remove C:\\packages\\package.cab) salt '*' dism.remove_package C:\\packages\\package.cab ''' cmd = ['DISM', '/Quiet', '/Image:{0}'.format(image) if image else '/Online', '/Remove-Package'] if not restart: cmd.append('/NoRestart') if '~' in package: cmd.append('/PackageName:{0}'.format(package)) else: cmd.append('/PackagePath:{0}'.format(package)) return __salt__['cmd.run_all'](cmd)
[ "def", "remove_package", "(", "package", ",", "image", "=", "None", ",", "restart", "=", "False", ")", ":", "cmd", "=", "[", "'DISM'", ",", "'/Quiet'", ",", "'/Image:{0}'", ".", "format", "(", "image", ")", "if", "image", "else", "'/Online'", ",", "'/R...
Uninstall a package Args: package (str): The full path to the package. Can be either a .cab file or a folder. Should point to the original source of the package, not to where the file is installed. This can also be the name of a package as listed in ``dism.installed_packages`` image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. restart (Optional[bool]): Reboot the machine if required by the install Returns: dict: A dictionary containing the results of the command CLI Example: .. code-block:: bash # Remove the Calc Package salt '*' dism.remove_package Microsoft.Windows.Calc.Demo~6595b6144ccf1df~x86~en~1.0.0.0 # Remove the package.cab (does not remove C:\\packages\\package.cab) salt '*' dism.remove_package C:\\packages\\package.cab
[ "Uninstall", "a", "package" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dism.py#L480-L520
train
saltstack/salt
salt/modules/win_dism.py
package_info
def package_info(package, image=None): ''' Display information about a package Args: package (str): The full path to the package. Can be either a .cab file or a folder. Should point to the original source of the package, not to where the file is installed. You cannot use this command to get package information for .msu files image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. Returns: dict: A dictionary containing the results of the command CLI Example: .. code-block:: bash salt '*' dism. package_info C:\\packages\\package.cab ''' cmd = ['DISM', '/English', '/Image:{0}'.format(image) if image else '/Online', '/Get-PackageInfo'] if '~' in package: cmd.append('/PackageName:{0}'.format(package)) else: cmd.append('/PackagePath:{0}'.format(package)) out = __salt__['cmd.run_all'](cmd) if out['retcode'] == 0: ret = dict() for line in six.text_type(out['stdout']).splitlines(): if ' : ' in line: info = line.split(' : ') if len(info) < 2: continue ret[info[0]] = info[1] else: ret = out return ret
python
def package_info(package, image=None): ''' Display information about a package Args: package (str): The full path to the package. Can be either a .cab file or a folder. Should point to the original source of the package, not to where the file is installed. You cannot use this command to get package information for .msu files image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. Returns: dict: A dictionary containing the results of the command CLI Example: .. code-block:: bash salt '*' dism. package_info C:\\packages\\package.cab ''' cmd = ['DISM', '/English', '/Image:{0}'.format(image) if image else '/Online', '/Get-PackageInfo'] if '~' in package: cmd.append('/PackageName:{0}'.format(package)) else: cmd.append('/PackagePath:{0}'.format(package)) out = __salt__['cmd.run_all'](cmd) if out['retcode'] == 0: ret = dict() for line in six.text_type(out['stdout']).splitlines(): if ' : ' in line: info = line.split(' : ') if len(info) < 2: continue ret[info[0]] = info[1] else: ret = out return ret
[ "def", "package_info", "(", "package", ",", "image", "=", "None", ")", ":", "cmd", "=", "[", "'DISM'", ",", "'/English'", ",", "'/Image:{0}'", ".", "format", "(", "image", ")", "if", "image", "else", "'/Online'", ",", "'/Get-PackageInfo'", "]", "if", "'~...
Display information about a package Args: package (str): The full path to the package. Can be either a .cab file or a folder. Should point to the original source of the package, not to where the file is installed. You cannot use this command to get package information for .msu files image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. Returns: dict: A dictionary containing the results of the command CLI Example: .. code-block:: bash salt '*' dism. package_info C:\\packages\\package.cab
[ "Display", "information", "about", "a", "package" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dism.py#L544-L589
train
saltstack/salt
salt/executors/sudo.py
execute
def execute(opts, data, func, args, kwargs): ''' Allow for the calling of execution modules via sudo. This module is invoked by the minion if the ``sudo_user`` minion config is present. Example minion config: .. code-block:: yaml sudo_user: saltdev Once this setting is made, any execution module call done by the minion will be run under ``sudo -u <sudo_user> salt-call``. For example, with the above minion config, .. code-block:: bash salt sudo_minion cmd.run 'cat /etc/sudoers' is equivalent to .. code-block:: bash sudo -u saltdev salt-call cmd.run 'cat /etc/sudoers' being run on ``sudo_minion``. ''' cmd = ['sudo', '-u', opts.get('sudo_user'), 'salt-call', '--out', 'json', '--metadata', '-c', opts.get('config_dir'), '--', data.get('fun')] if data['fun'] in ('state.sls', 'state.highstate', 'state.apply'): kwargs['concurrent'] = True for arg in args: cmd.append(_cmd_quote(six.text_type(arg))) for key in kwargs: cmd.append(_cmd_quote('{0}={1}'.format(key, kwargs[key]))) cmd_ret = __salt__['cmd.run_all'](cmd, use_vt=True, python_shell=False) if cmd_ret['retcode'] == 0: cmd_meta = salt.utils.json.loads(cmd_ret['stdout'])['local'] ret = cmd_meta['return'] __context__['retcode'] = cmd_meta.get('retcode', 0) else: ret = cmd_ret['stderr'] __context__['retcode'] = cmd_ret['retcode'] return ret
python
def execute(opts, data, func, args, kwargs): ''' Allow for the calling of execution modules via sudo. This module is invoked by the minion if the ``sudo_user`` minion config is present. Example minion config: .. code-block:: yaml sudo_user: saltdev Once this setting is made, any execution module call done by the minion will be run under ``sudo -u <sudo_user> salt-call``. For example, with the above minion config, .. code-block:: bash salt sudo_minion cmd.run 'cat /etc/sudoers' is equivalent to .. code-block:: bash sudo -u saltdev salt-call cmd.run 'cat /etc/sudoers' being run on ``sudo_minion``. ''' cmd = ['sudo', '-u', opts.get('sudo_user'), 'salt-call', '--out', 'json', '--metadata', '-c', opts.get('config_dir'), '--', data.get('fun')] if data['fun'] in ('state.sls', 'state.highstate', 'state.apply'): kwargs['concurrent'] = True for arg in args: cmd.append(_cmd_quote(six.text_type(arg))) for key in kwargs: cmd.append(_cmd_quote('{0}={1}'.format(key, kwargs[key]))) cmd_ret = __salt__['cmd.run_all'](cmd, use_vt=True, python_shell=False) if cmd_ret['retcode'] == 0: cmd_meta = salt.utils.json.loads(cmd_ret['stdout'])['local'] ret = cmd_meta['return'] __context__['retcode'] = cmd_meta.get('retcode', 0) else: ret = cmd_ret['stderr'] __context__['retcode'] = cmd_ret['retcode'] return ret
[ "def", "execute", "(", "opts", ",", "data", ",", "func", ",", "args", ",", "kwargs", ")", ":", "cmd", "=", "[", "'sudo'", ",", "'-u'", ",", "opts", ".", "get", "(", "'sudo_user'", ")", ",", "'salt-call'", ",", "'--out'", ",", "'json'", ",", "'--met...
Allow for the calling of execution modules via sudo. This module is invoked by the minion if the ``sudo_user`` minion config is present. Example minion config: .. code-block:: yaml sudo_user: saltdev Once this setting is made, any execution module call done by the minion will be run under ``sudo -u <sudo_user> salt-call``. For example, with the above minion config, .. code-block:: bash salt sudo_minion cmd.run 'cat /etc/sudoers' is equivalent to .. code-block:: bash sudo -u saltdev salt-call cmd.run 'cat /etc/sudoers' being run on ``sudo_minion``.
[ "Allow", "for", "the", "calling", "of", "execution", "modules", "via", "sudo", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/executors/sudo.py#L25-L79
train
saltstack/salt
salt/states/hg.py
_update_repo
def _update_repo(ret, name, target, clean, user, identity, rev, opts, update_head): ''' Update the repo to a given revision. Using clean passes -C to the hg up ''' log.debug('target %s is found, "hg pull && hg up is probably required"', target) current_rev = __salt__['hg.revision'](target, user=user, rev='.') if not current_rev: return _fail( ret, 'Seems that {0} is not a valid hg repo'.format(target)) if __opts__['test']: test_result = ( 'Repository {0} update is probably required (current ' 'revision is {1})').format(target, current_rev) return _neutral_test( ret, test_result) try: pull_out = __salt__['hg.pull'](target, user=user, identity=identity, opts=opts, repository=name) except CommandExecutionError as err: ret['result'] = False ret['comment'] = err return ret if update_head is False: changes = 'no changes found' not in pull_out if changes: ret['comment'] = 'Update is probably required but update_head=False so we will skip updating.' else: ret['comment'] = 'No changes found and update_head=False so will skip updating.' return ret if rev: try: __salt__['hg.update'](target, rev, force=clean, user=user) except CommandExecutionError as err: ret['result'] = False ret['comment'] = err return ret else: try: __salt__['hg.update'](target, 'tip', force=clean, user=user) except CommandExecutionError as err: ret['result'] = False ret['comment'] = err return ret new_rev = __salt__['hg.revision'](cwd=target, user=user, rev='.') if current_rev != new_rev: revision_text = '{0} => {1}'.format(current_rev, new_rev) log.info('Repository %s updated: %s', target, revision_text) ret['comment'] = 'Repository {0} updated.'.format(target) ret['changes']['revision'] = revision_text elif 'error:' in pull_out: return _fail( ret, 'An error was thrown by hg:\n{0}'.format(pull_out) ) return ret
python
def _update_repo(ret, name, target, clean, user, identity, rev, opts, update_head): ''' Update the repo to a given revision. Using clean passes -C to the hg up ''' log.debug('target %s is found, "hg pull && hg up is probably required"', target) current_rev = __salt__['hg.revision'](target, user=user, rev='.') if not current_rev: return _fail( ret, 'Seems that {0} is not a valid hg repo'.format(target)) if __opts__['test']: test_result = ( 'Repository {0} update is probably required (current ' 'revision is {1})').format(target, current_rev) return _neutral_test( ret, test_result) try: pull_out = __salt__['hg.pull'](target, user=user, identity=identity, opts=opts, repository=name) except CommandExecutionError as err: ret['result'] = False ret['comment'] = err return ret if update_head is False: changes = 'no changes found' not in pull_out if changes: ret['comment'] = 'Update is probably required but update_head=False so we will skip updating.' else: ret['comment'] = 'No changes found and update_head=False so will skip updating.' return ret if rev: try: __salt__['hg.update'](target, rev, force=clean, user=user) except CommandExecutionError as err: ret['result'] = False ret['comment'] = err return ret else: try: __salt__['hg.update'](target, 'tip', force=clean, user=user) except CommandExecutionError as err: ret['result'] = False ret['comment'] = err return ret new_rev = __salt__['hg.revision'](cwd=target, user=user, rev='.') if current_rev != new_rev: revision_text = '{0} => {1}'.format(current_rev, new_rev) log.info('Repository %s updated: %s', target, revision_text) ret['comment'] = 'Repository {0} updated.'.format(target) ret['changes']['revision'] = revision_text elif 'error:' in pull_out: return _fail( ret, 'An error was thrown by hg:\n{0}'.format(pull_out) ) return ret
[ "def", "_update_repo", "(", "ret", ",", "name", ",", "target", ",", "clean", ",", "user", ",", "identity", ",", "rev", ",", "opts", ",", "update_head", ")", ":", "log", ".", "debug", "(", "'target %s is found, \"hg pull && hg up is probably required\"'", ",", ...
Update the repo to a given revision. Using clean passes -C to the hg up
[ "Update", "the", "repo", "to", "a", "given", "revision", ".", "Using", "clean", "passes", "-", "C", "to", "the", "hg", "up" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/hg.py#L113-L175
train
saltstack/salt
salt/modules/zfs.py
exists
def exists(name, **kwargs): ''' Check if a ZFS filesystem or volume or snapshot exists. name : string name of dataset type : string also check if dataset is of a certain type, valid choices are: filesystem, snapshot, volume, bookmark, or all. .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt '*' zfs.exists myzpool/mydataset salt '*' zfs.exists myzpool/myvolume type=volume ''' ## Configure command # NOTE: initialize the defaults opts = {} # NOTE: set extra config from kwargs if kwargs.get('type', False): opts['-t'] = kwargs.get('type') ## Check if 'name' of 'type' exists res = __salt__['cmd.run_all']( __utils__['zfs.zfs_command']( command='list', opts=opts, target=name, ), python_shell=False, ignore_retcode=True, ) return res['retcode'] == 0
python
def exists(name, **kwargs): ''' Check if a ZFS filesystem or volume or snapshot exists. name : string name of dataset type : string also check if dataset is of a certain type, valid choices are: filesystem, snapshot, volume, bookmark, or all. .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt '*' zfs.exists myzpool/mydataset salt '*' zfs.exists myzpool/myvolume type=volume ''' ## Configure command # NOTE: initialize the defaults opts = {} # NOTE: set extra config from kwargs if kwargs.get('type', False): opts['-t'] = kwargs.get('type') ## Check if 'name' of 'type' exists res = __salt__['cmd.run_all']( __utils__['zfs.zfs_command']( command='list', opts=opts, target=name, ), python_shell=False, ignore_retcode=True, ) return res['retcode'] == 0
[ "def", "exists", "(", "name", ",", "*", "*", "kwargs", ")", ":", "## Configure command", "# NOTE: initialize the defaults", "opts", "=", "{", "}", "# NOTE: set extra config from kwargs", "if", "kwargs", ".", "get", "(", "'type'", ",", "False", ")", ":", "opts", ...
Check if a ZFS filesystem or volume or snapshot exists. name : string name of dataset type : string also check if dataset is of a certain type, valid choices are: filesystem, snapshot, volume, bookmark, or all. .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt '*' zfs.exists myzpool/mydataset salt '*' zfs.exists myzpool/myvolume type=volume
[ "Check", "if", "a", "ZFS", "filesystem", "or", "volume", "or", "snapshot", "exists", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zfs.py#L48-L87
train
saltstack/salt
salt/modules/zfs.py
create
def create(name, **kwargs): ''' Create a ZFS File System. name : string name of dataset or volume volume_size : string if specified, a zvol will be created instead of a dataset sparse : boolean create sparse volume create_parent : boolean creates all the non-existing parent datasets. any property specified on the command line using the -o option is ignored. properties : dict additional zfs properties (-o) .. note:: ZFS properties can be specified at the time of creation of the filesystem by passing an additional argument called "properties" and specifying the properties with their respective values in the form of a python dictionary:: properties="{'property1': 'value1', 'property2': 'value2'}" .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt '*' zfs.create myzpool/mydataset [create_parent=True|False] salt '*' zfs.create myzpool/mydataset properties="{'mountpoint': '/export/zfs', 'sharenfs': 'on'}" salt '*' zfs.create myzpool/volume volume_size=1G [sparse=True|False]` salt '*' zfs.create myzpool/volume volume_size=1G properties="{'volblocksize': '512'}" [sparse=True|False] ''' ## Configure command # NOTE: initialize the defaults flags = [] opts = {} # NOTE: push filesystem properties filesystem_properties = kwargs.get('properties', {}) # NOTE: set extra config from kwargs if kwargs.get('create_parent', False): flags.append('-p') if kwargs.get('sparse', False) and kwargs.get('volume_size', None): flags.append('-s') if kwargs.get('volume_size', None): opts['-V'] = __utils__['zfs.to_size'](kwargs.get('volume_size'), convert_to_human=False) ## Create filesystem/volume res = __salt__['cmd.run_all']( __utils__['zfs.zfs_command']( command='create', flags=flags, opts=opts, filesystem_properties=filesystem_properties, target=name, ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'created')
python
def create(name, **kwargs): ''' Create a ZFS File System. name : string name of dataset or volume volume_size : string if specified, a zvol will be created instead of a dataset sparse : boolean create sparse volume create_parent : boolean creates all the non-existing parent datasets. any property specified on the command line using the -o option is ignored. properties : dict additional zfs properties (-o) .. note:: ZFS properties can be specified at the time of creation of the filesystem by passing an additional argument called "properties" and specifying the properties with their respective values in the form of a python dictionary:: properties="{'property1': 'value1', 'property2': 'value2'}" .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt '*' zfs.create myzpool/mydataset [create_parent=True|False] salt '*' zfs.create myzpool/mydataset properties="{'mountpoint': '/export/zfs', 'sharenfs': 'on'}" salt '*' zfs.create myzpool/volume volume_size=1G [sparse=True|False]` salt '*' zfs.create myzpool/volume volume_size=1G properties="{'volblocksize': '512'}" [sparse=True|False] ''' ## Configure command # NOTE: initialize the defaults flags = [] opts = {} # NOTE: push filesystem properties filesystem_properties = kwargs.get('properties', {}) # NOTE: set extra config from kwargs if kwargs.get('create_parent', False): flags.append('-p') if kwargs.get('sparse', False) and kwargs.get('volume_size', None): flags.append('-s') if kwargs.get('volume_size', None): opts['-V'] = __utils__['zfs.to_size'](kwargs.get('volume_size'), convert_to_human=False) ## Create filesystem/volume res = __salt__['cmd.run_all']( __utils__['zfs.zfs_command']( command='create', flags=flags, opts=opts, filesystem_properties=filesystem_properties, target=name, ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'created')
[ "def", "create", "(", "name", ",", "*", "*", "kwargs", ")", ":", "## Configure command", "# NOTE: initialize the defaults", "flags", "=", "[", "]", "opts", "=", "{", "}", "# NOTE: push filesystem properties", "filesystem_properties", "=", "kwargs", ".", "get", "("...
Create a ZFS File System. name : string name of dataset or volume volume_size : string if specified, a zvol will be created instead of a dataset sparse : boolean create sparse volume create_parent : boolean creates all the non-existing parent datasets. any property specified on the command line using the -o option is ignored. properties : dict additional zfs properties (-o) .. note:: ZFS properties can be specified at the time of creation of the filesystem by passing an additional argument called "properties" and specifying the properties with their respective values in the form of a python dictionary:: properties="{'property1': 'value1', 'property2': 'value2'}" .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt '*' zfs.create myzpool/mydataset [create_parent=True|False] salt '*' zfs.create myzpool/mydataset properties="{'mountpoint': '/export/zfs', 'sharenfs': 'on'}" salt '*' zfs.create myzpool/volume volume_size=1G [sparse=True|False]` salt '*' zfs.create myzpool/volume volume_size=1G properties="{'volblocksize': '512'}" [sparse=True|False]
[ "Create", "a", "ZFS", "File", "System", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zfs.py#L90-L154
train
saltstack/salt
salt/modules/zfs.py
destroy
def destroy(name, **kwargs): ''' Destroy a ZFS File System. name : string name of dataset, volume, or snapshot force : boolean force an unmount of any file systems using the unmount -f command. recursive : boolean recursively destroy all children. (-r) recursive_all : boolean recursively destroy all dependents, including cloned file systems outside the target hierarchy. (-R) .. warning:: watch out when using recursive and recursive_all .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt '*' zfs.destroy myzpool/mydataset [force=True|False] ''' ## Configure command # NOTE: initialize the defaults flags = [] # NOTE: set extra config from kwargs if kwargs.get('force', False): flags.append('-f') if kwargs.get('recursive_all', False): flags.append('-R') if kwargs.get('recursive', False): flags.append('-r') ## Destroy filesystem/volume/snapshot/... res = __salt__['cmd.run_all']( __utils__['zfs.zfs_command']( command='destroy', flags=flags, target=name, ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'destroyed')
python
def destroy(name, **kwargs): ''' Destroy a ZFS File System. name : string name of dataset, volume, or snapshot force : boolean force an unmount of any file systems using the unmount -f command. recursive : boolean recursively destroy all children. (-r) recursive_all : boolean recursively destroy all dependents, including cloned file systems outside the target hierarchy. (-R) .. warning:: watch out when using recursive and recursive_all .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt '*' zfs.destroy myzpool/mydataset [force=True|False] ''' ## Configure command # NOTE: initialize the defaults flags = [] # NOTE: set extra config from kwargs if kwargs.get('force', False): flags.append('-f') if kwargs.get('recursive_all', False): flags.append('-R') if kwargs.get('recursive', False): flags.append('-r') ## Destroy filesystem/volume/snapshot/... res = __salt__['cmd.run_all']( __utils__['zfs.zfs_command']( command='destroy', flags=flags, target=name, ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'destroyed')
[ "def", "destroy", "(", "name", ",", "*", "*", "kwargs", ")", ":", "## Configure command", "# NOTE: initialize the defaults", "flags", "=", "[", "]", "# NOTE: set extra config from kwargs", "if", "kwargs", ".", "get", "(", "'force'", ",", "False", ")", ":", "flag...
Destroy a ZFS File System. name : string name of dataset, volume, or snapshot force : boolean force an unmount of any file systems using the unmount -f command. recursive : boolean recursively destroy all children. (-r) recursive_all : boolean recursively destroy all dependents, including cloned file systems outside the target hierarchy. (-R) .. warning:: watch out when using recursive and recursive_all .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt '*' zfs.destroy myzpool/mydataset [force=True|False]
[ "Destroy", "a", "ZFS", "File", "System", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zfs.py#L157-L205
train
saltstack/salt
salt/modules/zfs.py
rename
def rename(name, new_name, **kwargs): ''' Rename or Relocate a ZFS File System. name : string name of dataset, volume, or snapshot new_name : string new name of dataset, volume, or snapshot force : boolean force unmount any filesystems that need to be unmounted in the process. create_parent : boolean creates all the nonexistent parent datasets. Datasets created in this manner are automatically mounted according to the mountpoint property inherited from their parent. recursive : boolean recursively rename the snapshots of all descendent datasets. snapshots are the only dataset that can be renamed recursively. .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt '*' zfs.rename myzpool/mydataset myzpool/renameddataset ''' ## Configure command # NOTE: initialize the defaults flags = [] target = [] # NOTE: set extra config from kwargs if __utils__['zfs.is_snapshot'](name): if kwargs.get('create_parent', False): log.warning('zfs.rename - create_parent=True cannot be used with snapshots.') if kwargs.get('force', False): log.warning('zfs.rename - force=True cannot be used with snapshots.') if kwargs.get('recursive', False): flags.append('-r') else: if kwargs.get('create_parent', False): flags.append('-p') if kwargs.get('force', False): flags.append('-f') if kwargs.get('recursive', False): log.warning('zfs.rename - recursive=True can only be used with snapshots.') # NOTE: update target target.append(name) target.append(new_name) ## Rename filesystem/volume/snapshot/... res = __salt__['cmd.run_all']( __utils__['zfs.zfs_command']( command='rename', flags=flags, target=target, ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'renamed')
python
def rename(name, new_name, **kwargs): ''' Rename or Relocate a ZFS File System. name : string name of dataset, volume, or snapshot new_name : string new name of dataset, volume, or snapshot force : boolean force unmount any filesystems that need to be unmounted in the process. create_parent : boolean creates all the nonexistent parent datasets. Datasets created in this manner are automatically mounted according to the mountpoint property inherited from their parent. recursive : boolean recursively rename the snapshots of all descendent datasets. snapshots are the only dataset that can be renamed recursively. .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt '*' zfs.rename myzpool/mydataset myzpool/renameddataset ''' ## Configure command # NOTE: initialize the defaults flags = [] target = [] # NOTE: set extra config from kwargs if __utils__['zfs.is_snapshot'](name): if kwargs.get('create_parent', False): log.warning('zfs.rename - create_parent=True cannot be used with snapshots.') if kwargs.get('force', False): log.warning('zfs.rename - force=True cannot be used with snapshots.') if kwargs.get('recursive', False): flags.append('-r') else: if kwargs.get('create_parent', False): flags.append('-p') if kwargs.get('force', False): flags.append('-f') if kwargs.get('recursive', False): log.warning('zfs.rename - recursive=True can only be used with snapshots.') # NOTE: update target target.append(name) target.append(new_name) ## Rename filesystem/volume/snapshot/... res = __salt__['cmd.run_all']( __utils__['zfs.zfs_command']( command='rename', flags=flags, target=target, ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'renamed')
[ "def", "rename", "(", "name", ",", "new_name", ",", "*", "*", "kwargs", ")", ":", "## Configure command", "# NOTE: initialize the defaults", "flags", "=", "[", "]", "target", "=", "[", "]", "# NOTE: set extra config from kwargs", "if", "__utils__", "[", "'zfs.is_s...
Rename or Relocate a ZFS File System. name : string name of dataset, volume, or snapshot new_name : string new name of dataset, volume, or snapshot force : boolean force unmount any filesystems that need to be unmounted in the process. create_parent : boolean creates all the nonexistent parent datasets. Datasets created in this manner are automatically mounted according to the mountpoint property inherited from their parent. recursive : boolean recursively rename the snapshots of all descendent datasets. snapshots are the only dataset that can be renamed recursively. .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt '*' zfs.rename myzpool/mydataset myzpool/renameddataset
[ "Rename", "or", "Relocate", "a", "ZFS", "File", "System", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zfs.py#L208-L270
train
saltstack/salt
salt/modules/zfs.py
list_
def list_(name=None, **kwargs): ''' Return a list of all datasets or a specified dataset on the system and the values of their used, available, referenced, and mountpoint properties. name : string name of dataset, volume, or snapshot recursive : boolean recursively list children depth : int limit recursion to depth properties : string comma-separated list of properties to list, the name property will always be added type : string comma-separated list of types to display, where type is one of filesystem, snapshot, volume, bookmark, or all. sort : string property to sort on (default = name) order : string [ascending|descending] sort order (default = ascending) parsable : boolean display numbers in parsable (exact) values .. versionadded:: 2018.3.0 .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt '*' zfs.list salt '*' zfs.list myzpool/mydataset [recursive=True|False] salt '*' zfs.list myzpool/mydataset properties="sharenfs,mountpoint" ''' ret = OrderedDict() ## update properties # NOTE: properties should be a list properties = kwargs.get('properties', 'used,avail,refer,mountpoint') if not isinstance(properties, list): properties = properties.split(',') # NOTE: name should be first property # we loop here because there 'name' can be in the list # multiple times. while 'name' in properties: properties.remove('name') properties.insert(0, 'name') ## Configure command # NOTE: initialize the defaults flags = ['-H'] opts = {} # NOTE: set extra config from kwargs if kwargs.get('recursive', False): flags.append('-r') if kwargs.get('recursive', False) and kwargs.get('depth', False): opts['-d'] = kwargs.get('depth') if kwargs.get('type', False): opts['-t'] = kwargs.get('type') kwargs_sort = kwargs.get('sort', False) if kwargs_sort and kwargs_sort in properties: if kwargs.get('order', 'ascending').startswith('a'): opts['-s'] = kwargs_sort else: opts['-S'] = kwargs_sort if isinstance(properties, list): # NOTE: There can be only one -o and it takes a comma-seperated list opts['-o'] = ','.join(properties) else: opts['-o'] = properties ## parse zfs list res = __salt__['cmd.run_all']( __utils__['zfs.zfs_command']( command='list', flags=flags, opts=opts, target=name, ), python_shell=False, ) if res['retcode'] == 0: for ds in res['stdout'].splitlines(): if kwargs.get('parsable', True): ds_data = __utils__['zfs.from_auto_dict']( OrderedDict(list(zip(properties, ds.split("\t")))), ) else: ds_data = __utils__['zfs.to_auto_dict']( OrderedDict(list(zip(properties, ds.split("\t")))), convert_to_human=True, ) ret[ds_data['name']] = ds_data del ret[ds_data['name']]['name'] else: return __utils__['zfs.parse_command_result'](res) return ret
python
def list_(name=None, **kwargs): ''' Return a list of all datasets or a specified dataset on the system and the values of their used, available, referenced, and mountpoint properties. name : string name of dataset, volume, or snapshot recursive : boolean recursively list children depth : int limit recursion to depth properties : string comma-separated list of properties to list, the name property will always be added type : string comma-separated list of types to display, where type is one of filesystem, snapshot, volume, bookmark, or all. sort : string property to sort on (default = name) order : string [ascending|descending] sort order (default = ascending) parsable : boolean display numbers in parsable (exact) values .. versionadded:: 2018.3.0 .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt '*' zfs.list salt '*' zfs.list myzpool/mydataset [recursive=True|False] salt '*' zfs.list myzpool/mydataset properties="sharenfs,mountpoint" ''' ret = OrderedDict() ## update properties # NOTE: properties should be a list properties = kwargs.get('properties', 'used,avail,refer,mountpoint') if not isinstance(properties, list): properties = properties.split(',') # NOTE: name should be first property # we loop here because there 'name' can be in the list # multiple times. while 'name' in properties: properties.remove('name') properties.insert(0, 'name') ## Configure command # NOTE: initialize the defaults flags = ['-H'] opts = {} # NOTE: set extra config from kwargs if kwargs.get('recursive', False): flags.append('-r') if kwargs.get('recursive', False) and kwargs.get('depth', False): opts['-d'] = kwargs.get('depth') if kwargs.get('type', False): opts['-t'] = kwargs.get('type') kwargs_sort = kwargs.get('sort', False) if kwargs_sort and kwargs_sort in properties: if kwargs.get('order', 'ascending').startswith('a'): opts['-s'] = kwargs_sort else: opts['-S'] = kwargs_sort if isinstance(properties, list): # NOTE: There can be only one -o and it takes a comma-seperated list opts['-o'] = ','.join(properties) else: opts['-o'] = properties ## parse zfs list res = __salt__['cmd.run_all']( __utils__['zfs.zfs_command']( command='list', flags=flags, opts=opts, target=name, ), python_shell=False, ) if res['retcode'] == 0: for ds in res['stdout'].splitlines(): if kwargs.get('parsable', True): ds_data = __utils__['zfs.from_auto_dict']( OrderedDict(list(zip(properties, ds.split("\t")))), ) else: ds_data = __utils__['zfs.to_auto_dict']( OrderedDict(list(zip(properties, ds.split("\t")))), convert_to_human=True, ) ret[ds_data['name']] = ds_data del ret[ds_data['name']]['name'] else: return __utils__['zfs.parse_command_result'](res) return ret
[ "def", "list_", "(", "name", "=", "None", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "OrderedDict", "(", ")", "## update properties", "# NOTE: properties should be a list", "properties", "=", "kwargs", ".", "get", "(", "'properties'", ",", "'used,avail,refer...
Return a list of all datasets or a specified dataset on the system and the values of their used, available, referenced, and mountpoint properties. name : string name of dataset, volume, or snapshot recursive : boolean recursively list children depth : int limit recursion to depth properties : string comma-separated list of properties to list, the name property will always be added type : string comma-separated list of types to display, where type is one of filesystem, snapshot, volume, bookmark, or all. sort : string property to sort on (default = name) order : string [ascending|descending] sort order (default = ascending) parsable : boolean display numbers in parsable (exact) values .. versionadded:: 2018.3.0 .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt '*' zfs.list salt '*' zfs.list myzpool/mydataset [recursive=True|False] salt '*' zfs.list myzpool/mydataset properties="sharenfs,mountpoint"
[ "Return", "a", "list", "of", "all", "datasets", "or", "a", "specified", "dataset", "on", "the", "system", "and", "the", "values", "of", "their", "used", "available", "referenced", "and", "mountpoint", "properties", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zfs.py#L273-L374
train
saltstack/salt
salt/modules/zfs.py
list_mount
def list_mount(): ''' List mounted zfs filesystems .. versionadded:: 2018.3.1 CLI Example: .. code-block:: bash salt '*' zfs.list_mount ''' ## List mounted filesystem res = __salt__['cmd.run_all']( __utils__['zfs.zfs_command']( command='mount', ), python_shell=False, ) if res['retcode'] == 0: ret = OrderedDict() for mount in res['stdout'].splitlines(): mount = mount.split() ret[mount[0]] = mount[-1] return ret else: return __utils__['zfs.parse_command_result'](res)
python
def list_mount(): ''' List mounted zfs filesystems .. versionadded:: 2018.3.1 CLI Example: .. code-block:: bash salt '*' zfs.list_mount ''' ## List mounted filesystem res = __salt__['cmd.run_all']( __utils__['zfs.zfs_command']( command='mount', ), python_shell=False, ) if res['retcode'] == 0: ret = OrderedDict() for mount in res['stdout'].splitlines(): mount = mount.split() ret[mount[0]] = mount[-1] return ret else: return __utils__['zfs.parse_command_result'](res)
[ "def", "list_mount", "(", ")", ":", "## List mounted filesystem", "res", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "__utils__", "[", "'zfs.zfs_command'", "]", "(", "command", "=", "'mount'", ",", ")", ",", "python_shell", "=", "False", ",", ")", "if",...
List mounted zfs filesystems .. versionadded:: 2018.3.1 CLI Example: .. code-block:: bash salt '*' zfs.list_mount
[ "List", "mounted", "zfs", "filesystems" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zfs.py#L377-L405
train
saltstack/salt
salt/modules/zfs.py
mount
def mount(name=None, **kwargs): ''' Mounts ZFS file systems name : string name of the filesystem, having this set to None will mount all filesystems. (this is the default) overlay : boolean perform an overlay mount. options : string optional comma-separated list of mount options to use temporarily for the duration of the mount. .. versionadded:: 2016.3.0 .. versionchanged:: 2018.3.1 .. warning:: Passing '-a' as name is deprecated and will be removed in Sodium. CLI Example: .. code-block:: bash salt '*' zfs.mount salt '*' zfs.mount myzpool/mydataset salt '*' zfs.mount myzpool/mydataset options=ro ''' ## Configure command # NOTE: initialize the defaults flags = [] opts = {} # NOTE: set extra config from kwargs if kwargs.get('overlay', False): flags.append('-O') if kwargs.get('options', False): opts['-o'] = kwargs.get('options') if name in [None, '-a']: # NOTE: the new way to mount all filesystems is to have name # set to ```None```. We still accept the old '-a' until # Sodium. After Sodium we can update the if statement # to ```if not name:``` if name == '-a': salt.utils.versions.warn_until( 'Sodium', 'Passing \'-a\' as name is deprecated as of Salt 2019.2.0. This ' 'warning will be removed in Salt Sodium. Please pass name as ' '\'None\' instead to mount all filesystems.') flags.append('-a') name = None ## Mount filesystem res = __salt__['cmd.run_all']( __utils__['zfs.zfs_command']( command='mount', flags=flags, opts=opts, target=name, ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'mounted')
python
def mount(name=None, **kwargs): ''' Mounts ZFS file systems name : string name of the filesystem, having this set to None will mount all filesystems. (this is the default) overlay : boolean perform an overlay mount. options : string optional comma-separated list of mount options to use temporarily for the duration of the mount. .. versionadded:: 2016.3.0 .. versionchanged:: 2018.3.1 .. warning:: Passing '-a' as name is deprecated and will be removed in Sodium. CLI Example: .. code-block:: bash salt '*' zfs.mount salt '*' zfs.mount myzpool/mydataset salt '*' zfs.mount myzpool/mydataset options=ro ''' ## Configure command # NOTE: initialize the defaults flags = [] opts = {} # NOTE: set extra config from kwargs if kwargs.get('overlay', False): flags.append('-O') if kwargs.get('options', False): opts['-o'] = kwargs.get('options') if name in [None, '-a']: # NOTE: the new way to mount all filesystems is to have name # set to ```None```. We still accept the old '-a' until # Sodium. After Sodium we can update the if statement # to ```if not name:``` if name == '-a': salt.utils.versions.warn_until( 'Sodium', 'Passing \'-a\' as name is deprecated as of Salt 2019.2.0. This ' 'warning will be removed in Salt Sodium. Please pass name as ' '\'None\' instead to mount all filesystems.') flags.append('-a') name = None ## Mount filesystem res = __salt__['cmd.run_all']( __utils__['zfs.zfs_command']( command='mount', flags=flags, opts=opts, target=name, ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'mounted')
[ "def", "mount", "(", "name", "=", "None", ",", "*", "*", "kwargs", ")", ":", "## Configure command", "# NOTE: initialize the defaults", "flags", "=", "[", "]", "opts", "=", "{", "}", "# NOTE: set extra config from kwargs", "if", "kwargs", ".", "get", "(", "'ov...
Mounts ZFS file systems name : string name of the filesystem, having this set to None will mount all filesystems. (this is the default) overlay : boolean perform an overlay mount. options : string optional comma-separated list of mount options to use temporarily for the duration of the mount. .. versionadded:: 2016.3.0 .. versionchanged:: 2018.3.1 .. warning:: Passing '-a' as name is deprecated and will be removed in Sodium. CLI Example: .. code-block:: bash salt '*' zfs.mount salt '*' zfs.mount myzpool/mydataset salt '*' zfs.mount myzpool/mydataset options=ro
[ "Mounts", "ZFS", "file", "systems" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zfs.py#L408-L471
train
saltstack/salt
salt/modules/zfs.py
unmount
def unmount(name, **kwargs): ''' Unmounts ZFS file systems name : string name of the filesystem, you can use None to unmount all mounted filesystems. force : boolean forcefully unmount the file system, even if it is currently in use. .. warning:: Using ``-a`` for the name parameter will probably break your system, unless your rootfs is not on zfs. .. versionadded:: 2016.3.0 .. versionchanged:: 2018.3.1 .. warning:: Passing '-a' as name is deprecated and will be removed in Sodium. CLI Example: .. code-block:: bash salt '*' zfs.unmount myzpool/mydataset [force=True|False] ''' ## Configure command # NOTE: initialize the defaults flags = [] # NOTE: set extra config from kwargs if kwargs.get('force', False): flags.append('-f') if name in [None, '-a']: # NOTE: still accept '-a' as name for backwards compatibility # until Salt Sodium this should just simplify # this to just set '-a' if name is not set. flags.append('-a') name = None ## Unmount filesystem res = __salt__['cmd.run_all']( __utils__['zfs.zfs_command']( command='unmount', flags=flags, target=name, ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'unmounted')
python
def unmount(name, **kwargs): ''' Unmounts ZFS file systems name : string name of the filesystem, you can use None to unmount all mounted filesystems. force : boolean forcefully unmount the file system, even if it is currently in use. .. warning:: Using ``-a`` for the name parameter will probably break your system, unless your rootfs is not on zfs. .. versionadded:: 2016.3.0 .. versionchanged:: 2018.3.1 .. warning:: Passing '-a' as name is deprecated and will be removed in Sodium. CLI Example: .. code-block:: bash salt '*' zfs.unmount myzpool/mydataset [force=True|False] ''' ## Configure command # NOTE: initialize the defaults flags = [] # NOTE: set extra config from kwargs if kwargs.get('force', False): flags.append('-f') if name in [None, '-a']: # NOTE: still accept '-a' as name for backwards compatibility # until Salt Sodium this should just simplify # this to just set '-a' if name is not set. flags.append('-a') name = None ## Unmount filesystem res = __salt__['cmd.run_all']( __utils__['zfs.zfs_command']( command='unmount', flags=flags, target=name, ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'unmounted')
[ "def", "unmount", "(", "name", ",", "*", "*", "kwargs", ")", ":", "## Configure command", "# NOTE: initialize the defaults", "flags", "=", "[", "]", "# NOTE: set extra config from kwargs", "if", "kwargs", ".", "get", "(", "'force'", ",", "False", ")", ":", "flag...
Unmounts ZFS file systems name : string name of the filesystem, you can use None to unmount all mounted filesystems. force : boolean forcefully unmount the file system, even if it is currently in use. .. warning:: Using ``-a`` for the name parameter will probably break your system, unless your rootfs is not on zfs. .. versionadded:: 2016.3.0 .. versionchanged:: 2018.3.1 .. warning:: Passing '-a' as name is deprecated and will be removed in Sodium. CLI Example: .. code-block:: bash salt '*' zfs.unmount myzpool/mydataset [force=True|False]
[ "Unmounts", "ZFS", "file", "systems" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zfs.py#L474-L525
train
saltstack/salt
salt/modules/zfs.py
inherit
def inherit(prop, name, **kwargs): ''' Clears the specified property prop : string name of property name : string name of the filesystem, volume, or snapshot recursive : boolean recursively inherit the given property for all children. revert : boolean revert the property to the received value if one exists; otherwise operate as if the -S option was not specified. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zfs.inherit canmount myzpool/mydataset [recursive=True|False] ''' ## Configure command # NOTE: initialize the defaults flags = [] # NOTE: set extra config from kwargs if kwargs.get('recursive', False): flags.append('-r') if kwargs.get('revert', False): flags.append('-S') ## Inherit property res = __salt__['cmd.run_all']( __utils__['zfs.zfs_command']( command='inherit', flags=flags, property_name=prop, target=name, ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'inherited')
python
def inherit(prop, name, **kwargs): ''' Clears the specified property prop : string name of property name : string name of the filesystem, volume, or snapshot recursive : boolean recursively inherit the given property for all children. revert : boolean revert the property to the received value if one exists; otherwise operate as if the -S option was not specified. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zfs.inherit canmount myzpool/mydataset [recursive=True|False] ''' ## Configure command # NOTE: initialize the defaults flags = [] # NOTE: set extra config from kwargs if kwargs.get('recursive', False): flags.append('-r') if kwargs.get('revert', False): flags.append('-S') ## Inherit property res = __salt__['cmd.run_all']( __utils__['zfs.zfs_command']( command='inherit', flags=flags, property_name=prop, target=name, ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'inherited')
[ "def", "inherit", "(", "prop", ",", "name", ",", "*", "*", "kwargs", ")", ":", "## Configure command", "# NOTE: initialize the defaults", "flags", "=", "[", "]", "# NOTE: set extra config from kwargs", "if", "kwargs", ".", "get", "(", "'recursive'", ",", "False", ...
Clears the specified property prop : string name of property name : string name of the filesystem, volume, or snapshot recursive : boolean recursively inherit the given property for all children. revert : boolean revert the property to the received value if one exists; otherwise operate as if the -S option was not specified. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zfs.inherit canmount myzpool/mydataset [recursive=True|False]
[ "Clears", "the", "specified", "property" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zfs.py#L528-L572
train
saltstack/salt
salt/modules/zfs.py
diff
def diff(name_a, name_b=None, **kwargs): ''' Display the difference between a snapshot of a given filesystem and another snapshot of that filesystem from a later time or the current contents of the filesystem. name_a : string name of snapshot name_b : string (optional) name of snapshot or filesystem show_changetime : boolean display the path's inode change time as the first column of output. (default = True) show_indication : boolean display an indication of the type of file. (default = True) parsable : boolean if true we don't parse the timestamp to a more readable date (default = True) .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zfs.diff myzpool/mydataset@yesterday myzpool/mydataset ''' ## Configure command # NOTE: initialize the defaults flags = ['-H'] target = [] # NOTE: set extra config from kwargs if kwargs.get('show_changetime', True): flags.append('-t') if kwargs.get('show_indication', True): flags.append('-F') # NOTE: update target target.append(name_a) if name_b: target.append(name_b) ## Diff filesystem/snapshot res = __salt__['cmd.run_all']( __utils__['zfs.zfs_command']( command='diff', flags=flags, target=target, ), python_shell=False, ) if res['retcode'] != 0: return __utils__['zfs.parse_command_result'](res) else: if not kwargs.get('parsable', True) and kwargs.get('show_changetime', True): ret = OrderedDict() for entry in res['stdout'].splitlines(): entry = entry.split() entry_timestamp = __utils__['dateutils.strftime'](entry[0], '%Y-%m-%d.%H:%M:%S.%f') entry_data = "\t\t".join(entry[1:]) ret[entry_timestamp] = entry_data else: ret = res['stdout'].splitlines() return ret
python
def diff(name_a, name_b=None, **kwargs): ''' Display the difference between a snapshot of a given filesystem and another snapshot of that filesystem from a later time or the current contents of the filesystem. name_a : string name of snapshot name_b : string (optional) name of snapshot or filesystem show_changetime : boolean display the path's inode change time as the first column of output. (default = True) show_indication : boolean display an indication of the type of file. (default = True) parsable : boolean if true we don't parse the timestamp to a more readable date (default = True) .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zfs.diff myzpool/mydataset@yesterday myzpool/mydataset ''' ## Configure command # NOTE: initialize the defaults flags = ['-H'] target = [] # NOTE: set extra config from kwargs if kwargs.get('show_changetime', True): flags.append('-t') if kwargs.get('show_indication', True): flags.append('-F') # NOTE: update target target.append(name_a) if name_b: target.append(name_b) ## Diff filesystem/snapshot res = __salt__['cmd.run_all']( __utils__['zfs.zfs_command']( command='diff', flags=flags, target=target, ), python_shell=False, ) if res['retcode'] != 0: return __utils__['zfs.parse_command_result'](res) else: if not kwargs.get('parsable', True) and kwargs.get('show_changetime', True): ret = OrderedDict() for entry in res['stdout'].splitlines(): entry = entry.split() entry_timestamp = __utils__['dateutils.strftime'](entry[0], '%Y-%m-%d.%H:%M:%S.%f') entry_data = "\t\t".join(entry[1:]) ret[entry_timestamp] = entry_data else: ret = res['stdout'].splitlines() return ret
[ "def", "diff", "(", "name_a", ",", "name_b", "=", "None", ",", "*", "*", "kwargs", ")", ":", "## Configure command", "# NOTE: initialize the defaults", "flags", "=", "[", "'-H'", "]", "target", "=", "[", "]", "# NOTE: set extra config from kwargs", "if", "kwargs...
Display the difference between a snapshot of a given filesystem and another snapshot of that filesystem from a later time or the current contents of the filesystem. name_a : string name of snapshot name_b : string (optional) name of snapshot or filesystem show_changetime : boolean display the path's inode change time as the first column of output. (default = True) show_indication : boolean display an indication of the type of file. (default = True) parsable : boolean if true we don't parse the timestamp to a more readable date (default = True) .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zfs.diff myzpool/mydataset@yesterday myzpool/mydataset
[ "Display", "the", "difference", "between", "a", "snapshot", "of", "a", "given", "filesystem", "and", "another", "snapshot", "of", "that", "filesystem", "from", "a", "later", "time", "or", "the", "current", "contents", "of", "the", "filesystem", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zfs.py#L575-L639
train
saltstack/salt
salt/modules/zfs.py
rollback
def rollback(name, **kwargs): ''' Roll back the given dataset to a previous snapshot. name : string name of snapshot recursive : boolean destroy any snapshots and bookmarks more recent than the one specified. recursive_all : boolean destroy any more recent snapshots and bookmarks, as well as any clones of those snapshots. force : boolean used with the -R option to force an unmount of any clone file systems that are to be destroyed. .. warning:: When a dataset is rolled back, all data that has changed since the snapshot is discarded, and the dataset reverts to the state at the time of the snapshot. By default, the command refuses to roll back to a snapshot other than the most recent one. In order to do so, all intermediate snapshots and bookmarks must be destroyed by specifying the -r option. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zfs.rollback myzpool/mydataset@yesterday ''' ## Configure command # NOTE: initialize the defaults flags = [] # NOTE: set extra config from kwargs if kwargs.get('recursive_all', False): flags.append('-R') if kwargs.get('recursive', False): flags.append('-r') if kwargs.get('force', False): if kwargs.get('recursive_all', False) or kwargs.get('recursive', False): flags.append('-f') else: log.warning('zfs.rollback - force=True can only be used with recursive_all=True or recursive=True') ## Rollback to snapshot res = __salt__['cmd.run_all']( __utils__['zfs.zfs_command']( command='rollback', flags=flags, target=name, ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'rolledback')
python
def rollback(name, **kwargs): ''' Roll back the given dataset to a previous snapshot. name : string name of snapshot recursive : boolean destroy any snapshots and bookmarks more recent than the one specified. recursive_all : boolean destroy any more recent snapshots and bookmarks, as well as any clones of those snapshots. force : boolean used with the -R option to force an unmount of any clone file systems that are to be destroyed. .. warning:: When a dataset is rolled back, all data that has changed since the snapshot is discarded, and the dataset reverts to the state at the time of the snapshot. By default, the command refuses to roll back to a snapshot other than the most recent one. In order to do so, all intermediate snapshots and bookmarks must be destroyed by specifying the -r option. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zfs.rollback myzpool/mydataset@yesterday ''' ## Configure command # NOTE: initialize the defaults flags = [] # NOTE: set extra config from kwargs if kwargs.get('recursive_all', False): flags.append('-R') if kwargs.get('recursive', False): flags.append('-r') if kwargs.get('force', False): if kwargs.get('recursive_all', False) or kwargs.get('recursive', False): flags.append('-f') else: log.warning('zfs.rollback - force=True can only be used with recursive_all=True or recursive=True') ## Rollback to snapshot res = __salt__['cmd.run_all']( __utils__['zfs.zfs_command']( command='rollback', flags=flags, target=name, ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'rolledback')
[ "def", "rollback", "(", "name", ",", "*", "*", "kwargs", ")", ":", "## Configure command", "# NOTE: initialize the defaults", "flags", "=", "[", "]", "# NOTE: set extra config from kwargs", "if", "kwargs", ".", "get", "(", "'recursive_all'", ",", "False", ")", ":"...
Roll back the given dataset to a previous snapshot. name : string name of snapshot recursive : boolean destroy any snapshots and bookmarks more recent than the one specified. recursive_all : boolean destroy any more recent snapshots and bookmarks, as well as any clones of those snapshots. force : boolean used with the -R option to force an unmount of any clone file systems that are to be destroyed. .. warning:: When a dataset is rolled back, all data that has changed since the snapshot is discarded, and the dataset reverts to the state at the time of the snapshot. By default, the command refuses to roll back to a snapshot other than the most recent one. In order to do so, all intermediate snapshots and bookmarks must be destroyed by specifying the -r option. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zfs.rollback myzpool/mydataset@yesterday
[ "Roll", "back", "the", "given", "dataset", "to", "a", "previous", "snapshot", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zfs.py#L642-L702
train
saltstack/salt
salt/modules/zfs.py
clone
def clone(name_a, name_b, **kwargs): ''' Creates a clone of the given snapshot. name_a : string name of snapshot name_b : string name of filesystem or volume create_parent : boolean creates all the non-existing parent datasets. any property specified on the command line using the -o option is ignored. properties : dict additional zfs properties (-o) .. note:: ZFS properties can be specified at the time of creation of the filesystem by passing an additional argument called "properties" and specifying the properties with their respective values in the form of a python dictionary:: properties="{'property1': 'value1', 'property2': 'value2'}" .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zfs.clone myzpool/mydataset@yesterday myzpool/mydataset_yesterday ''' ## Configure command # NOTE: initialize the defaults flags = [] target = [] # NOTE: push filesystem properties filesystem_properties = kwargs.get('properties', {}) # NOTE: set extra config from kwargs if kwargs.get('create_parent', False): flags.append('-p') # NOTE: update target target.append(name_a) target.append(name_b) ## Clone filesystem/volume res = __salt__['cmd.run_all']( __utils__['zfs.zfs_command']( command='clone', flags=flags, filesystem_properties=filesystem_properties, target=target, ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'cloned')
python
def clone(name_a, name_b, **kwargs): ''' Creates a clone of the given snapshot. name_a : string name of snapshot name_b : string name of filesystem or volume create_parent : boolean creates all the non-existing parent datasets. any property specified on the command line using the -o option is ignored. properties : dict additional zfs properties (-o) .. note:: ZFS properties can be specified at the time of creation of the filesystem by passing an additional argument called "properties" and specifying the properties with their respective values in the form of a python dictionary:: properties="{'property1': 'value1', 'property2': 'value2'}" .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zfs.clone myzpool/mydataset@yesterday myzpool/mydataset_yesterday ''' ## Configure command # NOTE: initialize the defaults flags = [] target = [] # NOTE: push filesystem properties filesystem_properties = kwargs.get('properties', {}) # NOTE: set extra config from kwargs if kwargs.get('create_parent', False): flags.append('-p') # NOTE: update target target.append(name_a) target.append(name_b) ## Clone filesystem/volume res = __salt__['cmd.run_all']( __utils__['zfs.zfs_command']( command='clone', flags=flags, filesystem_properties=filesystem_properties, target=target, ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'cloned')
[ "def", "clone", "(", "name_a", ",", "name_b", ",", "*", "*", "kwargs", ")", ":", "## Configure command", "# NOTE: initialize the defaults", "flags", "=", "[", "]", "target", "=", "[", "]", "# NOTE: push filesystem properties", "filesystem_properties", "=", "kwargs",...
Creates a clone of the given snapshot. name_a : string name of snapshot name_b : string name of filesystem or volume create_parent : boolean creates all the non-existing parent datasets. any property specified on the command line using the -o option is ignored. properties : dict additional zfs properties (-o) .. note:: ZFS properties can be specified at the time of creation of the filesystem by passing an additional argument called "properties" and specifying the properties with their respective values in the form of a python dictionary:: properties="{'property1': 'value1', 'property2': 'value2'}" .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zfs.clone myzpool/mydataset@yesterday myzpool/mydataset_yesterday
[ "Creates", "a", "clone", "of", "the", "given", "snapshot", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zfs.py#L705-L763
train
saltstack/salt
salt/modules/zfs.py
promote
def promote(name): ''' Promotes a clone file system to no longer be dependent on its "origin" snapshot. .. note:: This makes it possible to destroy the file system that the clone was created from. The clone parent-child dependency relationship is reversed, so that the origin file system becomes a clone of the specified file system. The snapshot that was cloned, and any snapshots previous to this snapshot, are now owned by the promoted clone. The space they use moves from the origin file system to the promoted clone, so enough space must be available to accommodate these snapshots. No new space is consumed by this operation, but the space accounting is adjusted. The promoted clone must not have any conflicting snapshot names of its own. The rename subcommand can be used to rename any conflicting snapshots. name : string name of clone-filesystem .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zfs.promote myzpool/myclone ''' ## Promote clone res = __salt__['cmd.run_all']( __utils__['zfs.zfs_command']( command='promote', target=name, ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'promoted')
python
def promote(name): ''' Promotes a clone file system to no longer be dependent on its "origin" snapshot. .. note:: This makes it possible to destroy the file system that the clone was created from. The clone parent-child dependency relationship is reversed, so that the origin file system becomes a clone of the specified file system. The snapshot that was cloned, and any snapshots previous to this snapshot, are now owned by the promoted clone. The space they use moves from the origin file system to the promoted clone, so enough space must be available to accommodate these snapshots. No new space is consumed by this operation, but the space accounting is adjusted. The promoted clone must not have any conflicting snapshot names of its own. The rename subcommand can be used to rename any conflicting snapshots. name : string name of clone-filesystem .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zfs.promote myzpool/myclone ''' ## Promote clone res = __salt__['cmd.run_all']( __utils__['zfs.zfs_command']( command='promote', target=name, ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'promoted')
[ "def", "promote", "(", "name", ")", ":", "## Promote clone", "res", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "__utils__", "[", "'zfs.zfs_command'", "]", "(", "command", "=", "'promote'", ",", "target", "=", "name", ",", ")", ",", "python_shell", "=...
Promotes a clone file system to no longer be dependent on its "origin" snapshot. .. note:: This makes it possible to destroy the file system that the clone was created from. The clone parent-child dependency relationship is reversed, so that the origin file system becomes a clone of the specified file system. The snapshot that was cloned, and any snapshots previous to this snapshot, are now owned by the promoted clone. The space they use moves from the origin file system to the promoted clone, so enough space must be available to accommodate these snapshots. No new space is consumed by this operation, but the space accounting is adjusted. The promoted clone must not have any conflicting snapshot names of its own. The rename subcommand can be used to rename any conflicting snapshots. name : string name of clone-filesystem .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zfs.promote myzpool/myclone
[ "Promotes", "a", "clone", "file", "system", "to", "no", "longer", "be", "dependent", "on", "its", "origin", "snapshot", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zfs.py#L766-L807
train
saltstack/salt
salt/modules/zfs.py
bookmark
def bookmark(snapshot, bookmark): ''' Creates a bookmark of the given snapshot .. note:: Bookmarks mark the point in time when the snapshot was created, and can be used as the incremental source for a zfs send command. This feature must be enabled to be used. See zpool-features(5) for details on ZFS feature flags and the bookmarks feature. snapshot : string name of snapshot to bookmark bookmark : string name of bookmark .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zfs.bookmark myzpool/mydataset@yesterday myzpool/mydataset#complete ''' # abort if we do not have feature flags if not __utils__['zfs.has_feature_flags'](): return OrderedDict([('error', 'bookmarks are not supported')]) ## Configure command # NOTE: initialize the defaults target = [] # NOTE: update target target.append(snapshot) target.append(bookmark) ## Bookmark snapshot res = __salt__['cmd.run_all']( __utils__['zfs.zfs_command']( command='bookmark', target=target, ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'bookmarked')
python
def bookmark(snapshot, bookmark): ''' Creates a bookmark of the given snapshot .. note:: Bookmarks mark the point in time when the snapshot was created, and can be used as the incremental source for a zfs send command. This feature must be enabled to be used. See zpool-features(5) for details on ZFS feature flags and the bookmarks feature. snapshot : string name of snapshot to bookmark bookmark : string name of bookmark .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zfs.bookmark myzpool/mydataset@yesterday myzpool/mydataset#complete ''' # abort if we do not have feature flags if not __utils__['zfs.has_feature_flags'](): return OrderedDict([('error', 'bookmarks are not supported')]) ## Configure command # NOTE: initialize the defaults target = [] # NOTE: update target target.append(snapshot) target.append(bookmark) ## Bookmark snapshot res = __salt__['cmd.run_all']( __utils__['zfs.zfs_command']( command='bookmark', target=target, ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'bookmarked')
[ "def", "bookmark", "(", "snapshot", ",", "bookmark", ")", ":", "# abort if we do not have feature flags", "if", "not", "__utils__", "[", "'zfs.has_feature_flags'", "]", "(", ")", ":", "return", "OrderedDict", "(", "[", "(", "'error'", ",", "'bookmarks are not suppor...
Creates a bookmark of the given snapshot .. note:: Bookmarks mark the point in time when the snapshot was created, and can be used as the incremental source for a zfs send command. This feature must be enabled to be used. See zpool-features(5) for details on ZFS feature flags and the bookmarks feature. snapshot : string name of snapshot to bookmark bookmark : string name of bookmark .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zfs.bookmark myzpool/mydataset@yesterday myzpool/mydataset#complete
[ "Creates", "a", "bookmark", "of", "the", "given", "snapshot" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zfs.py#L810-L857
train
saltstack/salt
salt/modules/zfs.py
holds
def holds(snapshot, **kwargs): ''' Lists all existing user references for the given snapshot or snapshots. snapshot : string name of snapshot recursive : boolean lists the holds that are set on the named descendent snapshots also. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zfs.holds myzpool/mydataset@baseline ''' ## Configure command # NOTE: initialize the defaults flags = ['-H'] target = [] # NOTE: set extra config from kwargs if kwargs.get('recursive', False): flags.append('-r') # NOTE: update target target.append(snapshot) ## Lookup holds res = __salt__['cmd.run_all']( __utils__['zfs.zfs_command']( command='holds', flags=flags, target=target, ), python_shell=False, ) ret = __utils__['zfs.parse_command_result'](res) if res['retcode'] == 0: for hold in res['stdout'].splitlines(): hold_data = OrderedDict(list(zip( ['name', 'tag', 'timestamp'], hold.split("\t"), ))) ret[hold_data['tag'].strip()] = hold_data['timestamp'] return ret
python
def holds(snapshot, **kwargs): ''' Lists all existing user references for the given snapshot or snapshots. snapshot : string name of snapshot recursive : boolean lists the holds that are set on the named descendent snapshots also. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zfs.holds myzpool/mydataset@baseline ''' ## Configure command # NOTE: initialize the defaults flags = ['-H'] target = [] # NOTE: set extra config from kwargs if kwargs.get('recursive', False): flags.append('-r') # NOTE: update target target.append(snapshot) ## Lookup holds res = __salt__['cmd.run_all']( __utils__['zfs.zfs_command']( command='holds', flags=flags, target=target, ), python_shell=False, ) ret = __utils__['zfs.parse_command_result'](res) if res['retcode'] == 0: for hold in res['stdout'].splitlines(): hold_data = OrderedDict(list(zip( ['name', 'tag', 'timestamp'], hold.split("\t"), ))) ret[hold_data['tag'].strip()] = hold_data['timestamp'] return ret
[ "def", "holds", "(", "snapshot", ",", "*", "*", "kwargs", ")", ":", "## Configure command", "# NOTE: initialize the defaults", "flags", "=", "[", "'-H'", "]", "target", "=", "[", "]", "# NOTE: set extra config from kwargs", "if", "kwargs", ".", "get", "(", "'rec...
Lists all existing user references for the given snapshot or snapshots. snapshot : string name of snapshot recursive : boolean lists the holds that are set on the named descendent snapshots also. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zfs.holds myzpool/mydataset@baseline
[ "Lists", "all", "existing", "user", "references", "for", "the", "given", "snapshot", "or", "snapshots", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zfs.py#L860-L909
train
saltstack/salt
salt/modules/zfs.py
hold
def hold(tag, *snapshot, **kwargs): ''' Adds a single reference, named with the tag argument, to the specified snapshot or snapshots. .. note:: Each snapshot has its own tag namespace, and tags must be unique within that space. If a hold exists on a snapshot, attempts to destroy that snapshot by using the zfs destroy command return EBUSY. tag : string name of tag snapshot : string name of snapshot(s) recursive : boolean specifies that a hold with the given tag is applied recursively to the snapshots of all descendent file systems. .. versionadded:: 2016.3.0 .. versionchanged:: 2018.3.1 .. warning:: As of 2018.3.1 the tag parameter no longer accepts a comma-separated value. It's is now possible to create a tag that contains a comma, this was impossible before. CLI Example: .. code-block:: bash salt '*' zfs.hold mytag myzpool/mydataset@mysnapshot [recursive=True] salt '*' zfs.hold mytag myzpool/mydataset@mysnapshot myzpool/mydataset@myothersnapshot ''' ## warn about tag change if ',' in tag: salt.utils.versions.warn_until( 'Sodium', 'A comma-separated tag is no support as of Salt 2018.3.1 ' 'This warning will be removed in Salt Sodium.') ## Configure command # NOTE: initialize the defaults flags = [] target = [] # NOTE: set extra config from kwargs if kwargs.get('recursive', False): flags.append('-r') # NOTE: update target target.append(tag) target.extend(snapshot) ## hold snapshot res = __salt__['cmd.run_all']( __utils__['zfs.zfs_command']( command='hold', flags=flags, target=target, ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'held')
python
def hold(tag, *snapshot, **kwargs): ''' Adds a single reference, named with the tag argument, to the specified snapshot or snapshots. .. note:: Each snapshot has its own tag namespace, and tags must be unique within that space. If a hold exists on a snapshot, attempts to destroy that snapshot by using the zfs destroy command return EBUSY. tag : string name of tag snapshot : string name of snapshot(s) recursive : boolean specifies that a hold with the given tag is applied recursively to the snapshots of all descendent file systems. .. versionadded:: 2016.3.0 .. versionchanged:: 2018.3.1 .. warning:: As of 2018.3.1 the tag parameter no longer accepts a comma-separated value. It's is now possible to create a tag that contains a comma, this was impossible before. CLI Example: .. code-block:: bash salt '*' zfs.hold mytag myzpool/mydataset@mysnapshot [recursive=True] salt '*' zfs.hold mytag myzpool/mydataset@mysnapshot myzpool/mydataset@myothersnapshot ''' ## warn about tag change if ',' in tag: salt.utils.versions.warn_until( 'Sodium', 'A comma-separated tag is no support as of Salt 2018.3.1 ' 'This warning will be removed in Salt Sodium.') ## Configure command # NOTE: initialize the defaults flags = [] target = [] # NOTE: set extra config from kwargs if kwargs.get('recursive', False): flags.append('-r') # NOTE: update target target.append(tag) target.extend(snapshot) ## hold snapshot res = __salt__['cmd.run_all']( __utils__['zfs.zfs_command']( command='hold', flags=flags, target=target, ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'held')
[ "def", "hold", "(", "tag", ",", "*", "snapshot", ",", "*", "*", "kwargs", ")", ":", "## warn about tag change", "if", "','", "in", "tag", ":", "salt", ".", "utils", ".", "versions", ".", "warn_until", "(", "'Sodium'", ",", "'A comma-separated tag is no suppo...
Adds a single reference, named with the tag argument, to the specified snapshot or snapshots. .. note:: Each snapshot has its own tag namespace, and tags must be unique within that space. If a hold exists on a snapshot, attempts to destroy that snapshot by using the zfs destroy command return EBUSY. tag : string name of tag snapshot : string name of snapshot(s) recursive : boolean specifies that a hold with the given tag is applied recursively to the snapshots of all descendent file systems. .. versionadded:: 2016.3.0 .. versionchanged:: 2018.3.1 .. warning:: As of 2018.3.1 the tag parameter no longer accepts a comma-separated value. It's is now possible to create a tag that contains a comma, this was impossible before. CLI Example: .. code-block:: bash salt '*' zfs.hold mytag myzpool/mydataset@mysnapshot [recursive=True] salt '*' zfs.hold mytag myzpool/mydataset@mysnapshot myzpool/mydataset@myothersnapshot
[ "Adds", "a", "single", "reference", "named", "with", "the", "tag", "argument", "to", "the", "specified", "snapshot", "or", "snapshots", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zfs.py#L912-L978
train
saltstack/salt
salt/modules/zfs.py
snapshot
def snapshot(*snapshot, **kwargs): ''' Creates snapshots with the given names. snapshot : string name of snapshot(s) recursive : boolean recursively create snapshots of all descendent datasets. properties : dict additional zfs properties (-o) .. note:: ZFS properties can be specified at the time of creation of the filesystem by passing an additional argument called "properties" and specifying the properties with their respective values in the form of a python dictionary:: properties="{'property1': 'value1', 'property2': 'value2'}" .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zfs.snapshot myzpool/mydataset@yesterday [recursive=True] salt '*' zfs.snapshot myzpool/mydataset@yesterday myzpool/myotherdataset@yesterday [recursive=True] ''' ## Configure command # NOTE: initialize the defaults flags = [] # NOTE: push filesystem properties filesystem_properties = kwargs.get('properties', {}) # NOTE: set extra config from kwargs if kwargs.get('recursive', False): flags.append('-r') ## Create snapshot res = __salt__['cmd.run_all']( __utils__['zfs.zfs_command']( command='snapshot', flags=flags, filesystem_properties=filesystem_properties, target=list(snapshot), ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'snapshotted')
python
def snapshot(*snapshot, **kwargs): ''' Creates snapshots with the given names. snapshot : string name of snapshot(s) recursive : boolean recursively create snapshots of all descendent datasets. properties : dict additional zfs properties (-o) .. note:: ZFS properties can be specified at the time of creation of the filesystem by passing an additional argument called "properties" and specifying the properties with their respective values in the form of a python dictionary:: properties="{'property1': 'value1', 'property2': 'value2'}" .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zfs.snapshot myzpool/mydataset@yesterday [recursive=True] salt '*' zfs.snapshot myzpool/mydataset@yesterday myzpool/myotherdataset@yesterday [recursive=True] ''' ## Configure command # NOTE: initialize the defaults flags = [] # NOTE: push filesystem properties filesystem_properties = kwargs.get('properties', {}) # NOTE: set extra config from kwargs if kwargs.get('recursive', False): flags.append('-r') ## Create snapshot res = __salt__['cmd.run_all']( __utils__['zfs.zfs_command']( command='snapshot', flags=flags, filesystem_properties=filesystem_properties, target=list(snapshot), ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'snapshotted')
[ "def", "snapshot", "(", "*", "snapshot", ",", "*", "*", "kwargs", ")", ":", "## Configure command", "# NOTE: initialize the defaults", "flags", "=", "[", "]", "# NOTE: push filesystem properties", "filesystem_properties", "=", "kwargs", ".", "get", "(", "'properties'"...
Creates snapshots with the given names. snapshot : string name of snapshot(s) recursive : boolean recursively create snapshots of all descendent datasets. properties : dict additional zfs properties (-o) .. note:: ZFS properties can be specified at the time of creation of the filesystem by passing an additional argument called "properties" and specifying the properties with their respective values in the form of a python dictionary:: properties="{'property1': 'value1', 'property2': 'value2'}" .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zfs.snapshot myzpool/mydataset@yesterday [recursive=True] salt '*' zfs.snapshot myzpool/mydataset@yesterday myzpool/myotherdataset@yesterday [recursive=True]
[ "Creates", "snapshots", "with", "the", "given", "names", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zfs.py#L1049-L1100
train
saltstack/salt
salt/modules/zfs.py
set
def set(*dataset, **kwargs): ''' Sets the property or list of properties to the given value(s) for each dataset. dataset : string name of snapshot(s), filesystem(s), or volume(s) properties : string additional zfs properties pairs .. note:: properties are passed as key-value pairs. e.g. compression=off .. note:: Only some properties can be edited. See the Properties section for more information on what properties can be set and acceptable values. Numeric values can be specified as exact values, or in a human-readable form with a suffix of B, K, M, G, T, P, E (for bytes, kilobytes, megabytes, gigabytes, terabytes, petabytes, or exabytes respectively). .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zfs.set myzpool/mydataset compression=off salt '*' zfs.set myzpool/mydataset myzpool/myotherdataset compression=off salt '*' zfs.set myzpool/mydataset myzpool/myotherdataset compression=lz4 canmount=off ''' ## Configure command # NOTE: push filesystem properties filesystem_properties = salt.utils.args.clean_kwargs(**kwargs) ## Set property res = __salt__['cmd.run_all']( __utils__['zfs.zfs_command']( command='set', property_name=filesystem_properties.keys(), property_value=filesystem_properties.values(), target=list(dataset), ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'set')
python
def set(*dataset, **kwargs): ''' Sets the property or list of properties to the given value(s) for each dataset. dataset : string name of snapshot(s), filesystem(s), or volume(s) properties : string additional zfs properties pairs .. note:: properties are passed as key-value pairs. e.g. compression=off .. note:: Only some properties can be edited. See the Properties section for more information on what properties can be set and acceptable values. Numeric values can be specified as exact values, or in a human-readable form with a suffix of B, K, M, G, T, P, E (for bytes, kilobytes, megabytes, gigabytes, terabytes, petabytes, or exabytes respectively). .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zfs.set myzpool/mydataset compression=off salt '*' zfs.set myzpool/mydataset myzpool/myotherdataset compression=off salt '*' zfs.set myzpool/mydataset myzpool/myotherdataset compression=lz4 canmount=off ''' ## Configure command # NOTE: push filesystem properties filesystem_properties = salt.utils.args.clean_kwargs(**kwargs) ## Set property res = __salt__['cmd.run_all']( __utils__['zfs.zfs_command']( command='set', property_name=filesystem_properties.keys(), property_value=filesystem_properties.values(), target=list(dataset), ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'set')
[ "def", "set", "(", "*", "dataset", ",", "*", "*", "kwargs", ")", ":", "## Configure command", "# NOTE: push filesystem properties", "filesystem_properties", "=", "salt", ".", "utils", ".", "args", ".", "clean_kwargs", "(", "*", "*", "kwargs", ")", "## Set proper...
Sets the property or list of properties to the given value(s) for each dataset. dataset : string name of snapshot(s), filesystem(s), or volume(s) properties : string additional zfs properties pairs .. note:: properties are passed as key-value pairs. e.g. compression=off .. note:: Only some properties can be edited. See the Properties section for more information on what properties can be set and acceptable values. Numeric values can be specified as exact values, or in a human-readable form with a suffix of B, K, M, G, T, P, E (for bytes, kilobytes, megabytes, gigabytes, terabytes, petabytes, or exabytes respectively). .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zfs.set myzpool/mydataset compression=off salt '*' zfs.set myzpool/mydataset myzpool/myotherdataset compression=off salt '*' zfs.set myzpool/mydataset myzpool/myotherdataset compression=lz4 canmount=off
[ "Sets", "the", "property", "or", "list", "of", "properties", "to", "the", "given", "value", "(", "s", ")", "for", "each", "dataset", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zfs.py#L1103-L1155
train
saltstack/salt
salt/modules/zfs.py
get
def get(*dataset, **kwargs): ''' Displays properties for the given datasets. dataset : string name of snapshot(s), filesystem(s), or volume(s) properties : string comma-separated list of properties to list, defaults to all recursive : boolean recursively list children depth : int recursively list children to depth fields : string comma-separated list of fields to include, the name and property field will always be added type : string comma-separated list of types to display, where type is one of filesystem, snapshot, volume, bookmark, or all. source : string comma-separated list of sources to display. Must be one of the following: local, default, inherited, temporary, and none. The default value is all sources. parsable : boolean display numbers in parsable (exact) values (default = True) .. versionadded:: 2018.3.0 .. note:: If no datasets are specified, then the command displays properties for all datasets on the system. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zfs.get salt '*' zfs.get myzpool/mydataset [recursive=True|False] salt '*' zfs.get myzpool/mydataset properties="sharenfs,mountpoint" [recursive=True|False] salt '*' zfs.get myzpool/mydataset myzpool/myotherdataset properties=available fields=value depth=1 ''' ## Configure command # NOTE: initialize the defaults flags = ['-H'] opts = {} # NOTE: set extra config from kwargs if kwargs.get('depth', False): opts['-d'] = kwargs.get('depth') elif kwargs.get('recursive', False): flags.append('-r') fields = kwargs.get('fields', 'value,source').split(',') if 'name' in fields: # ensure name is first fields.remove('name') if 'property' in fields: # ensure property is second fields.remove('property') fields.insert(0, 'name') fields.insert(1, 'property') opts['-o'] = ",".join(fields) if kwargs.get('type', False): opts['-t'] = kwargs.get('type') if kwargs.get('source', False): opts['-s'] = kwargs.get('source') # NOTE: set property_name property_name = kwargs.get('properties', 'all') ## Get properties res = __salt__['cmd.run_all']( __utils__['zfs.zfs_command']( command='get', flags=flags, opts=opts, property_name=property_name, target=list(dataset), ), python_shell=False, ) ret = __utils__['zfs.parse_command_result'](res) if res['retcode'] == 0: for ds in res['stdout'].splitlines(): ds_data = OrderedDict(list(zip( fields, ds.split("\t") ))) if 'value' in ds_data: if kwargs.get('parsable', True): ds_data['value'] = __utils__['zfs.from_auto']( ds_data['property'], ds_data['value'], ) else: ds_data['value'] = __utils__['zfs.to_auto']( ds_data['property'], ds_data['value'], convert_to_human=True, ) if ds_data['name'] not in ret: ret[ds_data['name']] = OrderedDict() ret[ds_data['name']][ds_data['property']] = ds_data del ds_data['name'] del ds_data['property'] return ret
python
def get(*dataset, **kwargs): ''' Displays properties for the given datasets. dataset : string name of snapshot(s), filesystem(s), or volume(s) properties : string comma-separated list of properties to list, defaults to all recursive : boolean recursively list children depth : int recursively list children to depth fields : string comma-separated list of fields to include, the name and property field will always be added type : string comma-separated list of types to display, where type is one of filesystem, snapshot, volume, bookmark, or all. source : string comma-separated list of sources to display. Must be one of the following: local, default, inherited, temporary, and none. The default value is all sources. parsable : boolean display numbers in parsable (exact) values (default = True) .. versionadded:: 2018.3.0 .. note:: If no datasets are specified, then the command displays properties for all datasets on the system. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zfs.get salt '*' zfs.get myzpool/mydataset [recursive=True|False] salt '*' zfs.get myzpool/mydataset properties="sharenfs,mountpoint" [recursive=True|False] salt '*' zfs.get myzpool/mydataset myzpool/myotherdataset properties=available fields=value depth=1 ''' ## Configure command # NOTE: initialize the defaults flags = ['-H'] opts = {} # NOTE: set extra config from kwargs if kwargs.get('depth', False): opts['-d'] = kwargs.get('depth') elif kwargs.get('recursive', False): flags.append('-r') fields = kwargs.get('fields', 'value,source').split(',') if 'name' in fields: # ensure name is first fields.remove('name') if 'property' in fields: # ensure property is second fields.remove('property') fields.insert(0, 'name') fields.insert(1, 'property') opts['-o'] = ",".join(fields) if kwargs.get('type', False): opts['-t'] = kwargs.get('type') if kwargs.get('source', False): opts['-s'] = kwargs.get('source') # NOTE: set property_name property_name = kwargs.get('properties', 'all') ## Get properties res = __salt__['cmd.run_all']( __utils__['zfs.zfs_command']( command='get', flags=flags, opts=opts, property_name=property_name, target=list(dataset), ), python_shell=False, ) ret = __utils__['zfs.parse_command_result'](res) if res['retcode'] == 0: for ds in res['stdout'].splitlines(): ds_data = OrderedDict(list(zip( fields, ds.split("\t") ))) if 'value' in ds_data: if kwargs.get('parsable', True): ds_data['value'] = __utils__['zfs.from_auto']( ds_data['property'], ds_data['value'], ) else: ds_data['value'] = __utils__['zfs.to_auto']( ds_data['property'], ds_data['value'], convert_to_human=True, ) if ds_data['name'] not in ret: ret[ds_data['name']] = OrderedDict() ret[ds_data['name']][ds_data['property']] = ds_data del ds_data['name'] del ds_data['property'] return ret
[ "def", "get", "(", "*", "dataset", ",", "*", "*", "kwargs", ")", ":", "## Configure command", "# NOTE: initialize the defaults", "flags", "=", "[", "'-H'", "]", "opts", "=", "{", "}", "# NOTE: set extra config from kwargs", "if", "kwargs", ".", "get", "(", "'d...
Displays properties for the given datasets. dataset : string name of snapshot(s), filesystem(s), or volume(s) properties : string comma-separated list of properties to list, defaults to all recursive : boolean recursively list children depth : int recursively list children to depth fields : string comma-separated list of fields to include, the name and property field will always be added type : string comma-separated list of types to display, where type is one of filesystem, snapshot, volume, bookmark, or all. source : string comma-separated list of sources to display. Must be one of the following: local, default, inherited, temporary, and none. The default value is all sources. parsable : boolean display numbers in parsable (exact) values (default = True) .. versionadded:: 2018.3.0 .. note:: If no datasets are specified, then the command displays properties for all datasets on the system. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zfs.get salt '*' zfs.get myzpool/mydataset [recursive=True|False] salt '*' zfs.get myzpool/mydataset properties="sharenfs,mountpoint" [recursive=True|False] salt '*' zfs.get myzpool/mydataset myzpool/myotherdataset properties=available fields=value depth=1
[ "Displays", "properties", "for", "the", "given", "datasets", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zfs.py#L1158-L1264
train
saltstack/salt
salt/utils/versions.py
warn_until
def warn_until(version, message, category=DeprecationWarning, stacklevel=None, _version_info_=None, _dont_call_warnings=False): ''' Helper function to raise a warning, by default, a ``DeprecationWarning``, until the provided ``version``, after which, a ``RuntimeError`` will be raised to remind the developers to remove the warning because the target version has been reached. :param version: The version info or name after which the warning becomes a ``RuntimeError``. For example ``(0, 17)`` or ``Hydrogen`` or an instance of :class:`salt.version.SaltStackVersion`. :param message: The warning message to be displayed. :param category: The warning class to be thrown, by default ``DeprecationWarning`` :param stacklevel: There should be no need to set the value of ``stacklevel``. Salt should be able to do the right thing. :param _version_info_: In order to reuse this function for other SaltStack projects, they need to be able to provide the version info to compare to. :param _dont_call_warnings: This parameter is used just to get the functionality until the actual error is to be issued. When we're only after the salt version checks to raise a ``RuntimeError``. ''' if not isinstance(version, (tuple, six.string_types, salt.version.SaltStackVersion)): raise RuntimeError( 'The \'version\' argument should be passed as a tuple, string or ' 'an instance of \'salt.version.SaltStackVersion\'.' ) elif isinstance(version, tuple): version = salt.version.SaltStackVersion(*version) elif isinstance(version, six.string_types): version = salt.version.SaltStackVersion.from_name(version) if stacklevel is None: # Attribute the warning to the calling function, not to warn_until() stacklevel = 2 if _version_info_ is None: _version_info_ = salt.version.__version_info__ _version_ = salt.version.SaltStackVersion(*_version_info_) if _version_ >= version: import inspect caller = inspect.getframeinfo(sys._getframe(stacklevel - 1)) raise RuntimeError( 'The warning triggered on filename \'{filename}\', line number ' '{lineno}, is supposed to be shown until version ' '{until_version} is released. Current version is now ' '{salt_version}. Please remove the warning.'.format( filename=caller.filename, lineno=caller.lineno, until_version=version.formatted_version, salt_version=_version_.formatted_version ), ) if _dont_call_warnings is False: def _formatwarning(message, category, filename, lineno, line=None): # pylint: disable=W0613 ''' Replacement for warnings.formatwarning that disables the echoing of the 'line' parameter. ''' return '{0}:{1}: {2}: {3}\n'.format( filename, lineno, category.__name__, message ) saved = warnings.formatwarning warnings.formatwarning = _formatwarning warnings.warn( message.format(version=version.formatted_version), category, stacklevel=stacklevel ) warnings.formatwarning = saved
python
def warn_until(version, message, category=DeprecationWarning, stacklevel=None, _version_info_=None, _dont_call_warnings=False): ''' Helper function to raise a warning, by default, a ``DeprecationWarning``, until the provided ``version``, after which, a ``RuntimeError`` will be raised to remind the developers to remove the warning because the target version has been reached. :param version: The version info or name after which the warning becomes a ``RuntimeError``. For example ``(0, 17)`` or ``Hydrogen`` or an instance of :class:`salt.version.SaltStackVersion`. :param message: The warning message to be displayed. :param category: The warning class to be thrown, by default ``DeprecationWarning`` :param stacklevel: There should be no need to set the value of ``stacklevel``. Salt should be able to do the right thing. :param _version_info_: In order to reuse this function for other SaltStack projects, they need to be able to provide the version info to compare to. :param _dont_call_warnings: This parameter is used just to get the functionality until the actual error is to be issued. When we're only after the salt version checks to raise a ``RuntimeError``. ''' if not isinstance(version, (tuple, six.string_types, salt.version.SaltStackVersion)): raise RuntimeError( 'The \'version\' argument should be passed as a tuple, string or ' 'an instance of \'salt.version.SaltStackVersion\'.' ) elif isinstance(version, tuple): version = salt.version.SaltStackVersion(*version) elif isinstance(version, six.string_types): version = salt.version.SaltStackVersion.from_name(version) if stacklevel is None: # Attribute the warning to the calling function, not to warn_until() stacklevel = 2 if _version_info_ is None: _version_info_ = salt.version.__version_info__ _version_ = salt.version.SaltStackVersion(*_version_info_) if _version_ >= version: import inspect caller = inspect.getframeinfo(sys._getframe(stacklevel - 1)) raise RuntimeError( 'The warning triggered on filename \'{filename}\', line number ' '{lineno}, is supposed to be shown until version ' '{until_version} is released. Current version is now ' '{salt_version}. Please remove the warning.'.format( filename=caller.filename, lineno=caller.lineno, until_version=version.formatted_version, salt_version=_version_.formatted_version ), ) if _dont_call_warnings is False: def _formatwarning(message, category, filename, lineno, line=None): # pylint: disable=W0613 ''' Replacement for warnings.formatwarning that disables the echoing of the 'line' parameter. ''' return '{0}:{1}: {2}: {3}\n'.format( filename, lineno, category.__name__, message ) saved = warnings.formatwarning warnings.formatwarning = _formatwarning warnings.warn( message.format(version=version.formatted_version), category, stacklevel=stacklevel ) warnings.formatwarning = saved
[ "def", "warn_until", "(", "version", ",", "message", ",", "category", "=", "DeprecationWarning", ",", "stacklevel", "=", "None", ",", "_version_info_", "=", "None", ",", "_dont_call_warnings", "=", "False", ")", ":", "if", "not", "isinstance", "(", "version", ...
Helper function to raise a warning, by default, a ``DeprecationWarning``, until the provided ``version``, after which, a ``RuntimeError`` will be raised to remind the developers to remove the warning because the target version has been reached. :param version: The version info or name after which the warning becomes a ``RuntimeError``. For example ``(0, 17)`` or ``Hydrogen`` or an instance of :class:`salt.version.SaltStackVersion`. :param message: The warning message to be displayed. :param category: The warning class to be thrown, by default ``DeprecationWarning`` :param stacklevel: There should be no need to set the value of ``stacklevel``. Salt should be able to do the right thing. :param _version_info_: In order to reuse this function for other SaltStack projects, they need to be able to provide the version info to compare to. :param _dont_call_warnings: This parameter is used just to get the functionality until the actual error is to be issued. When we're only after the salt version checks to raise a ``RuntimeError``.
[ "Helper", "function", "to", "raise", "a", "warning", "by", "default", "a", "DeprecationWarning", "until", "the", "provided", "version", "after", "which", "a", "RuntimeError", "will", "be", "raised", "to", "remind", "the", "developers", "to", "remove", "the", "...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/versions.py#L78-L162
train
saltstack/salt
salt/utils/versions.py
kwargs_warn_until
def kwargs_warn_until(kwargs, version, category=DeprecationWarning, stacklevel=None, _version_info_=None, _dont_call_warnings=False): ''' Helper function to raise a warning (by default, a ``DeprecationWarning``) when unhandled keyword arguments are passed to function, until the provided ``version_info``, after which, a ``RuntimeError`` will be raised to remind the developers to remove the ``**kwargs`` because the target version has been reached. This function is used to help deprecate unused legacy ``**kwargs`` that were added to function parameters lists to preserve backwards compatibility when removing a parameter. See :ref:`the deprecation development docs <deprecations>` for the modern strategy for deprecating a function parameter. :param kwargs: The caller's ``**kwargs`` argument value (a ``dict``). :param version: The version info or name after which the warning becomes a ``RuntimeError``. For example ``(0, 17)`` or ``Hydrogen`` or an instance of :class:`salt.version.SaltStackVersion`. :param category: The warning class to be thrown, by default ``DeprecationWarning`` :param stacklevel: There should be no need to set the value of ``stacklevel``. Salt should be able to do the right thing. :param _version_info_: In order to reuse this function for other SaltStack projects, they need to be able to provide the version info to compare to. :param _dont_call_warnings: This parameter is used just to get the functionality until the actual error is to be issued. When we're only after the salt version checks to raise a ``RuntimeError``. ''' if not isinstance(version, (tuple, six.string_types, salt.version.SaltStackVersion)): raise RuntimeError( 'The \'version\' argument should be passed as a tuple, string or ' 'an instance of \'salt.version.SaltStackVersion\'.' ) elif isinstance(version, tuple): version = salt.version.SaltStackVersion(*version) elif isinstance(version, six.string_types): version = salt.version.SaltStackVersion.from_name(version) if stacklevel is None: # Attribute the warning to the calling function, # not to kwargs_warn_until() or warn_until() stacklevel = 3 if _version_info_ is None: _version_info_ = salt.version.__version_info__ _version_ = salt.version.SaltStackVersion(*_version_info_) if kwargs or _version_.info >= version.info: arg_names = ', '.join('\'{0}\''.format(key) for key in kwargs) warn_until( version, message='The following parameter(s) have been deprecated and ' 'will be removed in \'{0}\': {1}.'.format(version.string, arg_names), category=category, stacklevel=stacklevel, _version_info_=_version_.info, _dont_call_warnings=_dont_call_warnings )
python
def kwargs_warn_until(kwargs, version, category=DeprecationWarning, stacklevel=None, _version_info_=None, _dont_call_warnings=False): ''' Helper function to raise a warning (by default, a ``DeprecationWarning``) when unhandled keyword arguments are passed to function, until the provided ``version_info``, after which, a ``RuntimeError`` will be raised to remind the developers to remove the ``**kwargs`` because the target version has been reached. This function is used to help deprecate unused legacy ``**kwargs`` that were added to function parameters lists to preserve backwards compatibility when removing a parameter. See :ref:`the deprecation development docs <deprecations>` for the modern strategy for deprecating a function parameter. :param kwargs: The caller's ``**kwargs`` argument value (a ``dict``). :param version: The version info or name after which the warning becomes a ``RuntimeError``. For example ``(0, 17)`` or ``Hydrogen`` or an instance of :class:`salt.version.SaltStackVersion`. :param category: The warning class to be thrown, by default ``DeprecationWarning`` :param stacklevel: There should be no need to set the value of ``stacklevel``. Salt should be able to do the right thing. :param _version_info_: In order to reuse this function for other SaltStack projects, they need to be able to provide the version info to compare to. :param _dont_call_warnings: This parameter is used just to get the functionality until the actual error is to be issued. When we're only after the salt version checks to raise a ``RuntimeError``. ''' if not isinstance(version, (tuple, six.string_types, salt.version.SaltStackVersion)): raise RuntimeError( 'The \'version\' argument should be passed as a tuple, string or ' 'an instance of \'salt.version.SaltStackVersion\'.' ) elif isinstance(version, tuple): version = salt.version.SaltStackVersion(*version) elif isinstance(version, six.string_types): version = salt.version.SaltStackVersion.from_name(version) if stacklevel is None: # Attribute the warning to the calling function, # not to kwargs_warn_until() or warn_until() stacklevel = 3 if _version_info_ is None: _version_info_ = salt.version.__version_info__ _version_ = salt.version.SaltStackVersion(*_version_info_) if kwargs or _version_.info >= version.info: arg_names = ', '.join('\'{0}\''.format(key) for key in kwargs) warn_until( version, message='The following parameter(s) have been deprecated and ' 'will be removed in \'{0}\': {1}.'.format(version.string, arg_names), category=category, stacklevel=stacklevel, _version_info_=_version_.info, _dont_call_warnings=_dont_call_warnings )
[ "def", "kwargs_warn_until", "(", "kwargs", ",", "version", ",", "category", "=", "DeprecationWarning", ",", "stacklevel", "=", "None", ",", "_version_info_", "=", "None", ",", "_dont_call_warnings", "=", "False", ")", ":", "if", "not", "isinstance", "(", "vers...
Helper function to raise a warning (by default, a ``DeprecationWarning``) when unhandled keyword arguments are passed to function, until the provided ``version_info``, after which, a ``RuntimeError`` will be raised to remind the developers to remove the ``**kwargs`` because the target version has been reached. This function is used to help deprecate unused legacy ``**kwargs`` that were added to function parameters lists to preserve backwards compatibility when removing a parameter. See :ref:`the deprecation development docs <deprecations>` for the modern strategy for deprecating a function parameter. :param kwargs: The caller's ``**kwargs`` argument value (a ``dict``). :param version: The version info or name after which the warning becomes a ``RuntimeError``. For example ``(0, 17)`` or ``Hydrogen`` or an instance of :class:`salt.version.SaltStackVersion`. :param category: The warning class to be thrown, by default ``DeprecationWarning`` :param stacklevel: There should be no need to set the value of ``stacklevel``. Salt should be able to do the right thing. :param _version_info_: In order to reuse this function for other SaltStack projects, they need to be able to provide the version info to compare to. :param _dont_call_warnings: This parameter is used just to get the functionality until the actual error is to be issued. When we're only after the salt version checks to raise a ``RuntimeError``.
[ "Helper", "function", "to", "raise", "a", "warning", "(", "by", "default", "a", "DeprecationWarning", ")", "when", "unhandled", "keyword", "arguments", "are", "passed", "to", "function", "until", "the", "provided", "version_info", "after", "which", "a", "Runtime...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/versions.py#L165-L232
train
saltstack/salt
salt/utils/versions.py
version_cmp
def version_cmp(pkg1, pkg2, ignore_epoch=False): ''' Compares two version strings using salt.utils.versions.LooseVersion. This is a fallback for providers which don't have a version comparison utility built into them. Return -1 if version1 < version2, 0 if version1 == version2, and 1 if version1 > version2. Return None if there was a problem making the comparison. ''' normalize = lambda x: six.text_type(x).split(':', 1)[-1] \ if ignore_epoch else six.text_type(x) pkg1 = normalize(pkg1) pkg2 = normalize(pkg2) try: # pylint: disable=no-member if LooseVersion(pkg1) < LooseVersion(pkg2): return -1 elif LooseVersion(pkg1) == LooseVersion(pkg2): return 0 elif LooseVersion(pkg1) > LooseVersion(pkg2): return 1 except Exception as exc: log.exception(exc) return None
python
def version_cmp(pkg1, pkg2, ignore_epoch=False): ''' Compares two version strings using salt.utils.versions.LooseVersion. This is a fallback for providers which don't have a version comparison utility built into them. Return -1 if version1 < version2, 0 if version1 == version2, and 1 if version1 > version2. Return None if there was a problem making the comparison. ''' normalize = lambda x: six.text_type(x).split(':', 1)[-1] \ if ignore_epoch else six.text_type(x) pkg1 = normalize(pkg1) pkg2 = normalize(pkg2) try: # pylint: disable=no-member if LooseVersion(pkg1) < LooseVersion(pkg2): return -1 elif LooseVersion(pkg1) == LooseVersion(pkg2): return 0 elif LooseVersion(pkg1) > LooseVersion(pkg2): return 1 except Exception as exc: log.exception(exc) return None
[ "def", "version_cmp", "(", "pkg1", ",", "pkg2", ",", "ignore_epoch", "=", "False", ")", ":", "normalize", "=", "lambda", "x", ":", "six", ".", "text_type", "(", "x", ")", ".", "split", "(", "':'", ",", "1", ")", "[", "-", "1", "]", "if", "ignore_...
Compares two version strings using salt.utils.versions.LooseVersion. This is a fallback for providers which don't have a version comparison utility built into them. Return -1 if version1 < version2, 0 if version1 == version2, and 1 if version1 > version2. Return None if there was a problem making the comparison.
[ "Compares", "two", "version", "strings", "using", "salt", ".", "utils", ".", "versions", ".", "LooseVersion", ".", "This", "is", "a", "fallback", "for", "providers", "which", "don", "t", "have", "a", "version", "comparison", "utility", "built", "into", "them...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/versions.py#L235-L258
train
saltstack/salt
salt/utils/versions.py
compare
def compare(ver1='', oper='==', ver2='', cmp_func=None, ignore_epoch=False): ''' Compares two version numbers. Accepts a custom function to perform the cmp-style version comparison, otherwise uses version_cmp(). ''' cmp_map = {'<': (-1,), '<=': (-1, 0), '==': (0,), '>=': (0, 1), '>': (1,)} if oper not in ('!=',) and oper not in cmp_map: log.error('Invalid operator \'%s\' for version comparison', oper) return False if cmp_func is None: cmp_func = version_cmp cmp_result = cmp_func(ver1, ver2, ignore_epoch=ignore_epoch) if cmp_result is None: return False # Check if integer/long if not isinstance(cmp_result, numbers.Integral): log.error('The version comparison function did not return an ' 'integer/long.') return False if oper == '!=': return cmp_result not in cmp_map['=='] else: # Gracefully handle cmp_result not in (-1, 0, 1). if cmp_result < -1: cmp_result = -1 elif cmp_result > 1: cmp_result = 1 return cmp_result in cmp_map[oper]
python
def compare(ver1='', oper='==', ver2='', cmp_func=None, ignore_epoch=False): ''' Compares two version numbers. Accepts a custom function to perform the cmp-style version comparison, otherwise uses version_cmp(). ''' cmp_map = {'<': (-1,), '<=': (-1, 0), '==': (0,), '>=': (0, 1), '>': (1,)} if oper not in ('!=',) and oper not in cmp_map: log.error('Invalid operator \'%s\' for version comparison', oper) return False if cmp_func is None: cmp_func = version_cmp cmp_result = cmp_func(ver1, ver2, ignore_epoch=ignore_epoch) if cmp_result is None: return False # Check if integer/long if not isinstance(cmp_result, numbers.Integral): log.error('The version comparison function did not return an ' 'integer/long.') return False if oper == '!=': return cmp_result not in cmp_map['=='] else: # Gracefully handle cmp_result not in (-1, 0, 1). if cmp_result < -1: cmp_result = -1 elif cmp_result > 1: cmp_result = 1 return cmp_result in cmp_map[oper]
[ "def", "compare", "(", "ver1", "=", "''", ",", "oper", "=", "'=='", ",", "ver2", "=", "''", ",", "cmp_func", "=", "None", ",", "ignore_epoch", "=", "False", ")", ":", "cmp_map", "=", "{", "'<'", ":", "(", "-", "1", ",", ")", ",", "'<='", ":", ...
Compares two version numbers. Accepts a custom function to perform the cmp-style version comparison, otherwise uses version_cmp().
[ "Compares", "two", "version", "numbers", ".", "Accepts", "a", "custom", "function", "to", "perform", "the", "cmp", "-", "style", "version", "comparison", "otherwise", "uses", "version_cmp", "()", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/versions.py#L261-L294
train
saltstack/salt
salt/utils/versions.py
check_boto_reqs
def check_boto_reqs(boto_ver=None, boto3_ver=None, botocore_ver=None, check_boto=True, check_boto3=True): ''' Checks for the version of various required boto libs in one central location. Most boto states and modules rely on a single version of the boto, boto3, or botocore libs. However, some require newer versions of any of these dependencies. This function allows the module to pass in a version to override the default minimum required version. This function is useful in centralizing checks for ``__virtual__()`` functions in the various, and many, boto modules and states. boto_ver The minimum required version of the boto library. Defaults to ``2.0.0``. boto3_ver The minimum required version of the boto3 library. Defaults to ``1.2.6``. botocore_ver The minimum required version of the botocore library. Defaults to ``1.3.23``. check_boto Boolean defining whether or not to check for boto deps. This defaults to ``True`` as most boto modules/states rely on boto, but some do not. check_boto3 Boolean defining whether or not to check for boto3 (and therefore botocore) deps. This defaults to ``True`` as most boto modules/states rely on boto3/botocore, but some do not. ''' if check_boto is True: try: # Late import so we can only load these for this function import boto has_boto = True except ImportError: has_boto = False if boto_ver is None: boto_ver = '2.0.0' if not has_boto or version_cmp(boto.__version__, boto_ver) == -1: return False, 'A minimum version of boto {0} is required.'.format(boto_ver) if check_boto3 is True: try: # Late import so we can only load these for this function import boto3 import botocore has_boto3 = True except ImportError: has_boto3 = False # boto_s3_bucket module requires boto3 1.2.6 and botocore 1.3.23 for # idempotent ACL operations via the fix in https://github.com/boto/boto3/issues/390 if boto3_ver is None: boto3_ver = '1.2.6' if botocore_ver is None: botocore_ver = '1.3.23' if not has_boto3 or version_cmp(boto3.__version__, boto3_ver) == -1: return False, 'A minimum version of boto3 {0} is required.'.format(boto3_ver) elif version_cmp(botocore.__version__, botocore_ver) == -1: return False, 'A minimum version of botocore {0} is required'.format(botocore_ver) return True
python
def check_boto_reqs(boto_ver=None, boto3_ver=None, botocore_ver=None, check_boto=True, check_boto3=True): ''' Checks for the version of various required boto libs in one central location. Most boto states and modules rely on a single version of the boto, boto3, or botocore libs. However, some require newer versions of any of these dependencies. This function allows the module to pass in a version to override the default minimum required version. This function is useful in centralizing checks for ``__virtual__()`` functions in the various, and many, boto modules and states. boto_ver The minimum required version of the boto library. Defaults to ``2.0.0``. boto3_ver The minimum required version of the boto3 library. Defaults to ``1.2.6``. botocore_ver The minimum required version of the botocore library. Defaults to ``1.3.23``. check_boto Boolean defining whether or not to check for boto deps. This defaults to ``True`` as most boto modules/states rely on boto, but some do not. check_boto3 Boolean defining whether or not to check for boto3 (and therefore botocore) deps. This defaults to ``True`` as most boto modules/states rely on boto3/botocore, but some do not. ''' if check_boto is True: try: # Late import so we can only load these for this function import boto has_boto = True except ImportError: has_boto = False if boto_ver is None: boto_ver = '2.0.0' if not has_boto or version_cmp(boto.__version__, boto_ver) == -1: return False, 'A minimum version of boto {0} is required.'.format(boto_ver) if check_boto3 is True: try: # Late import so we can only load these for this function import boto3 import botocore has_boto3 = True except ImportError: has_boto3 = False # boto_s3_bucket module requires boto3 1.2.6 and botocore 1.3.23 for # idempotent ACL operations via the fix in https://github.com/boto/boto3/issues/390 if boto3_ver is None: boto3_ver = '1.2.6' if botocore_ver is None: botocore_ver = '1.3.23' if not has_boto3 or version_cmp(boto3.__version__, boto3_ver) == -1: return False, 'A minimum version of boto3 {0} is required.'.format(boto3_ver) elif version_cmp(botocore.__version__, botocore_ver) == -1: return False, 'A minimum version of botocore {0} is required'.format(botocore_ver) return True
[ "def", "check_boto_reqs", "(", "boto_ver", "=", "None", ",", "boto3_ver", "=", "None", ",", "botocore_ver", "=", "None", ",", "check_boto", "=", "True", ",", "check_boto3", "=", "True", ")", ":", "if", "check_boto", "is", "True", ":", "try", ":", "# Late...
Checks for the version of various required boto libs in one central location. Most boto states and modules rely on a single version of the boto, boto3, or botocore libs. However, some require newer versions of any of these dependencies. This function allows the module to pass in a version to override the default minimum required version. This function is useful in centralizing checks for ``__virtual__()`` functions in the various, and many, boto modules and states. boto_ver The minimum required version of the boto library. Defaults to ``2.0.0``. boto3_ver The minimum required version of the boto3 library. Defaults to ``1.2.6``. botocore_ver The minimum required version of the botocore library. Defaults to ``1.3.23``. check_boto Boolean defining whether or not to check for boto deps. This defaults to ``True`` as most boto modules/states rely on boto, but some do not. check_boto3 Boolean defining whether or not to check for boto3 (and therefore botocore) deps. This defaults to ``True`` as most boto modules/states rely on boto3/botocore, but some do not.
[ "Checks", "for", "the", "version", "of", "various", "required", "boto", "libs", "in", "one", "central", "location", ".", "Most", "boto", "states", "and", "modules", "rely", "on", "a", "single", "version", "of", "the", "boto", "boto3", "or", "botocore", "li...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/versions.py#L297-L364
train
saltstack/salt
salt/states/boto_elbv2.py
create_target_group
def create_target_group(name, protocol, port, vpc_id, region=None, key=None, keyid=None, profile=None, health_check_protocol='HTTP', health_check_port='traffic-port', health_check_path='/', health_check_interval_seconds=30, health_check_timeout_seconds=5, healthy_threshold_count=5, unhealthy_threshold_count=2, **kwargs): ''' .. versionadded:: 2017.11.0 Create target group if not present. name (string) - The name of the target group. protocol (string) - The protocol to use for routing traffic to the targets port (int) - The port on which the targets receive traffic. This port is used unless you specify a port override when registering the traffic. vpc_id (string) - The identifier of the virtual private cloud (VPC). health_check_protocol (string) - The protocol the load balancer uses when performing health check on targets. The default is the HTTP protocol. health_check_port (string) - The port the load balancer uses when performing health checks on targets. The default is 'traffic-port', which indicates the port on which each target receives traffic from the load balancer. health_check_path (string) - The ping path that is the destination on the targets for health checks. The default is /. health_check_interval_seconds (integer) - The approximate amount of time, in seconds, between health checks of an individual target. The default is 30 seconds. health_check_timeout_seconds (integer) - The amount of time, in seconds, during which no response from a target means a failed health check. The default is 5 seconds. healthy_threshold_count (integer) - The number of consecutive health checks successes required before considering an unhealthy target healthy. The default is 5. unhealthy_threshold_count (integer) - The number of consecutive health check failures required before considering a target unhealthy. The default is 2. returns (bool) - True on success, False on failure. CLI example: .. code-block:: yaml create-target: boto_elb2.create_targets_group: - name: myALB - protocol: https - port: 443 - vpc_id: myVPC ''' ret = {'name': name, 'result': None, 'comment': '', 'changes': {}} if __salt__['boto_elbv2.target_group_exists'](name, region, key, keyid, profile): ret['result'] = True ret['comment'] = 'Target Group {0} already exists'.format(name) return ret if __opts__['test']: ret['comment'] = 'Target Group {0} will be created'.format(name) return ret state = __salt__['boto_elbv2.create_target_group'](name, protocol, port, vpc_id, region=region, key=key, keyid=keyid, profile=profile, health_check_protocol=health_check_protocol, health_check_port=health_check_port, health_check_path=health_check_path, health_check_interval_seconds=health_check_interval_seconds, health_check_timeout_seconds=health_check_timeout_seconds, healthy_threshold_count=healthy_threshold_count, unhealthy_threshold_count=unhealthy_threshold_count, **kwargs) if state: ret['changes']['target_group'] = name ret['result'] = True ret['comment'] = 'Target Group {0} created'.format(name) else: ret['result'] = False ret['comment'] = 'Target Group {0} creation failed'.format(name) return ret
python
def create_target_group(name, protocol, port, vpc_id, region=None, key=None, keyid=None, profile=None, health_check_protocol='HTTP', health_check_port='traffic-port', health_check_path='/', health_check_interval_seconds=30, health_check_timeout_seconds=5, healthy_threshold_count=5, unhealthy_threshold_count=2, **kwargs): ''' .. versionadded:: 2017.11.0 Create target group if not present. name (string) - The name of the target group. protocol (string) - The protocol to use for routing traffic to the targets port (int) - The port on which the targets receive traffic. This port is used unless you specify a port override when registering the traffic. vpc_id (string) - The identifier of the virtual private cloud (VPC). health_check_protocol (string) - The protocol the load balancer uses when performing health check on targets. The default is the HTTP protocol. health_check_port (string) - The port the load balancer uses when performing health checks on targets. The default is 'traffic-port', which indicates the port on which each target receives traffic from the load balancer. health_check_path (string) - The ping path that is the destination on the targets for health checks. The default is /. health_check_interval_seconds (integer) - The approximate amount of time, in seconds, between health checks of an individual target. The default is 30 seconds. health_check_timeout_seconds (integer) - The amount of time, in seconds, during which no response from a target means a failed health check. The default is 5 seconds. healthy_threshold_count (integer) - The number of consecutive health checks successes required before considering an unhealthy target healthy. The default is 5. unhealthy_threshold_count (integer) - The number of consecutive health check failures required before considering a target unhealthy. The default is 2. returns (bool) - True on success, False on failure. CLI example: .. code-block:: yaml create-target: boto_elb2.create_targets_group: - name: myALB - protocol: https - port: 443 - vpc_id: myVPC ''' ret = {'name': name, 'result': None, 'comment': '', 'changes': {}} if __salt__['boto_elbv2.target_group_exists'](name, region, key, keyid, profile): ret['result'] = True ret['comment'] = 'Target Group {0} already exists'.format(name) return ret if __opts__['test']: ret['comment'] = 'Target Group {0} will be created'.format(name) return ret state = __salt__['boto_elbv2.create_target_group'](name, protocol, port, vpc_id, region=region, key=key, keyid=keyid, profile=profile, health_check_protocol=health_check_protocol, health_check_port=health_check_port, health_check_path=health_check_path, health_check_interval_seconds=health_check_interval_seconds, health_check_timeout_seconds=health_check_timeout_seconds, healthy_threshold_count=healthy_threshold_count, unhealthy_threshold_count=unhealthy_threshold_count, **kwargs) if state: ret['changes']['target_group'] = name ret['result'] = True ret['comment'] = 'Target Group {0} created'.format(name) else: ret['result'] = False ret['comment'] = 'Target Group {0} creation failed'.format(name) return ret
[ "def", "create_target_group", "(", "name", ",", "protocol", ",", "port", ",", "vpc_id", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ",", "health_check_protocol", "=", "'HTTP'", ",", "health...
.. versionadded:: 2017.11.0 Create target group if not present. name (string) - The name of the target group. protocol (string) - The protocol to use for routing traffic to the targets port (int) - The port on which the targets receive traffic. This port is used unless you specify a port override when registering the traffic. vpc_id (string) - The identifier of the virtual private cloud (VPC). health_check_protocol (string) - The protocol the load balancer uses when performing health check on targets. The default is the HTTP protocol. health_check_port (string) - The port the load balancer uses when performing health checks on targets. The default is 'traffic-port', which indicates the port on which each target receives traffic from the load balancer. health_check_path (string) - The ping path that is the destination on the targets for health checks. The default is /. health_check_interval_seconds (integer) - The approximate amount of time, in seconds, between health checks of an individual target. The default is 30 seconds. health_check_timeout_seconds (integer) - The amount of time, in seconds, during which no response from a target means a failed health check. The default is 5 seconds. healthy_threshold_count (integer) - The number of consecutive health checks successes required before considering an unhealthy target healthy. The default is 5. unhealthy_threshold_count (integer) - The number of consecutive health check failures required before considering a target unhealthy. The default is 2. returns (bool) - True on success, False on failure. CLI example: .. code-block:: yaml create-target: boto_elb2.create_targets_group: - name: myALB - protocol: https - port: 443 - vpc_id: myVPC
[ "..", "versionadded", "::", "2017", ".", "11", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_elbv2.py#L58-L150
train
saltstack/salt
salt/states/boto_elbv2.py
delete_target_group
def delete_target_group(name, region=None, key=None, keyid=None, profile=None): ''' Delete target group. name (string) - The Amazon Resource Name (ARN) of the resource. returns (bool) - True on success, False on failure. CLI example: .. code-block:: bash check-target: boto_elb2.delete_targets_group: - name: myALB - protocol: https - port: 443 - vpc_id: myVPC ''' ret = {'name': name, 'result': None, 'comment': '', 'changes': {}} if not __salt__['boto_elbv2.target_group_exists'](name, region, key, keyid, profile): ret['result'] = True ret['comment'] = 'Target Group {0} does not exists'.format(name) return ret if __opts__['test']: ret['comment'] = 'Target Group {0} will be deleted'.format(name) return ret state = __salt__['boto_elbv2.delete_target_group'](name, region=region, key=key, keyid=keyid, profile=profile) if state: ret['result'] = True ret['changes']['target_group'] = name ret['comment'] = 'Target Group {0} deleted'.format(name) else: ret['result'] = False ret['comment'] = 'Target Group {0} deletion failed'.format(name) return ret
python
def delete_target_group(name, region=None, key=None, keyid=None, profile=None): ''' Delete target group. name (string) - The Amazon Resource Name (ARN) of the resource. returns (bool) - True on success, False on failure. CLI example: .. code-block:: bash check-target: boto_elb2.delete_targets_group: - name: myALB - protocol: https - port: 443 - vpc_id: myVPC ''' ret = {'name': name, 'result': None, 'comment': '', 'changes': {}} if not __salt__['boto_elbv2.target_group_exists'](name, region, key, keyid, profile): ret['result'] = True ret['comment'] = 'Target Group {0} does not exists'.format(name) return ret if __opts__['test']: ret['comment'] = 'Target Group {0} will be deleted'.format(name) return ret state = __salt__['boto_elbv2.delete_target_group'](name, region=region, key=key, keyid=keyid, profile=profile) if state: ret['result'] = True ret['changes']['target_group'] = name ret['comment'] = 'Target Group {0} deleted'.format(name) else: ret['result'] = False ret['comment'] = 'Target Group {0} deletion failed'.format(name) return ret
[ "def", "delete_target_group", "(", "name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "None", ",", "'comment'", ...
Delete target group. name (string) - The Amazon Resource Name (ARN) of the resource. returns (bool) - True on success, False on failure. CLI example: .. code-block:: bash check-target: boto_elb2.delete_targets_group: - name: myALB - protocol: https - port: 443 - vpc_id: myVPC
[ "Delete", "target", "group", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_elbv2.py#L153-L198
train
saltstack/salt
salt/states/boto_elbv2.py
targets_registered
def targets_registered(name, targets, region=None, key=None, keyid=None, profile=None, **kwargs): ''' .. versionadded:: 2017.7.0 Add targets to an Application Load Balancer target group. This state will not remove targets. name The ARN of the Application Load Balancer Target Group to add targets to. targets A list of target IDs or a string of a single target that this target group should distribute traffic to. .. code-block:: yaml add-targets: boto_elb.targets_registered: - name: arn:myloadbalancer - targets: - instance-id1 - instance-id2 ''' ret = {'name': name, 'result': None, 'comment': '', 'changes': {}} if __salt__['boto_elbv2.target_group_exists'](name, region, key, keyid, profile): health = __salt__['boto_elbv2.describe_target_health'](name, region=region, key=key, keyid=keyid, profile=profile) failure = False changes = False newhealth_mock = copy.copy(health) if isinstance(targets, six.string_types): targets = [targets] for target in targets: if target in health and health.get(target) != "draining": ret['comment'] = ret['comment'] + 'Target/s {0} already registered and is {1}.\n'.format(target, health[target]) ret['result'] = True else: if __opts__['test']: changes = True newhealth_mock.update({target: "initial"}) else: state = __salt__['boto_elbv2.register_targets'](name, targets, region=region, key=key, keyid=keyid, profile=profile) if state: changes = True ret['result'] = True else: ret['comment'] = 'Target Group {0} failed to add targets'.format(name) failure = True if failure: ret['result'] = False if changes: ret['changes']['old'] = health if __opts__['test']: ret['comment'] = 'Target Group {0} would be changed'.format(name) ret['result'] = None ret['changes']['new'] = newhealth_mock else: ret['comment'] = 'Target Group {0} has been changed'.format(name) newhealth = __salt__['boto_elbv2.describe_target_health'](name, region=region, key=key, keyid=keyid, profile=profile) ret['changes']['new'] = newhealth return ret else: ret['comment'] = 'Could not find target group {0}'.format(name) return ret
python
def targets_registered(name, targets, region=None, key=None, keyid=None, profile=None, **kwargs): ''' .. versionadded:: 2017.7.0 Add targets to an Application Load Balancer target group. This state will not remove targets. name The ARN of the Application Load Balancer Target Group to add targets to. targets A list of target IDs or a string of a single target that this target group should distribute traffic to. .. code-block:: yaml add-targets: boto_elb.targets_registered: - name: arn:myloadbalancer - targets: - instance-id1 - instance-id2 ''' ret = {'name': name, 'result': None, 'comment': '', 'changes': {}} if __salt__['boto_elbv2.target_group_exists'](name, region, key, keyid, profile): health = __salt__['boto_elbv2.describe_target_health'](name, region=region, key=key, keyid=keyid, profile=profile) failure = False changes = False newhealth_mock = copy.copy(health) if isinstance(targets, six.string_types): targets = [targets] for target in targets: if target in health and health.get(target) != "draining": ret['comment'] = ret['comment'] + 'Target/s {0} already registered and is {1}.\n'.format(target, health[target]) ret['result'] = True else: if __opts__['test']: changes = True newhealth_mock.update({target: "initial"}) else: state = __salt__['boto_elbv2.register_targets'](name, targets, region=region, key=key, keyid=keyid, profile=profile) if state: changes = True ret['result'] = True else: ret['comment'] = 'Target Group {0} failed to add targets'.format(name) failure = True if failure: ret['result'] = False if changes: ret['changes']['old'] = health if __opts__['test']: ret['comment'] = 'Target Group {0} would be changed'.format(name) ret['result'] = None ret['changes']['new'] = newhealth_mock else: ret['comment'] = 'Target Group {0} has been changed'.format(name) newhealth = __salt__['boto_elbv2.describe_target_health'](name, region=region, key=key, keyid=keyid, profile=profile) ret['changes']['new'] = newhealth return ret else: ret['comment'] = 'Could not find target group {0}'.format(name) return ret
[ "def", "targets_registered", "(", "name", ",", "targets", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", ...
.. versionadded:: 2017.7.0 Add targets to an Application Load Balancer target group. This state will not remove targets. name The ARN of the Application Load Balancer Target Group to add targets to. targets A list of target IDs or a string of a single target that this target group should distribute traffic to. .. code-block:: yaml add-targets: boto_elb.targets_registered: - name: arn:myloadbalancer - targets: - instance-id1 - instance-id2
[ "..", "versionadded", "::", "2017", ".", "7", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_elbv2.py#L201-L279
train
saltstack/salt
salt/modules/bamboohr.py
list_employees
def list_employees(order_by='id'): ''' Show all employees for this company. CLI Example: salt myminion bamboohr.list_employees By default, the return data will be keyed by ID. However, it can be ordered by any other field. Keep in mind that if the field that is chosen contains duplicate values (i.e., location is used, for a company which only has one location), then each duplicate value will be overwritten by the previous. Therefore, it is advisable to only sort by fields that are guaranteed to be unique. CLI Examples: salt myminion bamboohr.list_employees order_by=id salt myminion bamboohr.list_employees order_by=displayName salt myminion bamboohr.list_employees order_by=workEmail ''' ret = {} status, result = _query(action='employees', command='directory') root = ET.fromstring(result) directory = root.getchildren() for cat in directory: if cat.tag != 'employees': continue for item in cat: emp_id = item.items()[0][1] emp_ret = {'id': emp_id} for details in item.getchildren(): emp_ret[details.items()[0][1]] = details.text ret[emp_ret[order_by]] = emp_ret return ret
python
def list_employees(order_by='id'): ''' Show all employees for this company. CLI Example: salt myminion bamboohr.list_employees By default, the return data will be keyed by ID. However, it can be ordered by any other field. Keep in mind that if the field that is chosen contains duplicate values (i.e., location is used, for a company which only has one location), then each duplicate value will be overwritten by the previous. Therefore, it is advisable to only sort by fields that are guaranteed to be unique. CLI Examples: salt myminion bamboohr.list_employees order_by=id salt myminion bamboohr.list_employees order_by=displayName salt myminion bamboohr.list_employees order_by=workEmail ''' ret = {} status, result = _query(action='employees', command='directory') root = ET.fromstring(result) directory = root.getchildren() for cat in directory: if cat.tag != 'employees': continue for item in cat: emp_id = item.items()[0][1] emp_ret = {'id': emp_id} for details in item.getchildren(): emp_ret[details.items()[0][1]] = details.text ret[emp_ret[order_by]] = emp_ret return ret
[ "def", "list_employees", "(", "order_by", "=", "'id'", ")", ":", "ret", "=", "{", "}", "status", ",", "result", "=", "_query", "(", "action", "=", "'employees'", ",", "command", "=", "'directory'", ")", "root", "=", "ET", ".", "fromstring", "(", "resul...
Show all employees for this company. CLI Example: salt myminion bamboohr.list_employees By default, the return data will be keyed by ID. However, it can be ordered by any other field. Keep in mind that if the field that is chosen contains duplicate values (i.e., location is used, for a company which only has one location), then each duplicate value will be overwritten by the previous. Therefore, it is advisable to only sort by fields that are guaranteed to be unique. CLI Examples: salt myminion bamboohr.list_employees order_by=id salt myminion bamboohr.list_employees order_by=displayName salt myminion bamboohr.list_employees order_by=workEmail
[ "Show", "all", "employees", "for", "this", "company", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bamboohr.py#L45-L79
train
saltstack/salt
salt/modules/bamboohr.py
show_employee
def show_employee(emp_id, fields=None): ''' Show all employees for this company. CLI Example: salt myminion bamboohr.show_employee 1138 By default, the fields normally returned from bamboohr.list_employees are returned. These fields are: - canUploadPhoto - department - displayName - firstName - id - jobTitle - lastName - location - mobilePhone - nickname - photoUploaded - photoUrl - workEmail - workPhone - workPhoneExtension If needed, a different set of fields may be specified, separated by commas: CLI Example: salt myminion bamboohr.show_employee 1138 displayName,dateOfBirth A list of available fields can be found at http://www.bamboohr.com/api/documentation/employees.php ''' ret = {} if fields is None: fields = ','.join(( 'canUploadPhoto', 'department', 'displayName', 'firstName', 'id', 'jobTitle', 'lastName', 'location', 'mobilePhone', 'nickname', 'photoUploaded', 'photoUrl', 'workEmail', 'workPhone', 'workPhoneExtension', )) status, result = _query( action='employees', command=emp_id, args={'fields': fields} ) root = ET.fromstring(result) items = root.getchildren() ret = {'id': emp_id} for item in items: ret[item.items()[0][1]] = item.text return ret
python
def show_employee(emp_id, fields=None): ''' Show all employees for this company. CLI Example: salt myminion bamboohr.show_employee 1138 By default, the fields normally returned from bamboohr.list_employees are returned. These fields are: - canUploadPhoto - department - displayName - firstName - id - jobTitle - lastName - location - mobilePhone - nickname - photoUploaded - photoUrl - workEmail - workPhone - workPhoneExtension If needed, a different set of fields may be specified, separated by commas: CLI Example: salt myminion bamboohr.show_employee 1138 displayName,dateOfBirth A list of available fields can be found at http://www.bamboohr.com/api/documentation/employees.php ''' ret = {} if fields is None: fields = ','.join(( 'canUploadPhoto', 'department', 'displayName', 'firstName', 'id', 'jobTitle', 'lastName', 'location', 'mobilePhone', 'nickname', 'photoUploaded', 'photoUrl', 'workEmail', 'workPhone', 'workPhoneExtension', )) status, result = _query( action='employees', command=emp_id, args={'fields': fields} ) root = ET.fromstring(result) items = root.getchildren() ret = {'id': emp_id} for item in items: ret[item.items()[0][1]] = item.text return ret
[ "def", "show_employee", "(", "emp_id", ",", "fields", "=", "None", ")", ":", "ret", "=", "{", "}", "if", "fields", "is", "None", ":", "fields", "=", "','", ".", "join", "(", "(", "'canUploadPhoto'", ",", "'department'", ",", "'displayName'", ",", "'fir...
Show all employees for this company. CLI Example: salt myminion bamboohr.show_employee 1138 By default, the fields normally returned from bamboohr.list_employees are returned. These fields are: - canUploadPhoto - department - displayName - firstName - id - jobTitle - lastName - location - mobilePhone - nickname - photoUploaded - photoUrl - workEmail - workPhone - workPhoneExtension If needed, a different set of fields may be specified, separated by commas: CLI Example: salt myminion bamboohr.show_employee 1138 displayName,dateOfBirth A list of available fields can be found at http://www.bamboohr.com/api/documentation/employees.php
[ "Show", "all", "employees", "for", "this", "company", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bamboohr.py#L82-L150
train
saltstack/salt
salt/modules/bamboohr.py
update_employee
def update_employee(emp_id, key=None, value=None, items=None): ''' Update one or more items for this employee. Specifying an empty value will clear it for that employee. CLI Examples: salt myminion bamboohr.update_employee 1138 nickname Curly salt myminion bamboohr.update_employee 1138 nickname '' salt myminion bamboohr.update_employee 1138 items='{"nickname": "Curly"} salt myminion bamboohr.update_employee 1138 items='{"nickname": ""} ''' if items is None: if key is None or value is None: return {'Error': 'At least one key/value pair is required'} items = {key: value} elif isinstance(items, six.string_types): items = salt.utils.yaml.safe_load(items) xml_items = '' for pair in items: xml_items += '<field id="{0}">{1}</field>'.format(pair, items[pair]) xml_items = '<employee>{0}</employee>'.format(xml_items) status, result = _query( action='employees', command=emp_id, data=xml_items, method='POST', ) return show_employee(emp_id, ','.join(items.keys()))
python
def update_employee(emp_id, key=None, value=None, items=None): ''' Update one or more items for this employee. Specifying an empty value will clear it for that employee. CLI Examples: salt myminion bamboohr.update_employee 1138 nickname Curly salt myminion bamboohr.update_employee 1138 nickname '' salt myminion bamboohr.update_employee 1138 items='{"nickname": "Curly"} salt myminion bamboohr.update_employee 1138 items='{"nickname": ""} ''' if items is None: if key is None or value is None: return {'Error': 'At least one key/value pair is required'} items = {key: value} elif isinstance(items, six.string_types): items = salt.utils.yaml.safe_load(items) xml_items = '' for pair in items: xml_items += '<field id="{0}">{1}</field>'.format(pair, items[pair]) xml_items = '<employee>{0}</employee>'.format(xml_items) status, result = _query( action='employees', command=emp_id, data=xml_items, method='POST', ) return show_employee(emp_id, ','.join(items.keys()))
[ "def", "update_employee", "(", "emp_id", ",", "key", "=", "None", ",", "value", "=", "None", ",", "items", "=", "None", ")", ":", "if", "items", "is", "None", ":", "if", "key", "is", "None", "or", "value", "is", "None", ":", "return", "{", "'Error'...
Update one or more items for this employee. Specifying an empty value will clear it for that employee. CLI Examples: salt myminion bamboohr.update_employee 1138 nickname Curly salt myminion bamboohr.update_employee 1138 nickname '' salt myminion bamboohr.update_employee 1138 items='{"nickname": "Curly"} salt myminion bamboohr.update_employee 1138 items='{"nickname": ""}
[ "Update", "one", "or", "more", "items", "for", "this", "employee", ".", "Specifying", "an", "empty", "value", "will", "clear", "it", "for", "that", "employee", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bamboohr.py#L153-L184
train
saltstack/salt
salt/modules/bamboohr.py
list_users
def list_users(order_by='id'): ''' Show all users for this company. CLI Example: salt myminion bamboohr.list_users By default, the return data will be keyed by ID. However, it can be ordered by any other field. Keep in mind that if the field that is chosen contains duplicate values (i.e., location is used, for a company which only has one location), then each duplicate value will be overwritten by the previous. Therefore, it is advisable to only sort by fields that are guaranteed to be unique. CLI Examples: salt myminion bamboohr.list_users order_by=id salt myminion bamboohr.list_users order_by=email ''' ret = {} status, result = _query(action='meta', command='users') root = ET.fromstring(result) users = root.getchildren() for user in users: user_id = None user_ret = {} for item in user.items(): user_ret[item[0]] = item[1] if item[0] == 'id': user_id = item[1] for item in user.getchildren(): user_ret[item.tag] = item.text ret[user_ret[order_by]] = user_ret return ret
python
def list_users(order_by='id'): ''' Show all users for this company. CLI Example: salt myminion bamboohr.list_users By default, the return data will be keyed by ID. However, it can be ordered by any other field. Keep in mind that if the field that is chosen contains duplicate values (i.e., location is used, for a company which only has one location), then each duplicate value will be overwritten by the previous. Therefore, it is advisable to only sort by fields that are guaranteed to be unique. CLI Examples: salt myminion bamboohr.list_users order_by=id salt myminion bamboohr.list_users order_by=email ''' ret = {} status, result = _query(action='meta', command='users') root = ET.fromstring(result) users = root.getchildren() for user in users: user_id = None user_ret = {} for item in user.items(): user_ret[item[0]] = item[1] if item[0] == 'id': user_id = item[1] for item in user.getchildren(): user_ret[item.tag] = item.text ret[user_ret[order_by]] = user_ret return ret
[ "def", "list_users", "(", "order_by", "=", "'id'", ")", ":", "ret", "=", "{", "}", "status", ",", "result", "=", "_query", "(", "action", "=", "'meta'", ",", "command", "=", "'users'", ")", "root", "=", "ET", ".", "fromstring", "(", "result", ")", ...
Show all users for this company. CLI Example: salt myminion bamboohr.list_users By default, the return data will be keyed by ID. However, it can be ordered by any other field. Keep in mind that if the field that is chosen contains duplicate values (i.e., location is used, for a company which only has one location), then each duplicate value will be overwritten by the previous. Therefore, it is advisable to only sort by fields that are guaranteed to be unique. CLI Examples: salt myminion bamboohr.list_users order_by=id salt myminion bamboohr.list_users order_by=email
[ "Show", "all", "users", "for", "this", "company", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bamboohr.py#L187-L221
train
saltstack/salt
salt/modules/bamboohr.py
list_meta_fields
def list_meta_fields(): ''' Show all meta data fields for this company. CLI Example: salt myminion bamboohr.list_meta_fields ''' ret = {} status, result = _query(action='meta', command='fields') root = ET.fromstring(result) fields = root.getchildren() for field in fields: field_id = None field_ret = {'name': field.text} for item in field.items(): field_ret[item[0]] = item[1] if item[0] == 'id': field_id = item[1] ret[field_id] = field_ret return ret
python
def list_meta_fields(): ''' Show all meta data fields for this company. CLI Example: salt myminion bamboohr.list_meta_fields ''' ret = {} status, result = _query(action='meta', command='fields') root = ET.fromstring(result) fields = root.getchildren() for field in fields: field_id = None field_ret = {'name': field.text} for item in field.items(): field_ret[item[0]] = item[1] if item[0] == 'id': field_id = item[1] ret[field_id] = field_ret return ret
[ "def", "list_meta_fields", "(", ")", ":", "ret", "=", "{", "}", "status", ",", "result", "=", "_query", "(", "action", "=", "'meta'", ",", "command", "=", "'fields'", ")", "root", "=", "ET", ".", "fromstring", "(", "result", ")", "fields", "=", "root...
Show all meta data fields for this company. CLI Example: salt myminion bamboohr.list_meta_fields
[ "Show", "all", "meta", "data", "fields", "for", "this", "company", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bamboohr.py#L224-L244
train
saltstack/salt
salt/modules/bamboohr.py
_query
def _query(action=None, command=None, args=None, method='GET', data=None): ''' Make a web call to BambooHR The password can be any random text, so we chose Salty text. ''' subdomain = __opts__.get('bamboohr', {}).get('subdomain', None) path = 'https://api.bamboohr.com/api/gateway.php/{0}/v1/'.format( subdomain ) if action: path += action if command: path += '/{0}'.format(command) log.debug('BambooHR URL: %s', path) if not isinstance(args, dict): args = {} return_content = None result = salt.utils.http.query( path, method, username=_apikey(), password='saltypork', params=args, data=data, decode=False, text=True, status=True, opts=__opts__, ) log.debug('BambooHR Response Status Code: %s', result['status']) return [result['status'], result['text']]
python
def _query(action=None, command=None, args=None, method='GET', data=None): ''' Make a web call to BambooHR The password can be any random text, so we chose Salty text. ''' subdomain = __opts__.get('bamboohr', {}).get('subdomain', None) path = 'https://api.bamboohr.com/api/gateway.php/{0}/v1/'.format( subdomain ) if action: path += action if command: path += '/{0}'.format(command) log.debug('BambooHR URL: %s', path) if not isinstance(args, dict): args = {} return_content = None result = salt.utils.http.query( path, method, username=_apikey(), password='saltypork', params=args, data=data, decode=False, text=True, status=True, opts=__opts__, ) log.debug('BambooHR Response Status Code: %s', result['status']) return [result['status'], result['text']]
[ "def", "_query", "(", "action", "=", "None", ",", "command", "=", "None", ",", "args", "=", "None", ",", "method", "=", "'GET'", ",", "data", "=", "None", ")", ":", "subdomain", "=", "__opts__", ".", "get", "(", "'bamboohr'", ",", "{", "}", ")", ...
Make a web call to BambooHR The password can be any random text, so we chose Salty text.
[ "Make", "a", "web", "call", "to", "BambooHR" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bamboohr.py#L247-L288
train
saltstack/salt
salt/spm/pkgdb/sqlite3.py
init
def init(): ''' Get an sqlite3 connection, and initialize the package database if necessary ''' if not os.path.exists(__opts__['spm_cache_dir']): log.debug('Creating SPM cache directory at %s', __opts__['spm_db']) os.makedirs(__opts__['spm_cache_dir']) if not os.path.exists(__opts__['spm_db']): log.debug('Creating new package database at %s', __opts__['spm_db']) sqlite3.enable_callback_tracebacks(True) conn = sqlite3.connect(__opts__['spm_db'], isolation_level=None) try: conn.execute('SELECT count(*) FROM packages') except OperationalError: conn.execute('''CREATE TABLE packages ( package text, version text, release text, installed text, os text, os_family text, dependencies text, os_dependencies text, os_family_dependencies text, summary text, description text )''') try: conn.execute('SELECT count(*) FROM files') except OperationalError: conn.execute('''CREATE TABLE files ( package text, path text, size real, mode text, sum text, major text, minor text, linkname text, linkpath text, uname text, gname text, mtime text )''') return conn
python
def init(): ''' Get an sqlite3 connection, and initialize the package database if necessary ''' if not os.path.exists(__opts__['spm_cache_dir']): log.debug('Creating SPM cache directory at %s', __opts__['spm_db']) os.makedirs(__opts__['spm_cache_dir']) if not os.path.exists(__opts__['spm_db']): log.debug('Creating new package database at %s', __opts__['spm_db']) sqlite3.enable_callback_tracebacks(True) conn = sqlite3.connect(__opts__['spm_db'], isolation_level=None) try: conn.execute('SELECT count(*) FROM packages') except OperationalError: conn.execute('''CREATE TABLE packages ( package text, version text, release text, installed text, os text, os_family text, dependencies text, os_dependencies text, os_family_dependencies text, summary text, description text )''') try: conn.execute('SELECT count(*) FROM files') except OperationalError: conn.execute('''CREATE TABLE files ( package text, path text, size real, mode text, sum text, major text, minor text, linkname text, linkpath text, uname text, gname text, mtime text )''') return conn
[ "def", "init", "(", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "__opts__", "[", "'spm_cache_dir'", "]", ")", ":", "log", ".", "debug", "(", "'Creating SPM cache directory at %s'", ",", "__opts__", "[", "'spm_db'", "]", ")", "os", ".", ...
Get an sqlite3 connection, and initialize the package database if necessary
[ "Get", "an", "sqlite3", "connection", "and", "initialize", "the", "package", "database", "if", "necessary" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/spm/pkgdb/sqlite3.py#L20-L69
train
saltstack/salt
salt/spm/pkgdb/sqlite3.py
info
def info(package, conn=None): ''' List info for a package ''' close = False if conn is None: close = True conn = init() fields = ( 'package', 'version', 'release', 'installed', 'os', 'os_family', 'dependencies', 'os_dependencies', 'os_family_dependencies', 'summary', 'description', ) data = conn.execute( 'SELECT {0} FROM packages WHERE package=?'.format(','.join(fields)), (package, ) ) row = data.fetchone() if close: conn.close() if not row: return None formula_def = dict(list(zip(fields, row))) formula_def['name'] = formula_def['package'] return formula_def
python
def info(package, conn=None): ''' List info for a package ''' close = False if conn is None: close = True conn = init() fields = ( 'package', 'version', 'release', 'installed', 'os', 'os_family', 'dependencies', 'os_dependencies', 'os_family_dependencies', 'summary', 'description', ) data = conn.execute( 'SELECT {0} FROM packages WHERE package=?'.format(','.join(fields)), (package, ) ) row = data.fetchone() if close: conn.close() if not row: return None formula_def = dict(list(zip(fields, row))) formula_def['name'] = formula_def['package'] return formula_def
[ "def", "info", "(", "package", ",", "conn", "=", "None", ")", ":", "close", "=", "False", "if", "conn", "is", "None", ":", "close", "=", "True", "conn", "=", "init", "(", ")", "fields", "=", "(", "'package'", ",", "'version'", ",", "'release'", ","...
List info for a package
[ "List", "info", "for", "a", "package" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/spm/pkgdb/sqlite3.py#L72-L107
train
saltstack/salt
salt/spm/pkgdb/sqlite3.py
list_packages
def list_packages(conn=None): ''' List files for an installed package ''' close = False if conn is None: close = True conn = init() ret = [] data = conn.execute('SELECT package FROM packages') for pkg in data.fetchall(): ret.append(pkg) if close: conn.close() return ret
python
def list_packages(conn=None): ''' List files for an installed package ''' close = False if conn is None: close = True conn = init() ret = [] data = conn.execute('SELECT package FROM packages') for pkg in data.fetchall(): ret.append(pkg) if close: conn.close() return ret
[ "def", "list_packages", "(", "conn", "=", "None", ")", ":", "close", "=", "False", "if", "conn", "is", "None", ":", "close", "=", "True", "conn", "=", "init", "(", ")", "ret", "=", "[", "]", "data", "=", "conn", ".", "execute", "(", "'SELECT packag...
List files for an installed package
[ "List", "files", "for", "an", "installed", "package" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/spm/pkgdb/sqlite3.py#L110-L126
train
saltstack/salt
salt/spm/pkgdb/sqlite3.py
list_files
def list_files(package, conn=None): ''' List files for an installed package ''' close = False if conn is None: close = True conn = init() data = conn.execute('SELECT package FROM packages WHERE package=?', (package, )) if not data.fetchone(): if close: conn.close() return None ret = [] data = conn.execute('SELECT path, sum FROM files WHERE package=?', (package, )) for file_ in data.fetchall(): ret.append(file_) if close: conn.close() return ret
python
def list_files(package, conn=None): ''' List files for an installed package ''' close = False if conn is None: close = True conn = init() data = conn.execute('SELECT package FROM packages WHERE package=?', (package, )) if not data.fetchone(): if close: conn.close() return None ret = [] data = conn.execute('SELECT path, sum FROM files WHERE package=?', (package, )) for file_ in data.fetchall(): ret.append(file_) if close: conn.close() return ret
[ "def", "list_files", "(", "package", ",", "conn", "=", "None", ")", ":", "close", "=", "False", "if", "conn", "is", "None", ":", "close", "=", "True", "conn", "=", "init", "(", ")", "data", "=", "conn", ".", "execute", "(", "'SELECT package FROM packag...
List files for an installed package
[ "List", "files", "for", "an", "installed", "package" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/spm/pkgdb/sqlite3.py#L129-L151
train
saltstack/salt
salt/spm/pkgdb/sqlite3.py
register_pkg
def register_pkg(name, formula_def, conn=None): ''' Register a package in the package database ''' close = False if conn is None: close = True conn = init() conn.execute('INSERT INTO packages VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', ( name, formula_def['version'], formula_def['release'], datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT'), formula_def.get('os', None), formula_def.get('os_family', None), formula_def.get('dependencies', None), formula_def.get('os_dependencies', None), formula_def.get('os_family_dependencies', None), formula_def['summary'], formula_def['description'], )) if close: conn.close()
python
def register_pkg(name, formula_def, conn=None): ''' Register a package in the package database ''' close = False if conn is None: close = True conn = init() conn.execute('INSERT INTO packages VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', ( name, formula_def['version'], formula_def['release'], datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT'), formula_def.get('os', None), formula_def.get('os_family', None), formula_def.get('dependencies', None), formula_def.get('os_dependencies', None), formula_def.get('os_family_dependencies', None), formula_def['summary'], formula_def['description'], )) if close: conn.close()
[ "def", "register_pkg", "(", "name", ",", "formula_def", ",", "conn", "=", "None", ")", ":", "close", "=", "False", "if", "conn", "is", "None", ":", "close", "=", "True", "conn", "=", "init", "(", ")", "conn", ".", "execute", "(", "'INSERT INTO packages...
Register a package in the package database
[ "Register", "a", "package", "in", "the", "package", "database" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/spm/pkgdb/sqlite3.py#L154-L177
train
saltstack/salt
salt/spm/pkgdb/sqlite3.py
register_file
def register_file(name, member, path, digest='', conn=None): ''' Register a file in the package database ''' close = False if conn is None: close = True conn = init() conn.execute('INSERT INTO files VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', ( name, '{0}/{1}'.format(path, member.path), member.size, member.mode, digest, member.devmajor, member.devminor, member.linkname, member.linkpath, member.uname, member.gname, member.mtime )) if close: conn.close()
python
def register_file(name, member, path, digest='', conn=None): ''' Register a file in the package database ''' close = False if conn is None: close = True conn = init() conn.execute('INSERT INTO files VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', ( name, '{0}/{1}'.format(path, member.path), member.size, member.mode, digest, member.devmajor, member.devminor, member.linkname, member.linkpath, member.uname, member.gname, member.mtime )) if close: conn.close()
[ "def", "register_file", "(", "name", ",", "member", ",", "path", ",", "digest", "=", "''", ",", "conn", "=", "None", ")", ":", "close", "=", "False", "if", "conn", "is", "None", ":", "close", "=", "True", "conn", "=", "init", "(", ")", "conn", "....
Register a file in the package database
[ "Register", "a", "file", "in", "the", "package", "database" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/spm/pkgdb/sqlite3.py#L180-L204
train
saltstack/salt
salt/spm/pkgdb/sqlite3.py
unregister_file
def unregister_file(path, pkg=None, conn=None): # pylint: disable=W0612 ''' Unregister a file from the package database ''' close = False if conn is None: close = True conn = init() conn.execute('DELETE FROM files WHERE path=?', (path, )) if close: conn.close()
python
def unregister_file(path, pkg=None, conn=None): # pylint: disable=W0612 ''' Unregister a file from the package database ''' close = False if conn is None: close = True conn = init() conn.execute('DELETE FROM files WHERE path=?', (path, )) if close: conn.close()
[ "def", "unregister_file", "(", "path", ",", "pkg", "=", "None", ",", "conn", "=", "None", ")", ":", "# pylint: disable=W0612", "close", "=", "False", "if", "conn", "is", "None", ":", "close", "=", "True", "conn", "=", "init", "(", ")", "conn", ".", "...
Unregister a file from the package database
[ "Unregister", "a", "file", "from", "the", "package", "database" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/spm/pkgdb/sqlite3.py#L217-L228
train
saltstack/salt
salt/proxy/bluecoat_sslv.py
init
def init(opts): ''' This function gets called when the proxy starts up. ''' if 'host' not in opts['proxy']: log.critical('No \'host\' key found in pillar for this proxy.') return False if 'username' not in opts['proxy']: log.critical('No \'username\' key found in pillar for this proxy.') return False if 'password' not in opts['proxy']: log.critical('No \'passwords\' key found in pillar for this proxy.') return False if 'auth' not in opts['proxy']: log.critical('No \'auth\' key found in pillar for this proxy.') return False DETAILS['url'] = 'https://{0}/json'.format(opts['proxy']['host']) DETAILS['headers'] = {'Content-Type': 'application/json-rpc'} # Set configuration details DETAILS['host'] = opts['proxy']['host'] DETAILS['username'] = opts['proxy'].get('username') DETAILS['password'] = opts['proxy'].get('password') DETAILS['auth'] = opts['proxy'].get('auth') # Ensure connectivity to the device log.debug("Attempting to connect to bluecoat_sslv proxy host.") session, cookies, csrf_token = logon() log.debug("Successfully connected to bluecoat_sslv proxy host.") logout(session, cookies, csrf_token) DETAILS['initialized'] = True
python
def init(opts): ''' This function gets called when the proxy starts up. ''' if 'host' not in opts['proxy']: log.critical('No \'host\' key found in pillar for this proxy.') return False if 'username' not in opts['proxy']: log.critical('No \'username\' key found in pillar for this proxy.') return False if 'password' not in opts['proxy']: log.critical('No \'passwords\' key found in pillar for this proxy.') return False if 'auth' not in opts['proxy']: log.critical('No \'auth\' key found in pillar for this proxy.') return False DETAILS['url'] = 'https://{0}/json'.format(opts['proxy']['host']) DETAILS['headers'] = {'Content-Type': 'application/json-rpc'} # Set configuration details DETAILS['host'] = opts['proxy']['host'] DETAILS['username'] = opts['proxy'].get('username') DETAILS['password'] = opts['proxy'].get('password') DETAILS['auth'] = opts['proxy'].get('auth') # Ensure connectivity to the device log.debug("Attempting to connect to bluecoat_sslv proxy host.") session, cookies, csrf_token = logon() log.debug("Successfully connected to bluecoat_sslv proxy host.") logout(session, cookies, csrf_token) DETAILS['initialized'] = True
[ "def", "init", "(", "opts", ")", ":", "if", "'host'", "not", "in", "opts", "[", "'proxy'", "]", ":", "log", ".", "critical", "(", "'No \\'host\\' key found in pillar for this proxy.'", ")", "return", "False", "if", "'username'", "not", "in", "opts", "[", "'p...
This function gets called when the proxy starts up.
[ "This", "function", "gets", "called", "when", "the", "proxy", "starts", "up", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/bluecoat_sslv.py#L110-L142
train
saltstack/salt
salt/proxy/bluecoat_sslv.py
call
def call(payload, apply_changes=False): ''' Sends a post command to the device and returns the decoded data. ''' session, cookies, csrf_token = logon() response = _post_request(session, payload, cookies, csrf_token) if apply_changes: apply_payload = {"jsonrpc": "2.0", "id": "ID1", "method": "apply_policy_changes", "params": []} _post_request(session, apply_payload, cookies, csrf_token) logout(session, cookies, csrf_token) return response
python
def call(payload, apply_changes=False): ''' Sends a post command to the device and returns the decoded data. ''' session, cookies, csrf_token = logon() response = _post_request(session, payload, cookies, csrf_token) if apply_changes: apply_payload = {"jsonrpc": "2.0", "id": "ID1", "method": "apply_policy_changes", "params": []} _post_request(session, apply_payload, cookies, csrf_token) logout(session, cookies, csrf_token) return response
[ "def", "call", "(", "payload", ",", "apply_changes", "=", "False", ")", ":", "session", ",", "cookies", ",", "csrf_token", "=", "logon", "(", ")", "response", "=", "_post_request", "(", "session", ",", "payload", ",", "cookies", ",", "csrf_token", ")", "...
Sends a post command to the device and returns the decoded data.
[ "Sends", "a", "post", "command", "to", "the", "device", "and", "returns", "the", "decoded", "data", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/bluecoat_sslv.py#L145-L158
train
saltstack/salt
salt/proxy/bluecoat_sslv.py
logon
def logon(): ''' Logs into the bluecoat_sslv device and returns the session cookies. ''' session = requests.session() payload = {"jsonrpc": "2.0", "id": "ID0", "method": "login", "params": [DETAILS['username'], DETAILS['password'], DETAILS['auth'], True] } logon_response = session.post(DETAILS['url'], data=json.dumps(payload), verify=False) if logon_response.status_code != 200: log.error("Error logging into proxy. HTTP Error code: %s", logon_response.status_code) raise salt.exceptions.CommandExecutionError( "Did not receive a valid response from host.") try: cookies = {'sslng_csrf_token': logon_response.cookies['sslng_csrf_token'], 'sslng_session_id': logon_response.cookies['sslng_session_id']} csrf_token = logon_response.cookies['sslng_csrf_token'] except KeyError: log.error("Unable to authentication to the bluecoat_sslv proxy.") raise salt.exceptions.CommandExecutionError( "Did not receive a valid response from host.") return session, cookies, csrf_token
python
def logon(): ''' Logs into the bluecoat_sslv device and returns the session cookies. ''' session = requests.session() payload = {"jsonrpc": "2.0", "id": "ID0", "method": "login", "params": [DETAILS['username'], DETAILS['password'], DETAILS['auth'], True] } logon_response = session.post(DETAILS['url'], data=json.dumps(payload), verify=False) if logon_response.status_code != 200: log.error("Error logging into proxy. HTTP Error code: %s", logon_response.status_code) raise salt.exceptions.CommandExecutionError( "Did not receive a valid response from host.") try: cookies = {'sslng_csrf_token': logon_response.cookies['sslng_csrf_token'], 'sslng_session_id': logon_response.cookies['sslng_session_id']} csrf_token = logon_response.cookies['sslng_csrf_token'] except KeyError: log.error("Unable to authentication to the bluecoat_sslv proxy.") raise salt.exceptions.CommandExecutionError( "Did not receive a valid response from host.") return session, cookies, csrf_token
[ "def", "logon", "(", ")", ":", "session", "=", "requests", ".", "session", "(", ")", "payload", "=", "{", "\"jsonrpc\"", ":", "\"2.0\"", ",", "\"id\"", ":", "\"ID0\"", ",", "\"method\"", ":", "\"login\"", ",", "\"params\"", ":", "[", "DETAILS", "[", "'...
Logs into the bluecoat_sslv device and returns the session cookies.
[ "Logs", "into", "the", "bluecoat_sslv", "device", "and", "returns", "the", "session", "cookies", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/bluecoat_sslv.py#L170-L198
train
saltstack/salt
salt/proxy/bluecoat_sslv.py
logout
def logout(session, cookies, csrf_token): ''' Closes the session with the device. ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "logout", "params": [] } session.post(DETAILS['url'], data=json.dumps(payload), cookies=cookies, headers={'X-CSRF-Token': csrf_token})
python
def logout(session, cookies, csrf_token): ''' Closes the session with the device. ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "logout", "params": [] } session.post(DETAILS['url'], data=json.dumps(payload), cookies=cookies, headers={'X-CSRF-Token': csrf_token})
[ "def", "logout", "(", "session", ",", "cookies", ",", "csrf_token", ")", ":", "payload", "=", "{", "\"jsonrpc\"", ":", "\"2.0\"", ",", "\"id\"", ":", "\"ID0\"", ",", "\"method\"", ":", "\"logout\"", ",", "\"params\"", ":", "[", "]", "}", "session", ".", ...
Closes the session with the device.
[ "Closes", "the", "session", "with", "the", "device", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/bluecoat_sslv.py#L201-L213
train
saltstack/salt
salt/proxy/bluecoat_sslv.py
grains
def grains(): ''' Get the grains from the proxied device ''' if not DETAILS.get('grains_cache', {}): DETAILS['grains_cache'] = GRAINS_CACHE try: DETAILS['grains_cache'] = _get_grain_information() except salt.exceptions.CommandExecutionError: pass except Exception as err: log.error(err) return DETAILS['grains_cache']
python
def grains(): ''' Get the grains from the proxied device ''' if not DETAILS.get('grains_cache', {}): DETAILS['grains_cache'] = GRAINS_CACHE try: DETAILS['grains_cache'] = _get_grain_information() except salt.exceptions.CommandExecutionError: pass except Exception as err: log.error(err) return DETAILS['grains_cache']
[ "def", "grains", "(", ")", ":", "if", "not", "DETAILS", ".", "get", "(", "'grains_cache'", ",", "{", "}", ")", ":", "DETAILS", "[", "'grains_cache'", "]", "=", "GRAINS_CACHE", "try", ":", "DETAILS", "[", "'grains_cache'", "]", "=", "_get_grain_information"...
Get the grains from the proxied device
[ "Get", "the", "grains", "from", "the", "proxied", "device" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/bluecoat_sslv.py#L250-L262
train
saltstack/salt
salt/proxy/bluecoat_sslv.py
ping
def ping(): ''' Returns true if the device is reachable, else false. ''' try: session, cookies, csrf_token = logon() logout(session, cookies, csrf_token) except salt.exceptions.CommandExecutionError: return False except Exception as err: log.debug(err) return False return True
python
def ping(): ''' Returns true if the device is reachable, else false. ''' try: session, cookies, csrf_token = logon() logout(session, cookies, csrf_token) except salt.exceptions.CommandExecutionError: return False except Exception as err: log.debug(err) return False return True
[ "def", "ping", "(", ")", ":", "try", ":", "session", ",", "cookies", ",", "csrf_token", "=", "logon", "(", ")", "logout", "(", "session", ",", "cookies", ",", "csrf_token", ")", "except", "salt", ".", "exceptions", ".", "CommandExecutionError", ":", "ret...
Returns true if the device is reachable, else false.
[ "Returns", "true", "if", "the", "device", "is", "reachable", "else", "false", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/bluecoat_sslv.py#L273-L285
train
saltstack/salt
salt/runners/ssh.py
cmd
def cmd(tgt, fun, arg=(), timeout=None, tgt_type='glob', kwarg=None): ''' .. versionadded:: 2015.5.0 .. versionchanged:: 2017.7.0 The ``expr_form`` argument has been renamed to ``tgt_type``, earlier releases must use ``expr_form``. Execute a single command via the salt-ssh subsystem and return all routines at once A wrapper around the :py:meth:`SSHClient.cmd <salt.client.ssh.client.SSHClient.cmd>` method. ''' client = salt.client.ssh.client.SSHClient(mopts=__opts__) return client.cmd( tgt, fun, arg, timeout, tgt_type, kwarg)
python
def cmd(tgt, fun, arg=(), timeout=None, tgt_type='glob', kwarg=None): ''' .. versionadded:: 2015.5.0 .. versionchanged:: 2017.7.0 The ``expr_form`` argument has been renamed to ``tgt_type``, earlier releases must use ``expr_form``. Execute a single command via the salt-ssh subsystem and return all routines at once A wrapper around the :py:meth:`SSHClient.cmd <salt.client.ssh.client.SSHClient.cmd>` method. ''' client = salt.client.ssh.client.SSHClient(mopts=__opts__) return client.cmd( tgt, fun, arg, timeout, tgt_type, kwarg)
[ "def", "cmd", "(", "tgt", ",", "fun", ",", "arg", "=", "(", ")", ",", "timeout", "=", "None", ",", "tgt_type", "=", "'glob'", ",", "kwarg", "=", "None", ")", ":", "client", "=", "salt", ".", "client", ".", "ssh", ".", "client", ".", "SSHClient", ...
.. versionadded:: 2015.5.0 .. versionchanged:: 2017.7.0 The ``expr_form`` argument has been renamed to ``tgt_type``, earlier releases must use ``expr_form``. Execute a single command via the salt-ssh subsystem and return all routines at once A wrapper around the :py:meth:`SSHClient.cmd <salt.client.ssh.client.SSHClient.cmd>` method.
[ "..", "versionadded", "::", "2015", ".", "5", ".", "0", "..", "versionchanged", "::", "2017", ".", "7", ".", "0", "The", "expr_form", "argument", "has", "been", "renamed", "to", "tgt_type", "earlier", "releases", "must", "use", "expr_form", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/ssh.py#L15-L40
train
saltstack/salt
salt/tokens/localfs.py
mk_token
def mk_token(opts, tdata): ''' Mint a new token using the config option hash_type and store tdata with 'token' attribute set to the token. This module uses the hash of random 512 bytes as a token. :param opts: Salt master config options :param tdata: Token data to be stored with 'token' attirbute of this dict set to the token. :returns: tdata with token if successful. Empty dict if failed. ''' hash_type = getattr(hashlib, opts.get('hash_type', 'md5')) tok = six.text_type(hash_type(os.urandom(512)).hexdigest()) t_path = os.path.join(opts['token_dir'], tok) while os.path.isfile(t_path): tok = six.text_type(hash_type(os.urandom(512)).hexdigest()) t_path = os.path.join(opts['token_dir'], tok) tdata['token'] = tok serial = salt.payload.Serial(opts) try: with salt.utils.files.set_umask(0o177): with salt.utils.files.fopen(t_path, 'w+b') as fp_: fp_.write(serial.dumps(tdata)) except (IOError, OSError): log.warning( 'Authentication failure: can not write token file "%s".', t_path) return {} return tdata
python
def mk_token(opts, tdata): ''' Mint a new token using the config option hash_type and store tdata with 'token' attribute set to the token. This module uses the hash of random 512 bytes as a token. :param opts: Salt master config options :param tdata: Token data to be stored with 'token' attirbute of this dict set to the token. :returns: tdata with token if successful. Empty dict if failed. ''' hash_type = getattr(hashlib, opts.get('hash_type', 'md5')) tok = six.text_type(hash_type(os.urandom(512)).hexdigest()) t_path = os.path.join(opts['token_dir'], tok) while os.path.isfile(t_path): tok = six.text_type(hash_type(os.urandom(512)).hexdigest()) t_path = os.path.join(opts['token_dir'], tok) tdata['token'] = tok serial = salt.payload.Serial(opts) try: with salt.utils.files.set_umask(0o177): with salt.utils.files.fopen(t_path, 'w+b') as fp_: fp_.write(serial.dumps(tdata)) except (IOError, OSError): log.warning( 'Authentication failure: can not write token file "%s".', t_path) return {} return tdata
[ "def", "mk_token", "(", "opts", ",", "tdata", ")", ":", "hash_type", "=", "getattr", "(", "hashlib", ",", "opts", ".", "get", "(", "'hash_type'", ",", "'md5'", ")", ")", "tok", "=", "six", ".", "text_type", "(", "hash_type", "(", "os", ".", "urandom"...
Mint a new token using the config option hash_type and store tdata with 'token' attribute set to the token. This module uses the hash of random 512 bytes as a token. :param opts: Salt master config options :param tdata: Token data to be stored with 'token' attirbute of this dict set to the token. :returns: tdata with token if successful. Empty dict if failed.
[ "Mint", "a", "new", "token", "using", "the", "config", "option", "hash_type", "and", "store", "tdata", "with", "token", "attribute", "set", "to", "the", "token", ".", "This", "module", "uses", "the", "hash", "of", "random", "512", "bytes", "as", "a", "to...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/tokens/localfs.py#L24-L50
train
saltstack/salt
salt/tokens/localfs.py
get_token
def get_token(opts, tok): ''' Fetch the token data from the store. :param opts: Salt master config options :param tok: Token value to get :returns: Token data if successful. Empty dict if failed. ''' t_path = os.path.join(opts['token_dir'], tok) if not os.path.isfile(t_path): return {} serial = salt.payload.Serial(opts) try: with salt.utils.files.fopen(t_path, 'rb') as fp_: tdata = serial.loads(fp_.read()) return tdata except (IOError, OSError): log.warning( 'Authentication failure: can not read token file "%s".', t_path) return {}
python
def get_token(opts, tok): ''' Fetch the token data from the store. :param opts: Salt master config options :param tok: Token value to get :returns: Token data if successful. Empty dict if failed. ''' t_path = os.path.join(opts['token_dir'], tok) if not os.path.isfile(t_path): return {} serial = salt.payload.Serial(opts) try: with salt.utils.files.fopen(t_path, 'rb') as fp_: tdata = serial.loads(fp_.read()) return tdata except (IOError, OSError): log.warning( 'Authentication failure: can not read token file "%s".', t_path) return {}
[ "def", "get_token", "(", "opts", ",", "tok", ")", ":", "t_path", "=", "os", ".", "path", ".", "join", "(", "opts", "[", "'token_dir'", "]", ",", "tok", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "t_path", ")", ":", "return", "{", ...
Fetch the token data from the store. :param opts: Salt master config options :param tok: Token value to get :returns: Token data if successful. Empty dict if failed.
[ "Fetch", "the", "token", "data", "from", "the", "store", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/tokens/localfs.py#L53-L72
train
saltstack/salt
salt/tokens/localfs.py
rm_token
def rm_token(opts, tok): ''' Remove token from the store. :param opts: Salt master config options :param tok: Token to remove :returns: Empty dict if successful. None if failed. ''' t_path = os.path.join(opts['token_dir'], tok) try: os.remove(t_path) return {} except (IOError, OSError): log.warning('Could not remove token %s', tok)
python
def rm_token(opts, tok): ''' Remove token from the store. :param opts: Salt master config options :param tok: Token to remove :returns: Empty dict if successful. None if failed. ''' t_path = os.path.join(opts['token_dir'], tok) try: os.remove(t_path) return {} except (IOError, OSError): log.warning('Could not remove token %s', tok)
[ "def", "rm_token", "(", "opts", ",", "tok", ")", ":", "t_path", "=", "os", ".", "path", ".", "join", "(", "opts", "[", "'token_dir'", "]", ",", "tok", ")", "try", ":", "os", ".", "remove", "(", "t_path", ")", "return", "{", "}", "except", "(", ...
Remove token from the store. :param opts: Salt master config options :param tok: Token to remove :returns: Empty dict if successful. None if failed.
[ "Remove", "token", "from", "the", "store", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/tokens/localfs.py#L75-L88
train
saltstack/salt
salt/tokens/localfs.py
list_tokens
def list_tokens(opts): ''' List all tokens in the store. :param opts: Salt master config options :returns: List of dicts (tokens) ''' ret = [] for (dirpath, dirnames, filenames) in salt.utils.path.os_walk(opts['token_dir']): for token in filenames: ret.append(token) return ret
python
def list_tokens(opts): ''' List all tokens in the store. :param opts: Salt master config options :returns: List of dicts (tokens) ''' ret = [] for (dirpath, dirnames, filenames) in salt.utils.path.os_walk(opts['token_dir']): for token in filenames: ret.append(token) return ret
[ "def", "list_tokens", "(", "opts", ")", ":", "ret", "=", "[", "]", "for", "(", "dirpath", ",", "dirnames", ",", "filenames", ")", "in", "salt", ".", "utils", ".", "path", ".", "os_walk", "(", "opts", "[", "'token_dir'", "]", ")", ":", "for", "token...
List all tokens in the store. :param opts: Salt master config options :returns: List of dicts (tokens)
[ "List", "all", "tokens", "in", "the", "store", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/tokens/localfs.py#L91-L102
train
saltstack/salt
salt/utils/path.py
islink
def islink(path): ''' Equivalent to os.path.islink() ''' if six.PY3 or not salt.utils.platform.is_windows(): return os.path.islink(path) if not HAS_WIN32FILE: log.error('Cannot check if %s is a link, missing required modules', path) if not _is_reparse_point(path): return False # check that it is a symlink reparse point (in case it is something else, # like a mount point) reparse_data = _get_reparse_data(path) # sanity check - this should not happen if not reparse_data: # not a reparse point return False # REPARSE_DATA_BUFFER structure - see # http://msdn.microsoft.com/en-us/library/ff552012.aspx # parse the structure header to work out which type of reparse point this is header_parser = struct.Struct('L') ReparseTag, = header_parser.unpack(reparse_data[:header_parser.size]) # http://msdn.microsoft.com/en-us/library/windows/desktop/aa365511.aspx if not ReparseTag & 0xA000FFFF == 0xA000000C: return False else: return True
python
def islink(path): ''' Equivalent to os.path.islink() ''' if six.PY3 or not salt.utils.platform.is_windows(): return os.path.islink(path) if not HAS_WIN32FILE: log.error('Cannot check if %s is a link, missing required modules', path) if not _is_reparse_point(path): return False # check that it is a symlink reparse point (in case it is something else, # like a mount point) reparse_data = _get_reparse_data(path) # sanity check - this should not happen if not reparse_data: # not a reparse point return False # REPARSE_DATA_BUFFER structure - see # http://msdn.microsoft.com/en-us/library/ff552012.aspx # parse the structure header to work out which type of reparse point this is header_parser = struct.Struct('L') ReparseTag, = header_parser.unpack(reparse_data[:header_parser.size]) # http://msdn.microsoft.com/en-us/library/windows/desktop/aa365511.aspx if not ReparseTag & 0xA000FFFF == 0xA000000C: return False else: return True
[ "def", "islink", "(", "path", ")", ":", "if", "six", ".", "PY3", "or", "not", "salt", ".", "utils", ".", "platform", ".", "is_windows", "(", ")", ":", "return", "os", ".", "path", ".", "islink", "(", "path", ")", "if", "not", "HAS_WIN32FILE", ":", ...
Equivalent to os.path.islink()
[ "Equivalent", "to", "os", ".", "path", ".", "islink", "()" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/path.py#L41-L73
train
saltstack/salt
salt/utils/path.py
readlink
def readlink(path): ''' Equivalent to os.readlink() ''' if six.PY3 or not salt.utils.platform.is_windows(): return os.readlink(path) if not HAS_WIN32FILE: log.error('Cannot read %s, missing required modules', path) reparse_data = _get_reparse_data(path) if not reparse_data: # Reproduce *NIX behavior when os.readlink is performed on a path that # is not a symbolic link. raise OSError(errno.EINVAL, 'Invalid argument: \'{0}\''.format(path)) # REPARSE_DATA_BUFFER structure - see # http://msdn.microsoft.com/en-us/library/ff552012.aspx # parse the structure header to work out which type of reparse point this is header_parser = struct.Struct('L') ReparseTag, = header_parser.unpack(reparse_data[:header_parser.size]) # http://msdn.microsoft.com/en-us/library/windows/desktop/aa365511.aspx if not ReparseTag & 0xA000FFFF == 0xA000000C: raise OSError( errno.EINVAL, '{0} is not a symlink, but another type of reparse point ' '(0x{0:X}).'.format(ReparseTag) ) # parse as a symlink reparse point structure (the structure for other # reparse points is different) data_parser = struct.Struct('LHHHHHHL') ReparseTag, ReparseDataLength, Reserved, SubstituteNameOffset, \ SubstituteNameLength, PrintNameOffset, \ PrintNameLength, Flags = data_parser.unpack(reparse_data[:data_parser.size]) path_buffer_offset = data_parser.size absolute_substitute_name_offset = path_buffer_offset + SubstituteNameOffset target_bytes = reparse_data[absolute_substitute_name_offset:absolute_substitute_name_offset+SubstituteNameLength] target = target_bytes.decode('UTF-16') if target.startswith('\\??\\'): target = target[4:] try: # comes out in 8.3 form; convert it to LFN to make it look nicer target = win32file.GetLongPathName(target) except pywinerror as exc: # If target is on a UNC share, the decoded target will be in the format # "UNC\hostanme\sharename\additional\subdirs\under\share". So, in # these cases, return the target path in the proper UNC path format. if target.startswith('UNC\\'): return re.sub(r'^UNC\\+', r'\\\\', target) # if file is not found (i.e. bad symlink), return it anyway like on *nix if exc.winerror == 2: return target raise return target
python
def readlink(path): ''' Equivalent to os.readlink() ''' if six.PY3 or not salt.utils.platform.is_windows(): return os.readlink(path) if not HAS_WIN32FILE: log.error('Cannot read %s, missing required modules', path) reparse_data = _get_reparse_data(path) if not reparse_data: # Reproduce *NIX behavior when os.readlink is performed on a path that # is not a symbolic link. raise OSError(errno.EINVAL, 'Invalid argument: \'{0}\''.format(path)) # REPARSE_DATA_BUFFER structure - see # http://msdn.microsoft.com/en-us/library/ff552012.aspx # parse the structure header to work out which type of reparse point this is header_parser = struct.Struct('L') ReparseTag, = header_parser.unpack(reparse_data[:header_parser.size]) # http://msdn.microsoft.com/en-us/library/windows/desktop/aa365511.aspx if not ReparseTag & 0xA000FFFF == 0xA000000C: raise OSError( errno.EINVAL, '{0} is not a symlink, but another type of reparse point ' '(0x{0:X}).'.format(ReparseTag) ) # parse as a symlink reparse point structure (the structure for other # reparse points is different) data_parser = struct.Struct('LHHHHHHL') ReparseTag, ReparseDataLength, Reserved, SubstituteNameOffset, \ SubstituteNameLength, PrintNameOffset, \ PrintNameLength, Flags = data_parser.unpack(reparse_data[:data_parser.size]) path_buffer_offset = data_parser.size absolute_substitute_name_offset = path_buffer_offset + SubstituteNameOffset target_bytes = reparse_data[absolute_substitute_name_offset:absolute_substitute_name_offset+SubstituteNameLength] target = target_bytes.decode('UTF-16') if target.startswith('\\??\\'): target = target[4:] try: # comes out in 8.3 form; convert it to LFN to make it look nicer target = win32file.GetLongPathName(target) except pywinerror as exc: # If target is on a UNC share, the decoded target will be in the format # "UNC\hostanme\sharename\additional\subdirs\under\share". So, in # these cases, return the target path in the proper UNC path format. if target.startswith('UNC\\'): return re.sub(r'^UNC\\+', r'\\\\', target) # if file is not found (i.e. bad symlink), return it anyway like on *nix if exc.winerror == 2: return target raise return target
[ "def", "readlink", "(", "path", ")", ":", "if", "six", ".", "PY3", "or", "not", "salt", ".", "utils", ".", "platform", ".", "is_windows", "(", ")", ":", "return", "os", ".", "readlink", "(", "path", ")", "if", "not", "HAS_WIN32FILE", ":", "log", "....
Equivalent to os.readlink()
[ "Equivalent", "to", "os", ".", "readlink", "()" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/path.py#L76-L136
train
saltstack/salt
salt/utils/path.py
_is_reparse_point
def _is_reparse_point(path): ''' Returns True if path is a reparse point; False otherwise. ''' result = win32file.GetFileAttributesW(path) if result == -1: return False return True if result & 0x400 else False
python
def _is_reparse_point(path): ''' Returns True if path is a reparse point; False otherwise. ''' result = win32file.GetFileAttributesW(path) if result == -1: return False return True if result & 0x400 else False
[ "def", "_is_reparse_point", "(", "path", ")", ":", "result", "=", "win32file", ".", "GetFileAttributesW", "(", "path", ")", "if", "result", "==", "-", "1", ":", "return", "False", "return", "True", "if", "result", "&", "0x400", "else", "False" ]
Returns True if path is a reparse point; False otherwise.
[ "Returns", "True", "if", "path", "is", "a", "reparse", "point", ";", "False", "otherwise", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/path.py#L139-L148
train
saltstack/salt
salt/utils/path.py
_get_reparse_data
def _get_reparse_data(path): ''' Retrieves the reparse point data structure for the given path. If the path is not a reparse point, None is returned. See http://msdn.microsoft.com/en-us/library/ff552012.aspx for details on the REPARSE_DATA_BUFFER structure returned. ''' # ensure paths are using the right slashes path = os.path.normpath(path) if not _is_reparse_point(path): return None fileHandle = None try: fileHandle = win32file.CreateFileW( path, 0x80000000, # GENERIC_READ 1, # share with other readers None, # no inherit, default security descriptor 3, # OPEN_EXISTING 0x00200000 | 0x02000000 # FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS ) reparseData = win32file.DeviceIoControl( fileHandle, 0x900a8, # FSCTL_GET_REPARSE_POINT None, # in buffer 16384 # out buffer size (MAXIMUM_REPARSE_DATA_BUFFER_SIZE) ) finally: if fileHandle: win32file.CloseHandle(fileHandle) return reparseData
python
def _get_reparse_data(path): ''' Retrieves the reparse point data structure for the given path. If the path is not a reparse point, None is returned. See http://msdn.microsoft.com/en-us/library/ff552012.aspx for details on the REPARSE_DATA_BUFFER structure returned. ''' # ensure paths are using the right slashes path = os.path.normpath(path) if not _is_reparse_point(path): return None fileHandle = None try: fileHandle = win32file.CreateFileW( path, 0x80000000, # GENERIC_READ 1, # share with other readers None, # no inherit, default security descriptor 3, # OPEN_EXISTING 0x00200000 | 0x02000000 # FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS ) reparseData = win32file.DeviceIoControl( fileHandle, 0x900a8, # FSCTL_GET_REPARSE_POINT None, # in buffer 16384 # out buffer size (MAXIMUM_REPARSE_DATA_BUFFER_SIZE) ) finally: if fileHandle: win32file.CloseHandle(fileHandle) return reparseData
[ "def", "_get_reparse_data", "(", "path", ")", ":", "# ensure paths are using the right slashes", "path", "=", "os", ".", "path", ".", "normpath", "(", "path", ")", "if", "not", "_is_reparse_point", "(", "path", ")", ":", "return", "None", "fileHandle", "=", "N...
Retrieves the reparse point data structure for the given path. If the path is not a reparse point, None is returned. See http://msdn.microsoft.com/en-us/library/ff552012.aspx for details on the REPARSE_DATA_BUFFER structure returned.
[ "Retrieves", "the", "reparse", "point", "data", "structure", "for", "the", "given", "path", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/path.py#L151-L188
train
saltstack/salt
salt/utils/path.py
which
def which(exe=None): ''' Python clone of /usr/bin/which ''' if not exe: log.error('No executable was passed to be searched by salt.utils.path.which()') return None ## define some utilities (we use closures here because our predecessor used them) def is_executable_common(path): ''' This returns truth if posixy semantics (which python simulates on windows) states that this is executable. ''' return os.path.isfile(path) and os.access(path, os.X_OK) def resolve(path): ''' This will take a path and recursively follow the link until we get to a real file. ''' while os.path.islink(path): res = os.readlink(path) # if the link points to a relative target, then convert it to an # absolute path relative to the original path if not os.path.isabs(res): directory, _ = os.path.split(path) res = join(directory, res) path = res return path # windows-only def has_executable_ext(path, ext_membership): ''' Extract the extension from the specified path, lowercase it so we can be insensitive, and then check it against the available exts. ''' p, ext = os.path.splitext(path) return ext.lower() in ext_membership ## prepare related variables from the environment res = salt.utils.stringutils.to_unicode(os.environ.get('PATH', '')) system_path = res.split(os.pathsep) # add some reasonable defaults in case someone's PATH is busted if not salt.utils.platform.is_windows(): res = set(system_path) extended_path = ['/sbin', '/bin', '/usr/sbin', '/usr/bin', '/usr/local/sbin', '/usr/local/bin'] system_path.extend([p for p in extended_path if p not in res]) ## now to define the semantics of what's considered executable on a given platform if salt.utils.platform.is_windows(): # executable semantics on windows requires us to search PATHEXT res = salt.utils.stringutils.to_str(os.environ.get('PATHEXT', str('.EXE'))) # generate two variables, one of them for O(n) searches (but ordered) # and another for O(1) searches. the previous guy was trying to use # memoization with a function that has no arguments, this provides # the exact same benefit pathext = res.split(os.pathsep) res = {ext.lower() for ext in pathext} # check if our caller already specified a valid extension as then we don't need to match it _, ext = os.path.splitext(exe) if ext.lower() in res: pathext = [''] is_executable = is_executable_common # The specified extension isn't valid, so we just assume it's part of the # filename and proceed to walk the pathext list else: is_executable = lambda path, membership=res: is_executable_common(path) and has_executable_ext(path, membership) else: # in posix, there's no such thing as file extensions..only zuul pathext = [''] # executable semantics are pretty simple on reasonable platforms... is_executable = is_executable_common ## search for the executable # check to see if the full path was specified as then we don't need # to actually walk the system_path for any reason if is_executable(exe): return exe # now to search through our system_path for path in system_path: p = join(path, exe) # iterate through all extensions to see which one is executable for ext in pathext: pext = p + ext rp = resolve(pext) if is_executable(rp): return p + ext continue continue ## if something was executable, we should've found it already... log.trace( '\'%s\' could not be found in the following search path: \'%s\'', exe, system_path ) return None
python
def which(exe=None): ''' Python clone of /usr/bin/which ''' if not exe: log.error('No executable was passed to be searched by salt.utils.path.which()') return None ## define some utilities (we use closures here because our predecessor used them) def is_executable_common(path): ''' This returns truth if posixy semantics (which python simulates on windows) states that this is executable. ''' return os.path.isfile(path) and os.access(path, os.X_OK) def resolve(path): ''' This will take a path and recursively follow the link until we get to a real file. ''' while os.path.islink(path): res = os.readlink(path) # if the link points to a relative target, then convert it to an # absolute path relative to the original path if not os.path.isabs(res): directory, _ = os.path.split(path) res = join(directory, res) path = res return path # windows-only def has_executable_ext(path, ext_membership): ''' Extract the extension from the specified path, lowercase it so we can be insensitive, and then check it against the available exts. ''' p, ext = os.path.splitext(path) return ext.lower() in ext_membership ## prepare related variables from the environment res = salt.utils.stringutils.to_unicode(os.environ.get('PATH', '')) system_path = res.split(os.pathsep) # add some reasonable defaults in case someone's PATH is busted if not salt.utils.platform.is_windows(): res = set(system_path) extended_path = ['/sbin', '/bin', '/usr/sbin', '/usr/bin', '/usr/local/sbin', '/usr/local/bin'] system_path.extend([p for p in extended_path if p not in res]) ## now to define the semantics of what's considered executable on a given platform if salt.utils.platform.is_windows(): # executable semantics on windows requires us to search PATHEXT res = salt.utils.stringutils.to_str(os.environ.get('PATHEXT', str('.EXE'))) # generate two variables, one of them for O(n) searches (but ordered) # and another for O(1) searches. the previous guy was trying to use # memoization with a function that has no arguments, this provides # the exact same benefit pathext = res.split(os.pathsep) res = {ext.lower() for ext in pathext} # check if our caller already specified a valid extension as then we don't need to match it _, ext = os.path.splitext(exe) if ext.lower() in res: pathext = [''] is_executable = is_executable_common # The specified extension isn't valid, so we just assume it's part of the # filename and proceed to walk the pathext list else: is_executable = lambda path, membership=res: is_executable_common(path) and has_executable_ext(path, membership) else: # in posix, there's no such thing as file extensions..only zuul pathext = [''] # executable semantics are pretty simple on reasonable platforms... is_executable = is_executable_common ## search for the executable # check to see if the full path was specified as then we don't need # to actually walk the system_path for any reason if is_executable(exe): return exe # now to search through our system_path for path in system_path: p = join(path, exe) # iterate through all extensions to see which one is executable for ext in pathext: pext = p + ext rp = resolve(pext) if is_executable(rp): return p + ext continue continue ## if something was executable, we should've found it already... log.trace( '\'%s\' could not be found in the following search path: \'%s\'', exe, system_path ) return None
[ "def", "which", "(", "exe", "=", "None", ")", ":", "if", "not", "exe", ":", "log", ".", "error", "(", "'No executable was passed to be searched by salt.utils.path.which()'", ")", "return", "None", "## define some utilities (we use closures here because our predecessor used th...
Python clone of /usr/bin/which
[ "Python", "clone", "of", "/", "usr", "/", "bin", "/", "which" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/path.py#L192-L300
train
saltstack/salt
salt/utils/path.py
which_bin
def which_bin(exes): ''' Scan over some possible executables and return the first one that is found ''' if not isinstance(exes, Iterable): return None for exe in exes: path = which(exe) if not path: continue return path return None
python
def which_bin(exes): ''' Scan over some possible executables and return the first one that is found ''' if not isinstance(exes, Iterable): return None for exe in exes: path = which(exe) if not path: continue return path return None
[ "def", "which_bin", "(", "exes", ")", ":", "if", "not", "isinstance", "(", "exes", ",", "Iterable", ")", ":", "return", "None", "for", "exe", "in", "exes", ":", "path", "=", "which", "(", "exe", ")", "if", "not", "path", ":", "continue", "return", ...
Scan over some possible executables and return the first one that is found
[ "Scan", "over", "some", "possible", "executables", "and", "return", "the", "first", "one", "that", "is", "found" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/path.py#L303-L314
train
saltstack/salt
salt/utils/path.py
join
def join(*parts, **kwargs): ''' This functions tries to solve some issues when joining multiple absolute paths on both *nix and windows platforms. See tests/unit/utils/path_join_test.py for some examples on what's being talked about here. The "use_posixpath" kwarg can be be used to force joining using poxixpath, which is useful for Salt fileserver paths on Windows masters. ''' if six.PY3: new_parts = [] for part in parts: new_parts.append(salt.utils.stringutils.to_str(part)) parts = new_parts kwargs = salt.utils.args.clean_kwargs(**kwargs) use_posixpath = kwargs.pop('use_posixpath', False) if kwargs: salt.utils.args.invalid_kwargs(kwargs) pathlib = posixpath if use_posixpath else os.path # Normalize path converting any os.sep as needed parts = [pathlib.normpath(p) for p in parts] try: root = parts.pop(0) except IndexError: # No args passed to func return '' root = salt.utils.stringutils.to_unicode(root) if not parts: ret = root else: stripped = [p.lstrip(os.sep) for p in parts] ret = pathlib.join(root, *salt.utils.data.decode(stripped)) return pathlib.normpath(ret)
python
def join(*parts, **kwargs): ''' This functions tries to solve some issues when joining multiple absolute paths on both *nix and windows platforms. See tests/unit/utils/path_join_test.py for some examples on what's being talked about here. The "use_posixpath" kwarg can be be used to force joining using poxixpath, which is useful for Salt fileserver paths on Windows masters. ''' if six.PY3: new_parts = [] for part in parts: new_parts.append(salt.utils.stringutils.to_str(part)) parts = new_parts kwargs = salt.utils.args.clean_kwargs(**kwargs) use_posixpath = kwargs.pop('use_posixpath', False) if kwargs: salt.utils.args.invalid_kwargs(kwargs) pathlib = posixpath if use_posixpath else os.path # Normalize path converting any os.sep as needed parts = [pathlib.normpath(p) for p in parts] try: root = parts.pop(0) except IndexError: # No args passed to func return '' root = salt.utils.stringutils.to_unicode(root) if not parts: ret = root else: stripped = [p.lstrip(os.sep) for p in parts] ret = pathlib.join(root, *salt.utils.data.decode(stripped)) return pathlib.normpath(ret)
[ "def", "join", "(", "*", "parts", ",", "*", "*", "kwargs", ")", ":", "if", "six", ".", "PY3", ":", "new_parts", "=", "[", "]", "for", "part", "in", "parts", ":", "new_parts", ".", "append", "(", "salt", ".", "utils", ".", "stringutils", ".", "to_...
This functions tries to solve some issues when joining multiple absolute paths on both *nix and windows platforms. See tests/unit/utils/path_join_test.py for some examples on what's being talked about here. The "use_posixpath" kwarg can be be used to force joining using poxixpath, which is useful for Salt fileserver paths on Windows masters.
[ "This", "functions", "tries", "to", "solve", "some", "issues", "when", "joining", "multiple", "absolute", "paths", "on", "both", "*", "nix", "and", "windows", "platforms", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/path.py#L318-L357
train
saltstack/salt
salt/utils/path.py
sanitize_win_path
def sanitize_win_path(winpath): ''' Remove illegal path characters for windows ''' intab = '<>:|?*' if isinstance(winpath, six.text_type): winpath = winpath.translate(dict((ord(c), '_') for c in intab)) elif isinstance(winpath, six.string_types): outtab = '_' * len(intab) trantab = ''.maketrans(intab, outtab) if six.PY3 else string.maketrans(intab, outtab) # pylint: disable=no-member winpath = winpath.translate(trantab) return winpath
python
def sanitize_win_path(winpath): ''' Remove illegal path characters for windows ''' intab = '<>:|?*' if isinstance(winpath, six.text_type): winpath = winpath.translate(dict((ord(c), '_') for c in intab)) elif isinstance(winpath, six.string_types): outtab = '_' * len(intab) trantab = ''.maketrans(intab, outtab) if six.PY3 else string.maketrans(intab, outtab) # pylint: disable=no-member winpath = winpath.translate(trantab) return winpath
[ "def", "sanitize_win_path", "(", "winpath", ")", ":", "intab", "=", "'<>:|?*'", "if", "isinstance", "(", "winpath", ",", "six", ".", "text_type", ")", ":", "winpath", "=", "winpath", ".", "translate", "(", "dict", "(", "(", "ord", "(", "c", ")", ",", ...
Remove illegal path characters for windows
[ "Remove", "illegal", "path", "characters", "for", "windows" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/path.py#L375-L386
train
saltstack/salt
salt/utils/path.py
safe_path
def safe_path(path, allow_path=None): r''' .. versionadded:: 2017.7.3 Checks that the path is safe for modification by Salt. For example, you wouldn't want to have salt delete the contents of ``C:\Windows``. The following directories are considered unsafe: - C:\, D:\, E:\, etc. - \ - C:\Windows Args: path (str): The path to check allow_paths (str, list): A directory or list of directories inside of path that may be safe. For example: ``C:\Windows\TEMP`` Returns: bool: True if safe, otherwise False ''' # Create regex definitions for directories that may be unsafe to modify system_root = os.environ.get('SystemRoot', 'C:\\Windows') deny_paths = ( r'[a-z]\:\\$', # C:\, D:\, etc r'\\$', # \ re.escape(system_root) # C:\Windows ) # Make allow_path a list if allow_path and not isinstance(allow_path, list): allow_path = [allow_path] # Create regex definition for directories we may want to make exceptions for allow_paths = list() if allow_path: for item in allow_path: allow_paths.append(re.escape(item)) # Check the path to make sure it's not one of the bad paths good_path = True for d_path in deny_paths: if re.match(d_path, path, flags=re.IGNORECASE) is not None: # Found deny path good_path = False # If local_dest is one of the bad paths, check for exceptions if not good_path: for a_path in allow_paths: if re.match(a_path, path, flags=re.IGNORECASE) is not None: # Found exception good_path = True return good_path
python
def safe_path(path, allow_path=None): r''' .. versionadded:: 2017.7.3 Checks that the path is safe for modification by Salt. For example, you wouldn't want to have salt delete the contents of ``C:\Windows``. The following directories are considered unsafe: - C:\, D:\, E:\, etc. - \ - C:\Windows Args: path (str): The path to check allow_paths (str, list): A directory or list of directories inside of path that may be safe. For example: ``C:\Windows\TEMP`` Returns: bool: True if safe, otherwise False ''' # Create regex definitions for directories that may be unsafe to modify system_root = os.environ.get('SystemRoot', 'C:\\Windows') deny_paths = ( r'[a-z]\:\\$', # C:\, D:\, etc r'\\$', # \ re.escape(system_root) # C:\Windows ) # Make allow_path a list if allow_path and not isinstance(allow_path, list): allow_path = [allow_path] # Create regex definition for directories we may want to make exceptions for allow_paths = list() if allow_path: for item in allow_path: allow_paths.append(re.escape(item)) # Check the path to make sure it's not one of the bad paths good_path = True for d_path in deny_paths: if re.match(d_path, path, flags=re.IGNORECASE) is not None: # Found deny path good_path = False # If local_dest is one of the bad paths, check for exceptions if not good_path: for a_path in allow_paths: if re.match(a_path, path, flags=re.IGNORECASE) is not None: # Found exception good_path = True return good_path
[ "def", "safe_path", "(", "path", ",", "allow_path", "=", "None", ")", ":", "# Create regex definitions for directories that may be unsafe to modify", "system_root", "=", "os", ".", "environ", ".", "get", "(", "'SystemRoot'", ",", "'C:\\\\Windows'", ")", "deny_paths", ...
r''' .. versionadded:: 2017.7.3 Checks that the path is safe for modification by Salt. For example, you wouldn't want to have salt delete the contents of ``C:\Windows``. The following directories are considered unsafe: - C:\, D:\, E:\, etc. - \ - C:\Windows Args: path (str): The path to check allow_paths (str, list): A directory or list of directories inside of path that may be safe. For example: ``C:\Windows\TEMP`` Returns: bool: True if safe, otherwise False
[ "r", "..", "versionadded", "::", "2017", ".", "7", ".", "3" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/path.py#L389-L443
train
saltstack/salt
salt/utils/path.py
os_walk
def os_walk(top, *args, **kwargs): ''' This is a helper than ensures that all paths returned from os.walk are unicode. ''' if six.PY2 and salt.utils.platform.is_windows(): top_query = top else: top_query = salt.utils.stringutils.to_str(top) for item in os.walk(top_query, *args, **kwargs): yield salt.utils.data.decode(item, preserve_tuples=True)
python
def os_walk(top, *args, **kwargs): ''' This is a helper than ensures that all paths returned from os.walk are unicode. ''' if six.PY2 and salt.utils.platform.is_windows(): top_query = top else: top_query = salt.utils.stringutils.to_str(top) for item in os.walk(top_query, *args, **kwargs): yield salt.utils.data.decode(item, preserve_tuples=True)
[ "def", "os_walk", "(", "top", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "six", ".", "PY2", "and", "salt", ".", "utils", ".", "platform", ".", "is_windows", "(", ")", ":", "top_query", "=", "top", "else", ":", "top_query", "=", "s...
This is a helper than ensures that all paths returned from os.walk are unicode.
[ "This", "is", "a", "helper", "than", "ensures", "that", "all", "paths", "returned", "from", "os", ".", "walk", "are", "unicode", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/path.py#L446-L456
train
saltstack/salt
salt/modules/ebuildpkg.py
_process_emerge_err
def _process_emerge_err(stdout, stderr): ''' Used to parse emerge output to provide meaningful output when emerge fails ''' ret = {} rexp = re.compile(r'^[<>=][^ ]+/[^ ]+ [^\n]+', re.M) slot_conflicts = re.compile(r'^[^ \n]+/[^ ]+:[^ ]', re.M).findall(stderr) if slot_conflicts: ret['slot conflicts'] = slot_conflicts blocked = re.compile(r'(?m)^\[blocks .+\] ' r'([^ ]+/[^ ]+-[0-9]+[^ ]+)' r'.*$').findall(stdout) unsatisfied = re.compile( r'Error: The above package list contains').findall(stderr) # If there were blocks and emerge could not resolve it. if blocked and unsatisfied: ret['blocked'] = blocked sections = re.split('\n\n', stderr) for section in sections: if 'The following keyword changes' in section: ret['keywords'] = rexp.findall(section) elif 'The following license changes' in section: ret['license'] = rexp.findall(section) elif 'The following USE changes' in section: ret['use'] = rexp.findall(section) elif 'The following mask changes' in section: ret['mask'] = rexp.findall(section) return ret
python
def _process_emerge_err(stdout, stderr): ''' Used to parse emerge output to provide meaningful output when emerge fails ''' ret = {} rexp = re.compile(r'^[<>=][^ ]+/[^ ]+ [^\n]+', re.M) slot_conflicts = re.compile(r'^[^ \n]+/[^ ]+:[^ ]', re.M).findall(stderr) if slot_conflicts: ret['slot conflicts'] = slot_conflicts blocked = re.compile(r'(?m)^\[blocks .+\] ' r'([^ ]+/[^ ]+-[0-9]+[^ ]+)' r'.*$').findall(stdout) unsatisfied = re.compile( r'Error: The above package list contains').findall(stderr) # If there were blocks and emerge could not resolve it. if blocked and unsatisfied: ret['blocked'] = blocked sections = re.split('\n\n', stderr) for section in sections: if 'The following keyword changes' in section: ret['keywords'] = rexp.findall(section) elif 'The following license changes' in section: ret['license'] = rexp.findall(section) elif 'The following USE changes' in section: ret['use'] = rexp.findall(section) elif 'The following mask changes' in section: ret['mask'] = rexp.findall(section) return ret
[ "def", "_process_emerge_err", "(", "stdout", ",", "stderr", ")", ":", "ret", "=", "{", "}", "rexp", "=", "re", ".", "compile", "(", "r'^[<>=][^ ]+/[^ ]+ [^\\n]+'", ",", "re", ".", "M", ")", "slot_conflicts", "=", "re", ".", "compile", "(", "r'^[^ \\n]+/[^ ...
Used to parse emerge output to provide meaningful output when emerge fails
[ "Used", "to", "parse", "emerge", "output", "to", "provide", "meaningful", "output", "when", "emerge", "fails" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ebuildpkg.py#L138-L170
train
saltstack/salt
salt/modules/ebuildpkg.py
check_db
def check_db(*names, **kwargs): ''' .. versionadded:: 0.17.0 Returns a dict containing the following information for each specified package: 1. A key ``found``, which will be a boolean value denoting if a match was found in the package database. 2. If ``found`` is ``False``, then a second key called ``suggestions`` will be present, which will contain a list of possible matches. This list will be empty if the package name was specified in ``category/pkgname`` format, since the suggestions are only intended to disambiguate ambiguous package names (ones submitted without a category). CLI Examples: .. code-block:: bash salt '*' pkg.check_db <package1> <package2> <package3> ''' ### NOTE: kwargs is not used here but needs to be present due to it being ### required in the check_db function in other package providers. ret = {} for name in names: if name in ret: log.warning( 'pkg.check_db: Duplicate package name \'%s\' submitted', name ) continue if '/' not in name: ret.setdefault(name, {})['found'] = False ret[name]['suggestions'] = porttree_matches(name) else: ret.setdefault(name, {})['found'] = name in _allnodes() if ret[name]['found'] is False: ret[name]['suggestions'] = [] return ret
python
def check_db(*names, **kwargs): ''' .. versionadded:: 0.17.0 Returns a dict containing the following information for each specified package: 1. A key ``found``, which will be a boolean value denoting if a match was found in the package database. 2. If ``found`` is ``False``, then a second key called ``suggestions`` will be present, which will contain a list of possible matches. This list will be empty if the package name was specified in ``category/pkgname`` format, since the suggestions are only intended to disambiguate ambiguous package names (ones submitted without a category). CLI Examples: .. code-block:: bash salt '*' pkg.check_db <package1> <package2> <package3> ''' ### NOTE: kwargs is not used here but needs to be present due to it being ### required in the check_db function in other package providers. ret = {} for name in names: if name in ret: log.warning( 'pkg.check_db: Duplicate package name \'%s\' submitted', name ) continue if '/' not in name: ret.setdefault(name, {})['found'] = False ret[name]['suggestions'] = porttree_matches(name) else: ret.setdefault(name, {})['found'] = name in _allnodes() if ret[name]['found'] is False: ret[name]['suggestions'] = [] return ret
[ "def", "check_db", "(", "*", "names", ",", "*", "*", "kwargs", ")", ":", "### NOTE: kwargs is not used here but needs to be present due to it being", "### required in the check_db function in other package providers.", "ret", "=", "{", "}", "for", "name", "in", "names", ":"...
.. versionadded:: 0.17.0 Returns a dict containing the following information for each specified package: 1. A key ``found``, which will be a boolean value denoting if a match was found in the package database. 2. If ``found`` is ``False``, then a second key called ``suggestions`` will be present, which will contain a list of possible matches. This list will be empty if the package name was specified in ``category/pkgname`` format, since the suggestions are only intended to disambiguate ambiguous package names (ones submitted without a category). CLI Examples: .. code-block:: bash salt '*' pkg.check_db <package1> <package2> <package3>
[ "..", "versionadded", "::", "0", ".", "17", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ebuildpkg.py#L173-L211
train
saltstack/salt
salt/modules/ebuildpkg.py
_get_upgradable
def _get_upgradable(backtrack=3): ''' Utility function to get upgradable packages Sample return data: { 'pkgname': '1.2.3-45', ... } ''' cmd = ['emerge', '--ask', 'n', '--backtrack', '{0}'.format(backtrack), '--pretend', '--update', '--newuse', '--deep', '@world'] call = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if call['retcode'] != 0: msg = 'Failed to get upgrades' for key in ('stderr', 'stdout'): if call[key]: msg += ': ' + call[key] break raise CommandExecutionError(msg) else: out = call['stdout'] rexp = re.compile(r'(?m)^\[.+\] ' r'([^ ]+/[^ ]+)' # Package string '-' r'([0-9]+[^ ]+)' # Version r'.*$') keys = ['name', 'version'] _get = lambda l, k: l[keys.index(k)] upgrades = rexp.findall(out) ret = {} for line in upgrades: name = _get(line, 'name') version_num = _get(line, 'version') ret[name] = version_num return ret
python
def _get_upgradable(backtrack=3): ''' Utility function to get upgradable packages Sample return data: { 'pkgname': '1.2.3-45', ... } ''' cmd = ['emerge', '--ask', 'n', '--backtrack', '{0}'.format(backtrack), '--pretend', '--update', '--newuse', '--deep', '@world'] call = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if call['retcode'] != 0: msg = 'Failed to get upgrades' for key in ('stderr', 'stdout'): if call[key]: msg += ': ' + call[key] break raise CommandExecutionError(msg) else: out = call['stdout'] rexp = re.compile(r'(?m)^\[.+\] ' r'([^ ]+/[^ ]+)' # Package string '-' r'([0-9]+[^ ]+)' # Version r'.*$') keys = ['name', 'version'] _get = lambda l, k: l[keys.index(k)] upgrades = rexp.findall(out) ret = {} for line in upgrades: name = _get(line, 'name') version_num = _get(line, 'version') ret[name] = version_num return ret
[ "def", "_get_upgradable", "(", "backtrack", "=", "3", ")", ":", "cmd", "=", "[", "'emerge'", ",", "'--ask'", ",", "'n'", ",", "'--backtrack'", ",", "'{0}'", ".", "format", "(", "backtrack", ")", ",", "'--pretend'", ",", "'--update'", ",", "'--newuse'", "...
Utility function to get upgradable packages Sample return data: { 'pkgname': '1.2.3-45', ... }
[ "Utility", "function", "to", "get", "upgradable", "packages" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ebuildpkg.py#L288-L335
train
saltstack/salt
salt/modules/ebuildpkg.py
list_upgrades
def list_upgrades(refresh=True, backtrack=3, **kwargs): # pylint: disable=W0613 ''' List all available package upgrades. refresh Whether or not to sync the portage tree before checking for upgrades. backtrack Specifies an integer number of times to backtrack if dependency calculation fails due to a conflict or an unsatisfied dependency (default: ´3´). .. versionadded: 2015.8.0 CLI Example: .. code-block:: bash salt '*' pkg.list_upgrades ''' if salt.utils.data.is_true(refresh): refresh_db() return _get_upgradable(backtrack)
python
def list_upgrades(refresh=True, backtrack=3, **kwargs): # pylint: disable=W0613 ''' List all available package upgrades. refresh Whether or not to sync the portage tree before checking for upgrades. backtrack Specifies an integer number of times to backtrack if dependency calculation fails due to a conflict or an unsatisfied dependency (default: ´3´). .. versionadded: 2015.8.0 CLI Example: .. code-block:: bash salt '*' pkg.list_upgrades ''' if salt.utils.data.is_true(refresh): refresh_db() return _get_upgradable(backtrack)
[ "def", "list_upgrades", "(", "refresh", "=", "True", ",", "backtrack", "=", "3", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=W0613", "if", "salt", ".", "utils", ".", "data", ".", "is_true", "(", "refresh", ")", ":", "refresh_db", "(", ")", "r...
List all available package upgrades. refresh Whether or not to sync the portage tree before checking for upgrades. backtrack Specifies an integer number of times to backtrack if dependency calculation fails due to a conflict or an unsatisfied dependency (default: ´3´). .. versionadded: 2015.8.0 CLI Example: .. code-block:: bash salt '*' pkg.list_upgrades
[ "List", "all", "available", "package", "upgrades", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ebuildpkg.py#L338-L360
train
saltstack/salt
salt/modules/ebuildpkg.py
porttree_matches
def porttree_matches(name): ''' Returns a list containing the matches for a given package name from the portage tree. Note that the specific version of the package will not be provided for packages that have several versions in the portage tree, but rather the name of the package (i.e. "dev-python/paramiko"). ''' matches = [] for category in _porttree().dbapi.categories: if _porttree().dbapi.cp_list(category + "/" + name): matches.append(category + "/" + name) return matches
python
def porttree_matches(name): ''' Returns a list containing the matches for a given package name from the portage tree. Note that the specific version of the package will not be provided for packages that have several versions in the portage tree, but rather the name of the package (i.e. "dev-python/paramiko"). ''' matches = [] for category in _porttree().dbapi.categories: if _porttree().dbapi.cp_list(category + "/" + name): matches.append(category + "/" + name) return matches
[ "def", "porttree_matches", "(", "name", ")", ":", "matches", "=", "[", "]", "for", "category", "in", "_porttree", "(", ")", ".", "dbapi", ".", "categories", ":", "if", "_porttree", "(", ")", ".", "dbapi", ".", "cp_list", "(", "category", "+", "\"/\"", ...
Returns a list containing the matches for a given package name from the portage tree. Note that the specific version of the package will not be provided for packages that have several versions in the portage tree, but rather the name of the package (i.e. "dev-python/paramiko").
[ "Returns", "a", "list", "containing", "the", "matches", "for", "a", "given", "package", "name", "from", "the", "portage", "tree", ".", "Note", "that", "the", "specific", "version", "of", "the", "package", "will", "not", "be", "provided", "for", "packages", ...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ebuildpkg.py#L392-L403
train
saltstack/salt
salt/modules/ebuildpkg.py
list_pkgs
def list_pkgs(versions_as_list=False, **kwargs): ''' List the packages currently installed in a dict:: {'<package_name>': '<version>'} CLI Example: .. code-block:: bash salt '*' pkg.list_pkgs ''' versions_as_list = salt.utils.data.is_true(versions_as_list) # not yet implemented or not applicable if any([salt.utils.data.is_true(kwargs.get(x)) for x in ('removed', 'purge_desired')]): return {} if 'pkg.list_pkgs' in __context__: if versions_as_list: return __context__['pkg.list_pkgs'] else: ret = copy.deepcopy(__context__['pkg.list_pkgs']) __salt__['pkg_resource.stringify'](ret) return ret ret = {} pkgs = _vartree().dbapi.cpv_all() for cpv in pkgs: __salt__['pkg_resource.add_pkg'](ret, _cpv_to_cp(cpv), _cpv_to_version(cpv)) __salt__['pkg_resource.sort_pkglist'](ret) __context__['pkg.list_pkgs'] = copy.deepcopy(ret) if not versions_as_list: __salt__['pkg_resource.stringify'](ret) return ret
python
def list_pkgs(versions_as_list=False, **kwargs): ''' List the packages currently installed in a dict:: {'<package_name>': '<version>'} CLI Example: .. code-block:: bash salt '*' pkg.list_pkgs ''' versions_as_list = salt.utils.data.is_true(versions_as_list) # not yet implemented or not applicable if any([salt.utils.data.is_true(kwargs.get(x)) for x in ('removed', 'purge_desired')]): return {} if 'pkg.list_pkgs' in __context__: if versions_as_list: return __context__['pkg.list_pkgs'] else: ret = copy.deepcopy(__context__['pkg.list_pkgs']) __salt__['pkg_resource.stringify'](ret) return ret ret = {} pkgs = _vartree().dbapi.cpv_all() for cpv in pkgs: __salt__['pkg_resource.add_pkg'](ret, _cpv_to_cp(cpv), _cpv_to_version(cpv)) __salt__['pkg_resource.sort_pkglist'](ret) __context__['pkg.list_pkgs'] = copy.deepcopy(ret) if not versions_as_list: __salt__['pkg_resource.stringify'](ret) return ret
[ "def", "list_pkgs", "(", "versions_as_list", "=", "False", ",", "*", "*", "kwargs", ")", ":", "versions_as_list", "=", "salt", ".", "utils", ".", "data", ".", "is_true", "(", "versions_as_list", ")", "# not yet implemented or not applicable", "if", "any", "(", ...
List the packages currently installed in a dict:: {'<package_name>': '<version>'} CLI Example: .. code-block:: bash salt '*' pkg.list_pkgs
[ "List", "the", "packages", "currently", "installed", "in", "a", "dict", "::" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ebuildpkg.py#L406-L442
train
saltstack/salt
salt/modules/ebuildpkg.py
refresh_db
def refresh_db(**kwargs): ''' Update the portage tree using the first available method from the following list: - emaint sync - eix-sync - emerge-webrsync - emerge --sync To prevent the portage tree from being synced within one day of the previous sync, add the following pillar data for this minion: .. code-block:: yaml portage: sync_wait_one_day: True CLI Example: .. code-block:: bash salt '*' pkg.refresh_db ''' has_emaint = os.path.isdir('/etc/portage/repos.conf') has_eix = True if 'eix.sync' in __salt__ else False has_webrsync = True if __salt__['makeconf.features_contains']('webrsync-gpg') else False # Remove rtag file to keep multiple refreshes from happening in pkg states salt.utils.pkg.clear_rtag(__opts__) # Option to prevent syncing package tree if done in the last 24 hours if __salt__['pillar.get']('portage:sync_wait_one_day', False): main_repo_root = __salt__['cmd.run']('portageq get_repo_path / gentoo') day = datetime.timedelta(days=1) now = datetime.datetime.now() timestamp = datetime.datetime.fromtimestamp(os.path.getmtime(main_repo_root)) if now - timestamp < day: log.info('Did not sync package tree since last sync was done at' ' %s, less than 1 day ago', timestamp) return False if has_emaint: return __salt__['cmd.retcode']('emaint sync -a') == 0 elif has_eix: return __salt__['eix.sync']() elif has_webrsync: # GPG sign verify is supported only for 'webrsync' cmd = 'emerge-webrsync -q' # Prefer 'delta-webrsync' to 'webrsync' if salt.utils.path.which('emerge-delta-webrsync'): cmd = 'emerge-delta-webrsync -q' return __salt__['cmd.retcode'](cmd) == 0 else: # Default to deprecated `emerge --sync` form return __salt__['cmd.retcode']('emerge --ask n --quiet --sync') == 0
python
def refresh_db(**kwargs): ''' Update the portage tree using the first available method from the following list: - emaint sync - eix-sync - emerge-webrsync - emerge --sync To prevent the portage tree from being synced within one day of the previous sync, add the following pillar data for this minion: .. code-block:: yaml portage: sync_wait_one_day: True CLI Example: .. code-block:: bash salt '*' pkg.refresh_db ''' has_emaint = os.path.isdir('/etc/portage/repos.conf') has_eix = True if 'eix.sync' in __salt__ else False has_webrsync = True if __salt__['makeconf.features_contains']('webrsync-gpg') else False # Remove rtag file to keep multiple refreshes from happening in pkg states salt.utils.pkg.clear_rtag(__opts__) # Option to prevent syncing package tree if done in the last 24 hours if __salt__['pillar.get']('portage:sync_wait_one_day', False): main_repo_root = __salt__['cmd.run']('portageq get_repo_path / gentoo') day = datetime.timedelta(days=1) now = datetime.datetime.now() timestamp = datetime.datetime.fromtimestamp(os.path.getmtime(main_repo_root)) if now - timestamp < day: log.info('Did not sync package tree since last sync was done at' ' %s, less than 1 day ago', timestamp) return False if has_emaint: return __salt__['cmd.retcode']('emaint sync -a') == 0 elif has_eix: return __salt__['eix.sync']() elif has_webrsync: # GPG sign verify is supported only for 'webrsync' cmd = 'emerge-webrsync -q' # Prefer 'delta-webrsync' to 'webrsync' if salt.utils.path.which('emerge-delta-webrsync'): cmd = 'emerge-delta-webrsync -q' return __salt__['cmd.retcode'](cmd) == 0 else: # Default to deprecated `emerge --sync` form return __salt__['cmd.retcode']('emerge --ask n --quiet --sync') == 0
[ "def", "refresh_db", "(", "*", "*", "kwargs", ")", ":", "has_emaint", "=", "os", ".", "path", ".", "isdir", "(", "'/etc/portage/repos.conf'", ")", "has_eix", "=", "True", "if", "'eix.sync'", "in", "__salt__", "else", "False", "has_webrsync", "=", "True", "...
Update the portage tree using the first available method from the following list: - emaint sync - eix-sync - emerge-webrsync - emerge --sync To prevent the portage tree from being synced within one day of the previous sync, add the following pillar data for this minion: .. code-block:: yaml portage: sync_wait_one_day: True CLI Example: .. code-block:: bash salt '*' pkg.refresh_db
[ "Update", "the", "portage", "tree", "using", "the", "first", "available", "method", "from", "the", "following", "list", ":" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ebuildpkg.py#L445-L499
train
saltstack/salt
salt/modules/ebuildpkg.py
install
def install(name=None, refresh=False, pkgs=None, sources=None, slot=None, fromrepo=None, uses=None, binhost=None, **kwargs): ''' .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands which modify installed packages from the ``salt-minion`` daemon's control group. This is done to keep systemd from killing any emerge commands spawned by Salt when the ``salt-minion`` service is restarted. (see ``KillMode`` in the `systemd.kill(5)`_ manpage for more information). If desired, usage of `systemd-run(1)`_ can be suppressed by setting a :mod:`config option <salt.modules.config.get>` called ``systemd.scope``, with a value of ``False`` (no quotes). .. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html .. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html Install the passed package(s), add refresh=True to sync the portage tree before package is installed. name The name of the package to be installed. Note that this parameter is ignored if either "pkgs" or "sources" is passed. Additionally, please note that this option can only be used to emerge a package from the portage tree. To install a tbz2 package manually, use the "sources" option described below. CLI Example: .. code-block:: bash salt '*' pkg.install <package name> refresh Whether or not to sync the portage tree before installing. version Install a specific version of the package, e.g. 1.0.9-r1. Ignored if "pkgs" or "sources" is passed. slot Similar to version, but specifies a valid slot to be installed. It will install the latest available version in the specified slot. Ignored if "pkgs" or "sources" or "version" is passed. CLI Example: .. code-block:: bash salt '*' pkg.install sys-devel/gcc slot='4.4' fromrepo Similar to slot, but specifies the repository from the package will be installed. It will install the latest available version in the specified repository. Ignored if "pkgs" or "sources" or "version" is passed. CLI Example: .. code-block:: bash salt '*' pkg.install salt fromrepo='gentoo' uses Similar to slot, but specifies a list of use flag. Ignored if "pkgs" or "sources" or "version" is passed. CLI Example: .. code-block:: bash salt '*' pkg.install sys-devel/gcc uses='["nptl","-nossp"]' Multiple Package Installation Options: pkgs A list of packages to install from the portage tree. Must be passed as a python list. CLI Example: .. code-block:: bash salt '*' pkg.install pkgs='["foo","bar","~category/package:slot::repository[use]"]' sources A list of tbz2 packages to install. Must be passed as a list of dicts, with the keys being package names, and the values being the source URI or local path to the package. CLI Example: .. code-block:: bash salt '*' pkg.install sources='[{"foo": "salt://foo.tbz2"},{"bar": "salt://bar.tbz2"}]' binhost has two options try and force. try - tells emerge to try and install the package from a configured binhost. force - forces emerge to install the package from a binhost otherwise it fails out. Returns a dict containing the new package names and versions:: {'<package>': {'old': '<old-version>', 'new': '<new-version>'}} ''' log.debug('Called modules.pkg.install: %s', { 'name': name, 'refresh': refresh, 'pkgs': pkgs, 'sources': sources, 'kwargs': kwargs, 'binhost': binhost, } ) if salt.utils.data.is_true(refresh): refresh_db() try: pkg_params, pkg_type = __salt__['pkg_resource.parse_targets']( name, pkgs, sources, **kwargs ) except MinionError as exc: raise CommandExecutionError(exc) # Handle version kwarg for a single package target if pkgs is None and sources is None: version_num = kwargs.get('version') if not version_num: version_num = '' if slot is not None: version_num += ':{0}'.format(slot) if fromrepo is not None: version_num += '::{0}'.format(fromrepo) if uses is not None: version_num += '[{0}]'.format(','.join(uses)) pkg_params = {name: version_num} if not pkg_params: return {} elif pkg_type == 'file': emerge_opts = ['tbz2file'] else: emerge_opts = [] if binhost == 'try': bin_opts = ['-g'] elif binhost == 'force': bin_opts = ['-G'] else: bin_opts = [] changes = {} if pkg_type == 'repository': targets = list() for param, version_num in six.iteritems(pkg_params): original_param = param param = _p_to_cp(param) if param is None: raise portage.dep.InvalidAtom(original_param) if version_num is None: targets.append(param) else: keyword = None match = re.match('^(~)?([<>])?(=)?([^<>=]*)$', version_num) if match: keyword, gt_lt, eq, verstr = match.groups() prefix = gt_lt or '' prefix += eq or '' # If no prefix characters were supplied and verstr contains a version, use '=' if verstr and verstr[0] != ':' and verstr[0] != '[': prefix = prefix or '=' target = '{0}{1}-{2}'.format(prefix, param, verstr) else: target = '{0}{1}'.format(param, verstr) else: target = '{0}'.format(param) if '[' in target: old = __salt__['portage_config.get_flags_from_package_conf']('use', target) __salt__['portage_config.append_use_flags'](target) new = __salt__['portage_config.get_flags_from_package_conf']('use', target) if old != new: changes[param + '-USE'] = {'old': old, 'new': new} target = target[:target.rfind('[')] if keyword is not None: __salt__['portage_config.append_to_package_conf']('accept_keywords', target, ['~ARCH']) changes[param + '-ACCEPT_KEYWORD'] = {'old': '', 'new': '~ARCH'} if not changes: inst_v = version(param) # Prevent latest_version from calling refresh_db. Either we # just called it or we were asked not to. if latest_version(param, refresh=False) == inst_v: all_uses = __salt__['portage_config.get_cleared_flags'](param) if _flags_changed(*all_uses): changes[param] = {'version': inst_v, 'old': {'use': all_uses[0]}, 'new': {'use': all_uses[1]}} targets.append(target) else: targets = pkg_params cmd = [] if salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): cmd.extend(['systemd-run', '--scope']) cmd.extend(['emerge', '--ask', 'n', '--quiet']) cmd.extend(bin_opts) cmd.extend(emerge_opts) cmd.extend(targets) old = list_pkgs() call = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if call['retcode'] != 0: needed_changes = _process_emerge_err(call['stdout'], call['stderr']) else: needed_changes = [] __context__.pop('pkg.list_pkgs', None) new = list_pkgs() changes.update(salt.utils.data.compare_dicts(old, new)) if needed_changes: raise CommandExecutionError( 'Error occurred installing package(s)', info={'needed changes': needed_changes, 'changes': changes} ) return changes
python
def install(name=None, refresh=False, pkgs=None, sources=None, slot=None, fromrepo=None, uses=None, binhost=None, **kwargs): ''' .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands which modify installed packages from the ``salt-minion`` daemon's control group. This is done to keep systemd from killing any emerge commands spawned by Salt when the ``salt-minion`` service is restarted. (see ``KillMode`` in the `systemd.kill(5)`_ manpage for more information). If desired, usage of `systemd-run(1)`_ can be suppressed by setting a :mod:`config option <salt.modules.config.get>` called ``systemd.scope``, with a value of ``False`` (no quotes). .. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html .. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html Install the passed package(s), add refresh=True to sync the portage tree before package is installed. name The name of the package to be installed. Note that this parameter is ignored if either "pkgs" or "sources" is passed. Additionally, please note that this option can only be used to emerge a package from the portage tree. To install a tbz2 package manually, use the "sources" option described below. CLI Example: .. code-block:: bash salt '*' pkg.install <package name> refresh Whether or not to sync the portage tree before installing. version Install a specific version of the package, e.g. 1.0.9-r1. Ignored if "pkgs" or "sources" is passed. slot Similar to version, but specifies a valid slot to be installed. It will install the latest available version in the specified slot. Ignored if "pkgs" or "sources" or "version" is passed. CLI Example: .. code-block:: bash salt '*' pkg.install sys-devel/gcc slot='4.4' fromrepo Similar to slot, but specifies the repository from the package will be installed. It will install the latest available version in the specified repository. Ignored if "pkgs" or "sources" or "version" is passed. CLI Example: .. code-block:: bash salt '*' pkg.install salt fromrepo='gentoo' uses Similar to slot, but specifies a list of use flag. Ignored if "pkgs" or "sources" or "version" is passed. CLI Example: .. code-block:: bash salt '*' pkg.install sys-devel/gcc uses='["nptl","-nossp"]' Multiple Package Installation Options: pkgs A list of packages to install from the portage tree. Must be passed as a python list. CLI Example: .. code-block:: bash salt '*' pkg.install pkgs='["foo","bar","~category/package:slot::repository[use]"]' sources A list of tbz2 packages to install. Must be passed as a list of dicts, with the keys being package names, and the values being the source URI or local path to the package. CLI Example: .. code-block:: bash salt '*' pkg.install sources='[{"foo": "salt://foo.tbz2"},{"bar": "salt://bar.tbz2"}]' binhost has two options try and force. try - tells emerge to try and install the package from a configured binhost. force - forces emerge to install the package from a binhost otherwise it fails out. Returns a dict containing the new package names and versions:: {'<package>': {'old': '<old-version>', 'new': '<new-version>'}} ''' log.debug('Called modules.pkg.install: %s', { 'name': name, 'refresh': refresh, 'pkgs': pkgs, 'sources': sources, 'kwargs': kwargs, 'binhost': binhost, } ) if salt.utils.data.is_true(refresh): refresh_db() try: pkg_params, pkg_type = __salt__['pkg_resource.parse_targets']( name, pkgs, sources, **kwargs ) except MinionError as exc: raise CommandExecutionError(exc) # Handle version kwarg for a single package target if pkgs is None and sources is None: version_num = kwargs.get('version') if not version_num: version_num = '' if slot is not None: version_num += ':{0}'.format(slot) if fromrepo is not None: version_num += '::{0}'.format(fromrepo) if uses is not None: version_num += '[{0}]'.format(','.join(uses)) pkg_params = {name: version_num} if not pkg_params: return {} elif pkg_type == 'file': emerge_opts = ['tbz2file'] else: emerge_opts = [] if binhost == 'try': bin_opts = ['-g'] elif binhost == 'force': bin_opts = ['-G'] else: bin_opts = [] changes = {} if pkg_type == 'repository': targets = list() for param, version_num in six.iteritems(pkg_params): original_param = param param = _p_to_cp(param) if param is None: raise portage.dep.InvalidAtom(original_param) if version_num is None: targets.append(param) else: keyword = None match = re.match('^(~)?([<>])?(=)?([^<>=]*)$', version_num) if match: keyword, gt_lt, eq, verstr = match.groups() prefix = gt_lt or '' prefix += eq or '' # If no prefix characters were supplied and verstr contains a version, use '=' if verstr and verstr[0] != ':' and verstr[0] != '[': prefix = prefix or '=' target = '{0}{1}-{2}'.format(prefix, param, verstr) else: target = '{0}{1}'.format(param, verstr) else: target = '{0}'.format(param) if '[' in target: old = __salt__['portage_config.get_flags_from_package_conf']('use', target) __salt__['portage_config.append_use_flags'](target) new = __salt__['portage_config.get_flags_from_package_conf']('use', target) if old != new: changes[param + '-USE'] = {'old': old, 'new': new} target = target[:target.rfind('[')] if keyword is not None: __salt__['portage_config.append_to_package_conf']('accept_keywords', target, ['~ARCH']) changes[param + '-ACCEPT_KEYWORD'] = {'old': '', 'new': '~ARCH'} if not changes: inst_v = version(param) # Prevent latest_version from calling refresh_db. Either we # just called it or we were asked not to. if latest_version(param, refresh=False) == inst_v: all_uses = __salt__['portage_config.get_cleared_flags'](param) if _flags_changed(*all_uses): changes[param] = {'version': inst_v, 'old': {'use': all_uses[0]}, 'new': {'use': all_uses[1]}} targets.append(target) else: targets = pkg_params cmd = [] if salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): cmd.extend(['systemd-run', '--scope']) cmd.extend(['emerge', '--ask', 'n', '--quiet']) cmd.extend(bin_opts) cmd.extend(emerge_opts) cmd.extend(targets) old = list_pkgs() call = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if call['retcode'] != 0: needed_changes = _process_emerge_err(call['stdout'], call['stderr']) else: needed_changes = [] __context__.pop('pkg.list_pkgs', None) new = list_pkgs() changes.update(salt.utils.data.compare_dicts(old, new)) if needed_changes: raise CommandExecutionError( 'Error occurred installing package(s)', info={'needed changes': needed_changes, 'changes': changes} ) return changes
[ "def", "install", "(", "name", "=", "None", ",", "refresh", "=", "False", ",", "pkgs", "=", "None", ",", "sources", "=", "None", ",", "slot", "=", "None", ",", "fromrepo", "=", "None", ",", "uses", "=", "None", ",", "binhost", "=", "None", ",", "...
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands which modify installed packages from the ``salt-minion`` daemon's control group. This is done to keep systemd from killing any emerge commands spawned by Salt when the ``salt-minion`` service is restarted. (see ``KillMode`` in the `systemd.kill(5)`_ manpage for more information). If desired, usage of `systemd-run(1)`_ can be suppressed by setting a :mod:`config option <salt.modules.config.get>` called ``systemd.scope``, with a value of ``False`` (no quotes). .. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html .. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html Install the passed package(s), add refresh=True to sync the portage tree before package is installed. name The name of the package to be installed. Note that this parameter is ignored if either "pkgs" or "sources" is passed. Additionally, please note that this option can only be used to emerge a package from the portage tree. To install a tbz2 package manually, use the "sources" option described below. CLI Example: .. code-block:: bash salt '*' pkg.install <package name> refresh Whether or not to sync the portage tree before installing. version Install a specific version of the package, e.g. 1.0.9-r1. Ignored if "pkgs" or "sources" is passed. slot Similar to version, but specifies a valid slot to be installed. It will install the latest available version in the specified slot. Ignored if "pkgs" or "sources" or "version" is passed. CLI Example: .. code-block:: bash salt '*' pkg.install sys-devel/gcc slot='4.4' fromrepo Similar to slot, but specifies the repository from the package will be installed. It will install the latest available version in the specified repository. Ignored if "pkgs" or "sources" or "version" is passed. CLI Example: .. code-block:: bash salt '*' pkg.install salt fromrepo='gentoo' uses Similar to slot, but specifies a list of use flag. Ignored if "pkgs" or "sources" or "version" is passed. CLI Example: .. code-block:: bash salt '*' pkg.install sys-devel/gcc uses='["nptl","-nossp"]' Multiple Package Installation Options: pkgs A list of packages to install from the portage tree. Must be passed as a python list. CLI Example: .. code-block:: bash salt '*' pkg.install pkgs='["foo","bar","~category/package:slot::repository[use]"]' sources A list of tbz2 packages to install. Must be passed as a list of dicts, with the keys being package names, and the values being the source URI or local path to the package. CLI Example: .. code-block:: bash salt '*' pkg.install sources='[{"foo": "salt://foo.tbz2"},{"bar": "salt://bar.tbz2"}]' binhost has two options try and force. try - tells emerge to try and install the package from a configured binhost. force - forces emerge to install the package from a binhost otherwise it fails out. Returns a dict containing the new package names and versions:: {'<package>': {'old': '<old-version>', 'new': '<new-version>'}}
[ "..", "versionchanged", "::", "2015", ".", "8", ".", "12", "2016", ".", "3", ".", "3", "2016", ".", "11", ".", "0", "On", "minions", "running", "systemd", ">", "=", "205", "systemd", "-", "run", "(", "1", ")", "_", "is", "now", "used", "to", "i...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ebuildpkg.py#L521-L767
train
saltstack/salt
salt/modules/ebuildpkg.py
update
def update(pkg, slot=None, fromrepo=None, refresh=False, binhost=None, **kwargs): ''' .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands which modify installed packages from the ``salt-minion`` daemon's control group. This is done to keep systemd from killing any emerge commands spawned by Salt when the ``salt-minion`` service is restarted. (see ``KillMode`` in the `systemd.kill(5)`_ manpage for more information). If desired, usage of `systemd-run(1)`_ can be suppressed by setting a :mod:`config option <salt.modules.config.get>` called ``systemd.scope``, with a value of ``False`` (no quotes). .. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html .. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html Updates the passed package (emerge --update package) slot Restrict the update to a particular slot. It will update to the latest version within the slot. fromrepo Restrict the update to a particular repository. It will update to the latest version within the repository. binhost has two options try and force. try - tells emerge to try and install the package from a configured binhost. force - forces emerge to install the package from a binhost otherwise it fails out. Return a dict containing the new package names and versions:: {'<package>': {'old': '<old-version>', 'new': '<new-version>'}} CLI Example: .. code-block:: bash salt '*' pkg.update <package name> ''' if salt.utils.data.is_true(refresh): refresh_db() full_atom = pkg if slot is not None: full_atom = '{0}:{1}'.format(full_atom, slot) if fromrepo is not None: full_atom = '{0}::{1}'.format(full_atom, fromrepo) if binhost == 'try': bin_opts = ['-g'] elif binhost == 'force': bin_opts = ['-G'] else: bin_opts = [] old = list_pkgs() cmd = [] if salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): cmd.extend(['systemd-run', '--scope']) cmd.extend(['emerge', '--ask', 'n', '--quiet', '--update', '--newuse', '--oneshot']) cmd.extend(bin_opts) cmd.append(full_atom) call = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if call['retcode'] != 0: needed_changes = _process_emerge_err(call['stdout'], call['stderr']) else: needed_changes = [] __context__.pop('pkg.list_pkgs', None) new = list_pkgs() ret = salt.utils.data.compare_dicts(old, new) if needed_changes: raise CommandExecutionError( 'Problem encountered updating package(s)', info={'needed_changes': needed_changes, 'changes': ret} ) return ret
python
def update(pkg, slot=None, fromrepo=None, refresh=False, binhost=None, **kwargs): ''' .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands which modify installed packages from the ``salt-minion`` daemon's control group. This is done to keep systemd from killing any emerge commands spawned by Salt when the ``salt-minion`` service is restarted. (see ``KillMode`` in the `systemd.kill(5)`_ manpage for more information). If desired, usage of `systemd-run(1)`_ can be suppressed by setting a :mod:`config option <salt.modules.config.get>` called ``systemd.scope``, with a value of ``False`` (no quotes). .. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html .. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html Updates the passed package (emerge --update package) slot Restrict the update to a particular slot. It will update to the latest version within the slot. fromrepo Restrict the update to a particular repository. It will update to the latest version within the repository. binhost has two options try and force. try - tells emerge to try and install the package from a configured binhost. force - forces emerge to install the package from a binhost otherwise it fails out. Return a dict containing the new package names and versions:: {'<package>': {'old': '<old-version>', 'new': '<new-version>'}} CLI Example: .. code-block:: bash salt '*' pkg.update <package name> ''' if salt.utils.data.is_true(refresh): refresh_db() full_atom = pkg if slot is not None: full_atom = '{0}:{1}'.format(full_atom, slot) if fromrepo is not None: full_atom = '{0}::{1}'.format(full_atom, fromrepo) if binhost == 'try': bin_opts = ['-g'] elif binhost == 'force': bin_opts = ['-G'] else: bin_opts = [] old = list_pkgs() cmd = [] if salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): cmd.extend(['systemd-run', '--scope']) cmd.extend(['emerge', '--ask', 'n', '--quiet', '--update', '--newuse', '--oneshot']) cmd.extend(bin_opts) cmd.append(full_atom) call = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if call['retcode'] != 0: needed_changes = _process_emerge_err(call['stdout'], call['stderr']) else: needed_changes = [] __context__.pop('pkg.list_pkgs', None) new = list_pkgs() ret = salt.utils.data.compare_dicts(old, new) if needed_changes: raise CommandExecutionError( 'Problem encountered updating package(s)', info={'needed_changes': needed_changes, 'changes': ret} ) return ret
[ "def", "update", "(", "pkg", ",", "slot", "=", "None", ",", "fromrepo", "=", "None", ",", "refresh", "=", "False", ",", "binhost", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "salt", ".", "utils", ".", "data", ".", "is_true", "(", "refr...
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands which modify installed packages from the ``salt-minion`` daemon's control group. This is done to keep systemd from killing any emerge commands spawned by Salt when the ``salt-minion`` service is restarted. (see ``KillMode`` in the `systemd.kill(5)`_ manpage for more information). If desired, usage of `systemd-run(1)`_ can be suppressed by setting a :mod:`config option <salt.modules.config.get>` called ``systemd.scope``, with a value of ``False`` (no quotes). .. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html .. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html Updates the passed package (emerge --update package) slot Restrict the update to a particular slot. It will update to the latest version within the slot. fromrepo Restrict the update to a particular repository. It will update to the latest version within the repository. binhost has two options try and force. try - tells emerge to try and install the package from a configured binhost. force - forces emerge to install the package from a binhost otherwise it fails out. Return a dict containing the new package names and versions:: {'<package>': {'old': '<old-version>', 'new': '<new-version>'}} CLI Example: .. code-block:: bash salt '*' pkg.update <package name>
[ "..", "versionchanged", "::", "2015", ".", "8", ".", "12", "2016", ".", "3", ".", "3", "2016", ".", "11", ".", "0", "On", "minions", "running", "systemd", ">", "=", "205", "systemd", "-", "run", "(", "1", ")", "_", "is", "now", "used", "to", "i...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ebuildpkg.py#L770-L860
train
saltstack/salt
salt/modules/ebuildpkg.py
remove
def remove(name=None, slot=None, fromrepo=None, pkgs=None, **kwargs): ''' .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands which modify installed packages from the ``salt-minion`` daemon's control group. This is done to keep systemd from killing any emerge commands spawned by Salt when the ``salt-minion`` service is restarted. (see ``KillMode`` in the `systemd.kill(5)`_ manpage for more information). If desired, usage of `systemd-run(1)`_ can be suppressed by setting a :mod:`config option <salt.modules.config.get>` called ``systemd.scope``, with a value of ``False`` (no quotes). .. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html .. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html Remove packages via emerge --unmerge. name The name of the package to be deleted. slot Restrict the remove to a specific slot. Ignored if ``name`` is None. fromrepo Restrict the remove to a specific slot. Ignored if ``name`` is None. Multiple Package Options: pkgs Uninstall multiple packages. ``slot`` and ``fromrepo`` arguments are ignored if this argument is present. Must be passed as a python list. .. versionadded:: 0.16.0 Returns a dict containing the changes. CLI Example: .. code-block:: bash salt '*' pkg.remove <package name> salt '*' pkg.remove <package name> slot=4.4 fromrepo=gentoo salt '*' pkg.remove <package1>,<package2>,<package3> salt '*' pkg.remove pkgs='["foo", "bar"]' ''' try: pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0] except MinionError as exc: raise CommandExecutionError(exc) old = list_pkgs() if name and not pkgs and (slot is not None or fromrepo is not None)and len(pkg_params) == 1: fullatom = name if slot is not None: targets = ['{0}:{1}'.format(fullatom, slot)] if fromrepo is not None: targets = ['{0}::{1}'.format(fullatom, fromrepo)] targets = [fullatom] else: targets = [x for x in pkg_params if x in old] if not targets: return {} cmd = [] if salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): cmd.extend(['systemd-run', '--scope']) cmd.extend(['emerge', '--ask', 'n', '--quiet', '--unmerge', '--quiet-unmerge-warn']) cmd.extend(targets) out = __salt__['cmd.run_all']( cmd, output_loglevel='trace', python_shell=False ) if out['retcode'] != 0 and out['stderr']: errors = [out['stderr']] else: errors = [] __context__.pop('pkg.list_pkgs', None) new = list_pkgs() ret = salt.utils.data.compare_dicts(old, new) if errors: raise CommandExecutionError( 'Problem encountered removing package(s)', info={'errors': errors, 'changes': ret} ) return ret
python
def remove(name=None, slot=None, fromrepo=None, pkgs=None, **kwargs): ''' .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands which modify installed packages from the ``salt-minion`` daemon's control group. This is done to keep systemd from killing any emerge commands spawned by Salt when the ``salt-minion`` service is restarted. (see ``KillMode`` in the `systemd.kill(5)`_ manpage for more information). If desired, usage of `systemd-run(1)`_ can be suppressed by setting a :mod:`config option <salt.modules.config.get>` called ``systemd.scope``, with a value of ``False`` (no quotes). .. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html .. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html Remove packages via emerge --unmerge. name The name of the package to be deleted. slot Restrict the remove to a specific slot. Ignored if ``name`` is None. fromrepo Restrict the remove to a specific slot. Ignored if ``name`` is None. Multiple Package Options: pkgs Uninstall multiple packages. ``slot`` and ``fromrepo`` arguments are ignored if this argument is present. Must be passed as a python list. .. versionadded:: 0.16.0 Returns a dict containing the changes. CLI Example: .. code-block:: bash salt '*' pkg.remove <package name> salt '*' pkg.remove <package name> slot=4.4 fromrepo=gentoo salt '*' pkg.remove <package1>,<package2>,<package3> salt '*' pkg.remove pkgs='["foo", "bar"]' ''' try: pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0] except MinionError as exc: raise CommandExecutionError(exc) old = list_pkgs() if name and not pkgs and (slot is not None or fromrepo is not None)and len(pkg_params) == 1: fullatom = name if slot is not None: targets = ['{0}:{1}'.format(fullatom, slot)] if fromrepo is not None: targets = ['{0}::{1}'.format(fullatom, fromrepo)] targets = [fullatom] else: targets = [x for x in pkg_params if x in old] if not targets: return {} cmd = [] if salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): cmd.extend(['systemd-run', '--scope']) cmd.extend(['emerge', '--ask', 'n', '--quiet', '--unmerge', '--quiet-unmerge-warn']) cmd.extend(targets) out = __salt__['cmd.run_all']( cmd, output_loglevel='trace', python_shell=False ) if out['retcode'] != 0 and out['stderr']: errors = [out['stderr']] else: errors = [] __context__.pop('pkg.list_pkgs', None) new = list_pkgs() ret = salt.utils.data.compare_dicts(old, new) if errors: raise CommandExecutionError( 'Problem encountered removing package(s)', info={'errors': errors, 'changes': ret} ) return ret
[ "def", "remove", "(", "name", "=", "None", ",", "slot", "=", "None", ",", "fromrepo", "=", "None", ",", "pkgs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "try", ":", "pkg_params", "=", "__salt__", "[", "'pkg_resource.parse_targets'", "]", "(", ...
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands which modify installed packages from the ``salt-minion`` daemon's control group. This is done to keep systemd from killing any emerge commands spawned by Salt when the ``salt-minion`` service is restarted. (see ``KillMode`` in the `systemd.kill(5)`_ manpage for more information). If desired, usage of `systemd-run(1)`_ can be suppressed by setting a :mod:`config option <salt.modules.config.get>` called ``systemd.scope``, with a value of ``False`` (no quotes). .. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html .. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html Remove packages via emerge --unmerge. name The name of the package to be deleted. slot Restrict the remove to a specific slot. Ignored if ``name`` is None. fromrepo Restrict the remove to a specific slot. Ignored if ``name`` is None. Multiple Package Options: pkgs Uninstall multiple packages. ``slot`` and ``fromrepo`` arguments are ignored if this argument is present. Must be passed as a python list. .. versionadded:: 0.16.0 Returns a dict containing the changes. CLI Example: .. code-block:: bash salt '*' pkg.remove <package name> salt '*' pkg.remove <package name> slot=4.4 fromrepo=gentoo salt '*' pkg.remove <package1>,<package2>,<package3> salt '*' pkg.remove pkgs='["foo", "bar"]'
[ "..", "versionchanged", "::", "2015", ".", "8", ".", "12", "2016", ".", "3", ".", "3", "2016", ".", "11", ".", "0", "On", "minions", "running", "systemd", ">", "=", "205", "systemd", "-", "run", "(", "1", ")", "_", "is", "now", "used", "to", "i...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ebuildpkg.py#L953-L1049
train
saltstack/salt
salt/modules/ebuildpkg.py
purge
def purge(name=None, slot=None, fromrepo=None, pkgs=None, **kwargs): ''' .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands which modify installed packages from the ``salt-minion`` daemon's control group. This is done to keep systemd from killing any emerge commands spawned by Salt when the ``salt-minion`` service is restarted. (see ``KillMode`` in the `systemd.kill(5)`_ manpage for more information). If desired, usage of `systemd-run(1)`_ can be suppressed by setting a :mod:`config option <salt.modules.config.get>` called ``systemd.scope``, with a value of ``False`` (no quotes). .. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html .. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html Portage does not have a purge, this function calls remove followed by depclean to emulate a purge process name The name of the package to be deleted. slot Restrict the remove to a specific slot. Ignored if name is None. fromrepo Restrict the remove to a specific slot. Ignored if ``name`` is None. Multiple Package Options: pkgs Uninstall multiple packages. ``slot`` and ``fromrepo`` arguments are ignored if this argument is present. Must be passed as a python list. .. versionadded:: 0.16.0 Returns a dict containing the changes. CLI Example: .. code-block:: bash salt '*' pkg.purge <package name> salt '*' pkg.purge <package name> slot=4.4 salt '*' pkg.purge <package1>,<package2>,<package3> salt '*' pkg.purge pkgs='["foo", "bar"]' ''' ret = remove(name=name, slot=slot, fromrepo=fromrepo, pkgs=pkgs) ret.update(depclean(name=name, slot=slot, fromrepo=fromrepo, pkgs=pkgs)) return ret
python
def purge(name=None, slot=None, fromrepo=None, pkgs=None, **kwargs): ''' .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands which modify installed packages from the ``salt-minion`` daemon's control group. This is done to keep systemd from killing any emerge commands spawned by Salt when the ``salt-minion`` service is restarted. (see ``KillMode`` in the `systemd.kill(5)`_ manpage for more information). If desired, usage of `systemd-run(1)`_ can be suppressed by setting a :mod:`config option <salt.modules.config.get>` called ``systemd.scope``, with a value of ``False`` (no quotes). .. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html .. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html Portage does not have a purge, this function calls remove followed by depclean to emulate a purge process name The name of the package to be deleted. slot Restrict the remove to a specific slot. Ignored if name is None. fromrepo Restrict the remove to a specific slot. Ignored if ``name`` is None. Multiple Package Options: pkgs Uninstall multiple packages. ``slot`` and ``fromrepo`` arguments are ignored if this argument is present. Must be passed as a python list. .. versionadded:: 0.16.0 Returns a dict containing the changes. CLI Example: .. code-block:: bash salt '*' pkg.purge <package name> salt '*' pkg.purge <package name> slot=4.4 salt '*' pkg.purge <package1>,<package2>,<package3> salt '*' pkg.purge pkgs='["foo", "bar"]' ''' ret = remove(name=name, slot=slot, fromrepo=fromrepo, pkgs=pkgs) ret.update(depclean(name=name, slot=slot, fromrepo=fromrepo, pkgs=pkgs)) return ret
[ "def", "purge", "(", "name", "=", "None", ",", "slot", "=", "None", ",", "fromrepo", "=", "None", ",", "pkgs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "remove", "(", "name", "=", "name", ",", "slot", "=", "slot", ",", "fromr...
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands which modify installed packages from the ``salt-minion`` daemon's control group. This is done to keep systemd from killing any emerge commands spawned by Salt when the ``salt-minion`` service is restarted. (see ``KillMode`` in the `systemd.kill(5)`_ manpage for more information). If desired, usage of `systemd-run(1)`_ can be suppressed by setting a :mod:`config option <salt.modules.config.get>` called ``systemd.scope``, with a value of ``False`` (no quotes). .. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html .. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html Portage does not have a purge, this function calls remove followed by depclean to emulate a purge process name The name of the package to be deleted. slot Restrict the remove to a specific slot. Ignored if name is None. fromrepo Restrict the remove to a specific slot. Ignored if ``name`` is None. Multiple Package Options: pkgs Uninstall multiple packages. ``slot`` and ``fromrepo`` arguments are ignored if this argument is present. Must be passed as a python list. .. versionadded:: 0.16.0 Returns a dict containing the changes. CLI Example: .. code-block:: bash salt '*' pkg.purge <package name> salt '*' pkg.purge <package name> slot=4.4 salt '*' pkg.purge <package1>,<package2>,<package3> salt '*' pkg.purge pkgs='["foo", "bar"]'
[ "..", "versionchanged", "::", "2015", ".", "8", ".", "12", "2016", ".", "3", ".", "3", "2016", ".", "11", ".", "0", "On", "minions", "running", "systemd", ">", "=", "205", "systemd", "-", "run", "(", "1", ")", "_", "is", "now", "used", "to", "i...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ebuildpkg.py#L1052-L1102
train
saltstack/salt
salt/modules/ebuildpkg.py
depclean
def depclean(name=None, slot=None, fromrepo=None, pkgs=None): ''' Portage has a function to remove unused dependencies. If a package is provided, it will only removed the package if no other package depends on it. name The name of the package to be cleaned. slot Restrict the remove to a specific slot. Ignored if ``name`` is None. fromrepo Restrict the remove to a specific slot. Ignored if ``name`` is None. pkgs Clean multiple packages. ``slot`` and ``fromrepo`` arguments are ignored if this argument is present. Must be passed as a python list. Return a list containing the removed packages: CLI Example: .. code-block:: bash salt '*' pkg.depclean <package name> ''' try: pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0] except MinionError as exc: raise CommandExecutionError(exc) old = list_pkgs() if name and not pkgs and (slot is not None or fromrepo is not None)and len(pkg_params) == 1: fullatom = name if slot is not None: targets = ['{0}:{1}'.format(fullatom, slot)] if fromrepo is not None: targets = ['{0}::{1}'.format(fullatom, fromrepo)] targets = [fullatom] else: targets = [x for x in pkg_params if x in old] cmd = ['emerge', '--ask', 'n', '--quiet', '--depclean'] + targets __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) __context__.pop('pkg.list_pkgs', None) new = list_pkgs() return salt.utils.data.compare_dicts(old, new)
python
def depclean(name=None, slot=None, fromrepo=None, pkgs=None): ''' Portage has a function to remove unused dependencies. If a package is provided, it will only removed the package if no other package depends on it. name The name of the package to be cleaned. slot Restrict the remove to a specific slot. Ignored if ``name`` is None. fromrepo Restrict the remove to a specific slot. Ignored if ``name`` is None. pkgs Clean multiple packages. ``slot`` and ``fromrepo`` arguments are ignored if this argument is present. Must be passed as a python list. Return a list containing the removed packages: CLI Example: .. code-block:: bash salt '*' pkg.depclean <package name> ''' try: pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0] except MinionError as exc: raise CommandExecutionError(exc) old = list_pkgs() if name and not pkgs and (slot is not None or fromrepo is not None)and len(pkg_params) == 1: fullatom = name if slot is not None: targets = ['{0}:{1}'.format(fullatom, slot)] if fromrepo is not None: targets = ['{0}::{1}'.format(fullatom, fromrepo)] targets = [fullatom] else: targets = [x for x in pkg_params if x in old] cmd = ['emerge', '--ask', 'n', '--quiet', '--depclean'] + targets __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) __context__.pop('pkg.list_pkgs', None) new = list_pkgs() return salt.utils.data.compare_dicts(old, new)
[ "def", "depclean", "(", "name", "=", "None", ",", "slot", "=", "None", ",", "fromrepo", "=", "None", ",", "pkgs", "=", "None", ")", ":", "try", ":", "pkg_params", "=", "__salt__", "[", "'pkg_resource.parse_targets'", "]", "(", "name", ",", "pkgs", ")",...
Portage has a function to remove unused dependencies. If a package is provided, it will only removed the package if no other package depends on it. name The name of the package to be cleaned. slot Restrict the remove to a specific slot. Ignored if ``name`` is None. fromrepo Restrict the remove to a specific slot. Ignored if ``name`` is None. pkgs Clean multiple packages. ``slot`` and ``fromrepo`` arguments are ignored if this argument is present. Must be passed as a python list. Return a list containing the removed packages: CLI Example: .. code-block:: bash salt '*' pkg.depclean <package name>
[ "Portage", "has", "a", "function", "to", "remove", "unused", "dependencies", ".", "If", "a", "package", "is", "provided", "it", "will", "only", "removed", "the", "package", "if", "no", "other", "package", "depends", "on", "it", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ebuildpkg.py#L1105-L1154
train
saltstack/salt
salt/modules/ebuildpkg.py
version_cmp
def version_cmp(pkg1, pkg2, **kwargs): ''' Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem making the comparison. CLI Example: .. code-block:: bash salt '*' pkg.version_cmp '0.2.4-0' '0.2.4.1-0' ''' # ignore_epoch is not supported here, but has to be included for API # compatibility. Rather than putting this argument into the function # definition (and thus have it show up in the docs), we just pop it out of # the kwargs dict and then raise an exception if any kwargs other than # ignore_epoch were passed. kwargs = salt.utils.args.clean_kwargs(**kwargs) kwargs.pop('ignore_epoch', None) if kwargs: salt.utils.args.invalid_kwargs(kwargs) regex = r'^~?([^:\[]+):?[^\[]*\[?.*$' ver1 = re.match(regex, pkg1) ver2 = re.match(regex, pkg2) if ver1 and ver2: return portage.versions.vercmp(ver1.group(1), ver2.group(1)) return None
python
def version_cmp(pkg1, pkg2, **kwargs): ''' Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem making the comparison. CLI Example: .. code-block:: bash salt '*' pkg.version_cmp '0.2.4-0' '0.2.4.1-0' ''' # ignore_epoch is not supported here, but has to be included for API # compatibility. Rather than putting this argument into the function # definition (and thus have it show up in the docs), we just pop it out of # the kwargs dict and then raise an exception if any kwargs other than # ignore_epoch were passed. kwargs = salt.utils.args.clean_kwargs(**kwargs) kwargs.pop('ignore_epoch', None) if kwargs: salt.utils.args.invalid_kwargs(kwargs) regex = r'^~?([^:\[]+):?[^\[]*\[?.*$' ver1 = re.match(regex, pkg1) ver2 = re.match(regex, pkg2) if ver1 and ver2: return portage.versions.vercmp(ver1.group(1), ver2.group(1)) return None
[ "def", "version_cmp", "(", "pkg1", ",", "pkg2", ",", "*", "*", "kwargs", ")", ":", "# ignore_epoch is not supported here, but has to be included for API", "# compatibility. Rather than putting this argument into the function", "# definition (and thus have it show up in the docs), we just...
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem making the comparison. CLI Example: .. code-block:: bash salt '*' pkg.version_cmp '0.2.4-0' '0.2.4.1-0'
[ "Do", "a", "cmp", "-", "style", "comparison", "on", "two", "packages", ".", "Return", "-", "1", "if", "pkg1", "<", "pkg2", "0", "if", "pkg1", "==", "pkg2", "and", "1", "if", "pkg1", ">", "pkg2", ".", "Return", "None", "if", "there", "was", "a", "...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ebuildpkg.py#L1157-L1185
train
saltstack/salt
salt/modules/ebuildpkg.py
check_extra_requirements
def check_extra_requirements(pkgname, pkgver): ''' Check if the installed package already has the given requirements. CLI Example: .. code-block:: bash salt '*' pkg.check_extra_requirements 'sys-devel/gcc' '~>4.1.2:4.1::gentoo[nls,fortran]' ''' keyword = None match = re.match('^(~)?([<>])?(=)?([^<>=]*)$', pkgver) if match: keyword, gt_lt, eq, verstr = match.groups() prefix = gt_lt or '' prefix += eq or '' # We need to delete quotes around use flag list elements verstr = verstr.replace("'", "") # If no prefix characters were supplied and verstr contains a version, use '=' if verstr[0] != ':' and verstr[0] != '[': prefix = prefix or '=' atom = '{0}{1}-{2}'.format(prefix, pkgname, verstr) else: atom = '{0}{1}'.format(pkgname, verstr) else: return True try: cpv = _porttree().dbapi.xmatch('bestmatch-visible', atom) except portage.exception.InvalidAtom as iae: log.error('Unable to find a matching package for %s: (%s)', atom, iae) return False if cpv == '': return False try: cur_repo, cur_use = _vartree().dbapi.aux_get(cpv, ['repository', 'USE']) except KeyError: return False des_repo = re.match(r'^.+::([^\[]+).*$', atom) if des_repo and des_repo.group(1) != cur_repo: return False des_uses = set(portage.dep.dep_getusedeps(atom)) cur_use = cur_use.split() if [x for x in des_uses.difference(cur_use) if x[0] != '-' or x[1:] in cur_use]: return False if keyword: if not __salt__['portage_config.has_flag']('accept_keywords', atom, '~ARCH'): return False return True
python
def check_extra_requirements(pkgname, pkgver): ''' Check if the installed package already has the given requirements. CLI Example: .. code-block:: bash salt '*' pkg.check_extra_requirements 'sys-devel/gcc' '~>4.1.2:4.1::gentoo[nls,fortran]' ''' keyword = None match = re.match('^(~)?([<>])?(=)?([^<>=]*)$', pkgver) if match: keyword, gt_lt, eq, verstr = match.groups() prefix = gt_lt or '' prefix += eq or '' # We need to delete quotes around use flag list elements verstr = verstr.replace("'", "") # If no prefix characters were supplied and verstr contains a version, use '=' if verstr[0] != ':' and verstr[0] != '[': prefix = prefix or '=' atom = '{0}{1}-{2}'.format(prefix, pkgname, verstr) else: atom = '{0}{1}'.format(pkgname, verstr) else: return True try: cpv = _porttree().dbapi.xmatch('bestmatch-visible', atom) except portage.exception.InvalidAtom as iae: log.error('Unable to find a matching package for %s: (%s)', atom, iae) return False if cpv == '': return False try: cur_repo, cur_use = _vartree().dbapi.aux_get(cpv, ['repository', 'USE']) except KeyError: return False des_repo = re.match(r'^.+::([^\[]+).*$', atom) if des_repo and des_repo.group(1) != cur_repo: return False des_uses = set(portage.dep.dep_getusedeps(atom)) cur_use = cur_use.split() if [x for x in des_uses.difference(cur_use) if x[0] != '-' or x[1:] in cur_use]: return False if keyword: if not __salt__['portage_config.has_flag']('accept_keywords', atom, '~ARCH'): return False return True
[ "def", "check_extra_requirements", "(", "pkgname", ",", "pkgver", ")", ":", "keyword", "=", "None", "match", "=", "re", ".", "match", "(", "'^(~)?([<>])?(=)?([^<>=]*)$'", ",", "pkgver", ")", "if", "match", ":", "keyword", ",", "gt_lt", ",", "eq", ",", "ver...
Check if the installed package already has the given requirements. CLI Example: .. code-block:: bash salt '*' pkg.check_extra_requirements 'sys-devel/gcc' '~>4.1.2:4.1::gentoo[nls,fortran]'
[ "Check", "if", "the", "installed", "package", "already", "has", "the", "given", "requirements", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ebuildpkg.py#L1201-L1256
train