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/nilrt_ip.py
build_network_settings
def build_network_settings(**settings): ''' Build the global network script. CLI Example: .. code-block:: bash salt '*' ip.build_network_settings <settings> ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') changes = [] if 'networking' in settings: if settings['networking'] in _CONFIG_TRUE: __salt__['service.enable']('connman') else: __salt__['service.disable']('connman') if 'hostname' in settings: new_hostname = settings['hostname'].split('.', 1)[0] settings['hostname'] = new_hostname old_hostname = __salt__['network.get_hostname'] if new_hostname != old_hostname: __salt__['network.mod_hostname'](new_hostname) changes.append('hostname={0}'.format(new_hostname)) return changes
python
def build_network_settings(**settings): ''' Build the global network script. CLI Example: .. code-block:: bash salt '*' ip.build_network_settings <settings> ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') changes = [] if 'networking' in settings: if settings['networking'] in _CONFIG_TRUE: __salt__['service.enable']('connman') else: __salt__['service.disable']('connman') if 'hostname' in settings: new_hostname = settings['hostname'].split('.', 1)[0] settings['hostname'] = new_hostname old_hostname = __salt__['network.get_hostname'] if new_hostname != old_hostname: __salt__['network.mod_hostname'](new_hostname) changes.append('hostname={0}'.format(new_hostname)) return changes
[ "def", "build_network_settings", "(", "*", "*", "settings", ")", ":", "if", "__grains__", "[", "'lsb_distrib_id'", "]", "==", "'nilrt'", ":", "raise", "salt", ".", "exceptions", ".", "CommandExecutionError", "(", "'Not supported in this version.'", ")", "changes", ...
Build the global network script. CLI Example: .. code-block:: bash salt '*' ip.build_network_settings <settings>
[ "Build", "the", "global", "network", "script", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L951-L978
train
saltstack/salt
salt/modules/nilrt_ip.py
get_network_settings
def get_network_settings(): ''' Return the contents of the global network script. CLI Example: .. code-block:: bash salt '*' ip.get_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') settings = [] networking = 'no' if _get_state() == 'offline' else 'yes' settings.append('networking={0}'.format(networking)) hostname = __salt__['network.get_hostname'] settings.append('hostname={0}'.format(hostname)) return settings
python
def get_network_settings(): ''' Return the contents of the global network script. CLI Example: .. code-block:: bash salt '*' ip.get_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') settings = [] networking = 'no' if _get_state() == 'offline' else 'yes' settings.append('networking={0}'.format(networking)) hostname = __salt__['network.get_hostname'] settings.append('hostname={0}'.format(hostname)) return settings
[ "def", "get_network_settings", "(", ")", ":", "if", "__grains__", "[", "'lsb_distrib_id'", "]", "==", "'nilrt'", ":", "raise", "salt", ".", "exceptions", ".", "CommandExecutionError", "(", "'Not supported in this version.'", ")", "settings", "=", "[", "]", "networ...
Return the contents of the global network script. CLI Example: .. code-block:: bash salt '*' ip.get_network_settings
[ "Return", "the", "contents", "of", "the", "global", "network", "script", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L981-L998
train
saltstack/salt
salt/modules/nilrt_ip.py
apply_network_settings
def apply_network_settings(**settings): ''' Apply global network configuration. CLI Example: .. code-block:: bash salt '*' ip.apply_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') if 'require_reboot' not in settings: settings['require_reboot'] = False if 'apply_hostname' not in settings: settings['apply_hostname'] = False hostname_res = True if settings['apply_hostname'] in _CONFIG_TRUE: if 'hostname' in settings: hostname_res = __salt__['network.mod_hostname'](settings['hostname']) else: log.warning( 'The network state sls is trying to apply hostname ' 'changes but no hostname is defined.' ) hostname_res = False res = True if settings['require_reboot'] in _CONFIG_TRUE: log.warning( 'The network state sls is requiring a reboot of the system to ' 'properly apply network configuration.' ) res = True else: stop = __salt__['service.stop']('connman') time.sleep(2) res = stop and __salt__['service.start']('connman') return hostname_res and res
python
def apply_network_settings(**settings): ''' Apply global network configuration. CLI Example: .. code-block:: bash salt '*' ip.apply_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') if 'require_reboot' not in settings: settings['require_reboot'] = False if 'apply_hostname' not in settings: settings['apply_hostname'] = False hostname_res = True if settings['apply_hostname'] in _CONFIG_TRUE: if 'hostname' in settings: hostname_res = __salt__['network.mod_hostname'](settings['hostname']) else: log.warning( 'The network state sls is trying to apply hostname ' 'changes but no hostname is defined.' ) hostname_res = False res = True if settings['require_reboot'] in _CONFIG_TRUE: log.warning( 'The network state sls is requiring a reboot of the system to ' 'properly apply network configuration.' ) res = True else: stop = __salt__['service.stop']('connman') time.sleep(2) res = stop and __salt__['service.start']('connman') return hostname_res and res
[ "def", "apply_network_settings", "(", "*", "*", "settings", ")", ":", "if", "__grains__", "[", "'lsb_distrib_id'", "]", "==", "'nilrt'", ":", "raise", "salt", ".", "exceptions", ".", "CommandExecutionError", "(", "'Not supported in this version.'", ")", "if", "'re...
Apply global network configuration. CLI Example: .. code-block:: bash salt '*' ip.apply_network_settings
[ "Apply", "global", "network", "configuration", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L1001-L1042
train
saltstack/salt
salt/utils/event.py
get_event
def get_event( node, sock_dir=None, transport='zeromq', opts=None, listen=True, io_loop=None, keep_loop=False, raise_errors=False): ''' Return an event object suitable for the named transport :param IOLoop io_loop: Pass in an io_loop if you want asynchronous operation for obtaining events. Eg use of set_event_handler() API. Otherwise, operation will be synchronous. ''' sock_dir = sock_dir or opts['sock_dir'] # TODO: AIO core is separate from transport if node == 'master': return MasterEvent(sock_dir, opts, listen=listen, io_loop=io_loop, keep_loop=keep_loop, raise_errors=raise_errors) return SaltEvent(node, sock_dir, opts, listen=listen, io_loop=io_loop, keep_loop=keep_loop, raise_errors=raise_errors)
python
def get_event( node, sock_dir=None, transport='zeromq', opts=None, listen=True, io_loop=None, keep_loop=False, raise_errors=False): ''' Return an event object suitable for the named transport :param IOLoop io_loop: Pass in an io_loop if you want asynchronous operation for obtaining events. Eg use of set_event_handler() API. Otherwise, operation will be synchronous. ''' sock_dir = sock_dir or opts['sock_dir'] # TODO: AIO core is separate from transport if node == 'master': return MasterEvent(sock_dir, opts, listen=listen, io_loop=io_loop, keep_loop=keep_loop, raise_errors=raise_errors) return SaltEvent(node, sock_dir, opts, listen=listen, io_loop=io_loop, keep_loop=keep_loop, raise_errors=raise_errors)
[ "def", "get_event", "(", "node", ",", "sock_dir", "=", "None", ",", "transport", "=", "'zeromq'", ",", "opts", "=", "None", ",", "listen", "=", "True", ",", "io_loop", "=", "None", ",", "keep_loop", "=", "False", ",", "raise_errors", "=", "False", ")",...
Return an event object suitable for the named transport :param IOLoop io_loop: Pass in an io_loop if you want asynchronous operation for obtaining events. Eg use of set_event_handler() API. Otherwise, operation will be synchronous.
[ "Return", "an", "event", "object", "suitable", "for", "the", "named", "transport" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/event.py#L119-L145
train
saltstack/salt
salt/utils/event.py
get_master_event
def get_master_event(opts, sock_dir, listen=True, io_loop=None, raise_errors=False, keep_loop=False): ''' Return an event object suitable for the named transport ''' # TODO: AIO core is separate from transport if opts['transport'] in ('zeromq', 'tcp', 'detect'): return MasterEvent(sock_dir, opts, listen=listen, io_loop=io_loop, raise_errors=raise_errors, keep_loop=keep_loop)
python
def get_master_event(opts, sock_dir, listen=True, io_loop=None, raise_errors=False, keep_loop=False): ''' Return an event object suitable for the named transport ''' # TODO: AIO core is separate from transport if opts['transport'] in ('zeromq', 'tcp', 'detect'): return MasterEvent(sock_dir, opts, listen=listen, io_loop=io_loop, raise_errors=raise_errors, keep_loop=keep_loop)
[ "def", "get_master_event", "(", "opts", ",", "sock_dir", ",", "listen", "=", "True", ",", "io_loop", "=", "None", ",", "raise_errors", "=", "False", ",", "keep_loop", "=", "False", ")", ":", "# TODO: AIO core is separate from transport", "if", "opts", "[", "'t...
Return an event object suitable for the named transport
[ "Return", "an", "event", "object", "suitable", "for", "the", "named", "transport" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/event.py#L148-L154
train
saltstack/salt
salt/utils/event.py
fire_args
def fire_args(opts, jid, tag_data, prefix=''): ''' Fire an event containing the arguments passed to an orchestration job ''' try: tag_suffix = [jid, 'args'] except NameError: pass else: tag = tagify(tag_suffix, prefix) try: _event = get_master_event(opts, opts['sock_dir'], listen=False) _event.fire_event(tag_data, tag=tag) except Exception as exc: # Don't let a problem here hold up the rest of the orchestration log.warning( 'Failed to fire args event %s with data %s: %s', tag, tag_data, exc )
python
def fire_args(opts, jid, tag_data, prefix=''): ''' Fire an event containing the arguments passed to an orchestration job ''' try: tag_suffix = [jid, 'args'] except NameError: pass else: tag = tagify(tag_suffix, prefix) try: _event = get_master_event(opts, opts['sock_dir'], listen=False) _event.fire_event(tag_data, tag=tag) except Exception as exc: # Don't let a problem here hold up the rest of the orchestration log.warning( 'Failed to fire args event %s with data %s: %s', tag, tag_data, exc )
[ "def", "fire_args", "(", "opts", ",", "jid", ",", "tag_data", ",", "prefix", "=", "''", ")", ":", "try", ":", "tag_suffix", "=", "[", "jid", ",", "'args'", "]", "except", "NameError", ":", "pass", "else", ":", "tag", "=", "tagify", "(", "tag_suffix",...
Fire an event containing the arguments passed to an orchestration job
[ "Fire", "an", "event", "containing", "the", "arguments", "passed", "to", "an", "orchestration", "job" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/event.py#L157-L175
train
saltstack/salt
salt/utils/event.py
tagify
def tagify(suffix='', prefix='', base=SALT): ''' convenience function to build a namespaced event tag string from joining with the TABPART character the base, prefix and suffix If string prefix is a valid key in TAGS Then use the value of key prefix Else use prefix string If suffix is a list Then join all string elements of suffix individually Else use string suffix ''' parts = [base, TAGS.get(prefix, prefix)] if hasattr(suffix, 'append'): # list so extend parts parts.extend(suffix) else: # string so append parts.append(suffix) for index, _ in enumerate(parts): try: parts[index] = salt.utils.stringutils.to_str(parts[index]) except TypeError: parts[index] = str(parts[index]) return TAGPARTER.join([part for part in parts if part])
python
def tagify(suffix='', prefix='', base=SALT): ''' convenience function to build a namespaced event tag string from joining with the TABPART character the base, prefix and suffix If string prefix is a valid key in TAGS Then use the value of key prefix Else use prefix string If suffix is a list Then join all string elements of suffix individually Else use string suffix ''' parts = [base, TAGS.get(prefix, prefix)] if hasattr(suffix, 'append'): # list so extend parts parts.extend(suffix) else: # string so append parts.append(suffix) for index, _ in enumerate(parts): try: parts[index] = salt.utils.stringutils.to_str(parts[index]) except TypeError: parts[index] = str(parts[index]) return TAGPARTER.join([part for part in parts if part])
[ "def", "tagify", "(", "suffix", "=", "''", ",", "prefix", "=", "''", ",", "base", "=", "SALT", ")", ":", "parts", "=", "[", "base", ",", "TAGS", ".", "get", "(", "prefix", ",", "prefix", ")", "]", "if", "hasattr", "(", "suffix", ",", "'append'", ...
convenience function to build a namespaced event tag string from joining with the TABPART character the base, prefix and suffix If string prefix is a valid key in TAGS Then use the value of key prefix Else use prefix string If suffix is a list Then join all string elements of suffix individually Else use string suffix
[ "convenience", "function", "to", "build", "a", "namespaced", "event", "tag", "string", "from", "joining", "with", "the", "TABPART", "character", "the", "base", "prefix", "and", "suffix" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/event.py#L178-L201
train
saltstack/salt
salt/utils/event.py
update_stats
def update_stats(stats, start_time, data): ''' Calculate the master stats and return the updated stat info ''' end_time = time.time() cmd = data['cmd'] # the jid is used as the create time try: jid = data['jid'] except KeyError: try: jid = data['data']['__pub_jid'] except KeyError: log.info('jid not found in data, stats not updated') return stats create_time = int(time.mktime(time.strptime(jid, '%Y%m%d%H%M%S%f'))) latency = start_time - create_time duration = end_time - start_time stats[cmd]['runs'] += 1 stats[cmd]['latency'] = (stats[cmd]['latency'] * (stats[cmd]['runs'] - 1) + latency) / stats[cmd]['runs'] stats[cmd]['mean'] = (stats[cmd]['mean'] * (stats[cmd]['runs'] - 1) + duration) / stats[cmd]['runs'] return stats
python
def update_stats(stats, start_time, data): ''' Calculate the master stats and return the updated stat info ''' end_time = time.time() cmd = data['cmd'] # the jid is used as the create time try: jid = data['jid'] except KeyError: try: jid = data['data']['__pub_jid'] except KeyError: log.info('jid not found in data, stats not updated') return stats create_time = int(time.mktime(time.strptime(jid, '%Y%m%d%H%M%S%f'))) latency = start_time - create_time duration = end_time - start_time stats[cmd]['runs'] += 1 stats[cmd]['latency'] = (stats[cmd]['latency'] * (stats[cmd]['runs'] - 1) + latency) / stats[cmd]['runs'] stats[cmd]['mean'] = (stats[cmd]['mean'] * (stats[cmd]['runs'] - 1) + duration) / stats[cmd]['runs'] return stats
[ "def", "update_stats", "(", "stats", ",", "start_time", ",", "data", ")", ":", "end_time", "=", "time", ".", "time", "(", ")", "cmd", "=", "data", "[", "'cmd'", "]", "# the jid is used as the create time", "try", ":", "jid", "=", "data", "[", "'jid'", "]...
Calculate the master stats and return the updated stat info
[ "Calculate", "the", "master", "stats", "and", "return", "the", "updated", "stat", "info" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/event.py#L204-L227
train
saltstack/salt
salt/utils/event.py
SaltEvent.__load_uri
def __load_uri(self, sock_dir, node): ''' Return the string URI for the location of the pull and pub sockets to use for firing and listening to events ''' if node == 'master': if self.opts['ipc_mode'] == 'tcp': puburi = int(self.opts['tcp_master_pub_port']) pulluri = int(self.opts['tcp_master_pull_port']) else: puburi = os.path.join( sock_dir, 'master_event_pub.ipc' ) pulluri = os.path.join( sock_dir, 'master_event_pull.ipc' ) else: if self.opts['ipc_mode'] == 'tcp': puburi = int(self.opts['tcp_pub_port']) pulluri = int(self.opts['tcp_pull_port']) else: hash_type = getattr(hashlib, self.opts['hash_type']) # Only use the first 10 chars to keep longer hashes from exceeding the # max socket path length. id_hash = hash_type(salt.utils.stringutils.to_bytes(self.opts['id'])).hexdigest()[:10] puburi = os.path.join( sock_dir, 'minion_event_{0}_pub.ipc'.format(id_hash) ) pulluri = os.path.join( sock_dir, 'minion_event_{0}_pull.ipc'.format(id_hash) ) log.debug('%s PUB socket URI: %s', self.__class__.__name__, puburi) log.debug('%s PULL socket URI: %s', self.__class__.__name__, pulluri) return puburi, pulluri
python
def __load_uri(self, sock_dir, node): ''' Return the string URI for the location of the pull and pub sockets to use for firing and listening to events ''' if node == 'master': if self.opts['ipc_mode'] == 'tcp': puburi = int(self.opts['tcp_master_pub_port']) pulluri = int(self.opts['tcp_master_pull_port']) else: puburi = os.path.join( sock_dir, 'master_event_pub.ipc' ) pulluri = os.path.join( sock_dir, 'master_event_pull.ipc' ) else: if self.opts['ipc_mode'] == 'tcp': puburi = int(self.opts['tcp_pub_port']) pulluri = int(self.opts['tcp_pull_port']) else: hash_type = getattr(hashlib, self.opts['hash_type']) # Only use the first 10 chars to keep longer hashes from exceeding the # max socket path length. id_hash = hash_type(salt.utils.stringutils.to_bytes(self.opts['id'])).hexdigest()[:10] puburi = os.path.join( sock_dir, 'minion_event_{0}_pub.ipc'.format(id_hash) ) pulluri = os.path.join( sock_dir, 'minion_event_{0}_pull.ipc'.format(id_hash) ) log.debug('%s PUB socket URI: %s', self.__class__.__name__, puburi) log.debug('%s PULL socket URI: %s', self.__class__.__name__, pulluri) return puburi, pulluri
[ "def", "__load_uri", "(", "self", ",", "sock_dir", ",", "node", ")", ":", "if", "node", "==", "'master'", ":", "if", "self", ".", "opts", "[", "'ipc_mode'", "]", "==", "'tcp'", ":", "puburi", "=", "int", "(", "self", ".", "opts", "[", "'tcp_master_pu...
Return the string URI for the location of the pull and pub sockets to use for firing and listening to events
[ "Return", "the", "string", "URI", "for", "the", "location", "of", "the", "pull", "and", "pub", "sockets", "to", "use", "for", "firing", "and", "listening", "to", "events" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/event.py#L302-L339
train
saltstack/salt
salt/utils/event.py
SaltEvent.subscribe
def subscribe(self, tag=None, match_type=None): ''' Subscribe to events matching the passed tag. If you do not subscribe to a tag, events will be discarded by calls to get_event that request a different tag. In contexts where many different jobs are outstanding it is important to subscribe to prevent one call to get_event from discarding a response required by a subsequent call to get_event. ''' if tag is None: return match_func = self._get_match_func(match_type) self.pending_tags.append([tag, match_func])
python
def subscribe(self, tag=None, match_type=None): ''' Subscribe to events matching the passed tag. If you do not subscribe to a tag, events will be discarded by calls to get_event that request a different tag. In contexts where many different jobs are outstanding it is important to subscribe to prevent one call to get_event from discarding a response required by a subsequent call to get_event. ''' if tag is None: return match_func = self._get_match_func(match_type) self.pending_tags.append([tag, match_func])
[ "def", "subscribe", "(", "self", ",", "tag", "=", "None", ",", "match_type", "=", "None", ")", ":", "if", "tag", "is", "None", ":", "return", "match_func", "=", "self", ".", "_get_match_func", "(", "match_type", ")", "self", ".", "pending_tags", ".", "...
Subscribe to events matching the passed tag. If you do not subscribe to a tag, events will be discarded by calls to get_event that request a different tag. In contexts where many different jobs are outstanding it is important to subscribe to prevent one call to get_event from discarding a response required by a subsequent call to get_event.
[ "Subscribe", "to", "events", "matching", "the", "passed", "tag", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/event.py#L341-L354
train
saltstack/salt
salt/utils/event.py
SaltEvent.unsubscribe
def unsubscribe(self, tag, match_type=None): ''' Un-subscribe to events matching the passed tag. ''' if tag is None: return match_func = self._get_match_func(match_type) self.pending_tags.remove([tag, match_func]) old_events = self.pending_events self.pending_events = [] for evt in old_events: if any(pmatch_func(evt['tag'], ptag) for ptag, pmatch_func in self.pending_tags): self.pending_events.append(evt)
python
def unsubscribe(self, tag, match_type=None): ''' Un-subscribe to events matching the passed tag. ''' if tag is None: return match_func = self._get_match_func(match_type) self.pending_tags.remove([tag, match_func]) old_events = self.pending_events self.pending_events = [] for evt in old_events: if any(pmatch_func(evt['tag'], ptag) for ptag, pmatch_func in self.pending_tags): self.pending_events.append(evt)
[ "def", "unsubscribe", "(", "self", ",", "tag", ",", "match_type", "=", "None", ")", ":", "if", "tag", "is", "None", ":", "return", "match_func", "=", "self", ".", "_get_match_func", "(", "match_type", ")", "self", ".", "pending_tags", ".", "remove", "(",...
Un-subscribe to events matching the passed tag.
[ "Un", "-", "subscribe", "to", "events", "matching", "the", "passed", "tag", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/event.py#L356-L370
train
saltstack/salt
salt/utils/event.py
SaltEvent.connect_pub
def connect_pub(self, timeout=None): ''' Establish the publish connection ''' if self.cpub: return True if self._run_io_loop_sync: with salt.utils.asynchronous.current_ioloop(self.io_loop): if self.subscriber is None: self.subscriber = salt.transport.ipc.IPCMessageSubscriber( self.puburi, io_loop=self.io_loop ) try: self.io_loop.run_sync( lambda: self.subscriber.connect(timeout=timeout)) self.cpub = True except Exception: pass else: if self.subscriber is None: self.subscriber = salt.transport.ipc.IPCMessageSubscriber( self.puburi, io_loop=self.io_loop ) # For the asynchronous case, the connect will be defered to when # set_event_handler() is invoked. self.cpub = True return self.cpub
python
def connect_pub(self, timeout=None): ''' Establish the publish connection ''' if self.cpub: return True if self._run_io_loop_sync: with salt.utils.asynchronous.current_ioloop(self.io_loop): if self.subscriber is None: self.subscriber = salt.transport.ipc.IPCMessageSubscriber( self.puburi, io_loop=self.io_loop ) try: self.io_loop.run_sync( lambda: self.subscriber.connect(timeout=timeout)) self.cpub = True except Exception: pass else: if self.subscriber is None: self.subscriber = salt.transport.ipc.IPCMessageSubscriber( self.puburi, io_loop=self.io_loop ) # For the asynchronous case, the connect will be defered to when # set_event_handler() is invoked. self.cpub = True return self.cpub
[ "def", "connect_pub", "(", "self", ",", "timeout", "=", "None", ")", ":", "if", "self", ".", "cpub", ":", "return", "True", "if", "self", ".", "_run_io_loop_sync", ":", "with", "salt", ".", "utils", ".", "asynchronous", ".", "current_ioloop", "(", "self"...
Establish the publish connection
[ "Establish", "the", "publish", "connection" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/event.py#L372-L402
train
saltstack/salt
salt/utils/event.py
SaltEvent.close_pub
def close_pub(self): ''' Close the publish connection (if established) ''' if not self.cpub: return self.subscriber.close() self.subscriber = None self.pending_events = [] self.cpub = False
python
def close_pub(self): ''' Close the publish connection (if established) ''' if not self.cpub: return self.subscriber.close() self.subscriber = None self.pending_events = [] self.cpub = False
[ "def", "close_pub", "(", "self", ")", ":", "if", "not", "self", ".", "cpub", ":", "return", "self", ".", "subscriber", ".", "close", "(", ")", "self", ".", "subscriber", "=", "None", "self", ".", "pending_events", "=", "[", "]", "self", ".", "cpub", ...
Close the publish connection (if established)
[ "Close", "the", "publish", "connection", "(", "if", "established", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/event.py#L404-L414
train
saltstack/salt
salt/utils/event.py
SaltEvent.connect_pull
def connect_pull(self, timeout=1): ''' Establish a connection with the event pull socket Default timeout is 1 s ''' if self.cpush: return True if self._run_io_loop_sync: with salt.utils.asynchronous.current_ioloop(self.io_loop): if self.pusher is None: self.pusher = salt.transport.ipc.IPCMessageClient( self.pulluri, io_loop=self.io_loop ) try: self.io_loop.run_sync( lambda: self.pusher.connect(timeout=timeout)) self.cpush = True except Exception: pass else: if self.pusher is None: self.pusher = salt.transport.ipc.IPCMessageClient( self.pulluri, io_loop=self.io_loop ) # For the asynchronous case, the connect will be deferred to when # fire_event() is invoked. self.cpush = True return self.cpush
python
def connect_pull(self, timeout=1): ''' Establish a connection with the event pull socket Default timeout is 1 s ''' if self.cpush: return True if self._run_io_loop_sync: with salt.utils.asynchronous.current_ioloop(self.io_loop): if self.pusher is None: self.pusher = salt.transport.ipc.IPCMessageClient( self.pulluri, io_loop=self.io_loop ) try: self.io_loop.run_sync( lambda: self.pusher.connect(timeout=timeout)) self.cpush = True except Exception: pass else: if self.pusher is None: self.pusher = salt.transport.ipc.IPCMessageClient( self.pulluri, io_loop=self.io_loop ) # For the asynchronous case, the connect will be deferred to when # fire_event() is invoked. self.cpush = True return self.cpush
[ "def", "connect_pull", "(", "self", ",", "timeout", "=", "1", ")", ":", "if", "self", ".", "cpush", ":", "return", "True", "if", "self", ".", "_run_io_loop_sync", ":", "with", "salt", ".", "utils", ".", "asynchronous", ".", "current_ioloop", "(", "self",...
Establish a connection with the event pull socket Default timeout is 1 s
[ "Establish", "a", "connection", "with", "the", "event", "pull", "socket", "Default", "timeout", "is", "1", "s" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/event.py#L416-L446
train
saltstack/salt
salt/utils/event.py
SaltEvent._check_pending
def _check_pending(self, tag, match_func=None): """Check the pending_events list for events that match the tag :param tag: The tag to search for :type tag: str :param tags_regex: List of re expressions to search for also :type tags_regex: list[re.compile()] :return: """ if match_func is None: match_func = self._get_match_func() old_events = self.pending_events self.pending_events = [] ret = None for evt in old_events: if match_func(evt['tag'], tag): if ret is None: ret = evt log.trace('get_event() returning cached event = %s', ret) else: self.pending_events.append(evt) elif any(pmatch_func(evt['tag'], ptag) for ptag, pmatch_func in self.pending_tags): self.pending_events.append(evt) else: log.trace('get_event() discarding cached event that no longer has any subscriptions = %s', evt) return ret
python
def _check_pending(self, tag, match_func=None): """Check the pending_events list for events that match the tag :param tag: The tag to search for :type tag: str :param tags_regex: List of re expressions to search for also :type tags_regex: list[re.compile()] :return: """ if match_func is None: match_func = self._get_match_func() old_events = self.pending_events self.pending_events = [] ret = None for evt in old_events: if match_func(evt['tag'], tag): if ret is None: ret = evt log.trace('get_event() returning cached event = %s', ret) else: self.pending_events.append(evt) elif any(pmatch_func(evt['tag'], ptag) for ptag, pmatch_func in self.pending_tags): self.pending_events.append(evt) else: log.trace('get_event() discarding cached event that no longer has any subscriptions = %s', evt) return ret
[ "def", "_check_pending", "(", "self", ",", "tag", ",", "match_func", "=", "None", ")", ":", "if", "match_func", "is", "None", ":", "match_func", "=", "self", ".", "_get_match_func", "(", ")", "old_events", "=", "self", ".", "pending_events", "self", ".", ...
Check the pending_events list for events that match the tag :param tag: The tag to search for :type tag: str :param tags_regex: List of re expressions to search for also :type tags_regex: list[re.compile()] :return:
[ "Check", "the", "pending_events", "list", "for", "events", "that", "match", "the", "tag" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/event.py#L467-L492
train
saltstack/salt
salt/utils/event.py
SaltEvent._match_tag_regex
def _match_tag_regex(self, event_tag, search_tag): ''' Check if the event_tag matches the search check. Uses regular expression search to check. Return True (matches) or False (no match) ''' return self.cache_regex.get(search_tag).search(event_tag) is not None
python
def _match_tag_regex(self, event_tag, search_tag): ''' Check if the event_tag matches the search check. Uses regular expression search to check. Return True (matches) or False (no match) ''' return self.cache_regex.get(search_tag).search(event_tag) is not None
[ "def", "_match_tag_regex", "(", "self", ",", "event_tag", ",", "search_tag", ")", ":", "return", "self", ".", "cache_regex", ".", "get", "(", "search_tag", ")", ".", "search", "(", "event_tag", ")", "is", "not", "None" ]
Check if the event_tag matches the search check. Uses regular expression search to check. Return True (matches) or False (no match)
[ "Check", "if", "the", "event_tag", "matches", "the", "search", "check", ".", "Uses", "regular", "expression", "search", "to", "check", ".", "Return", "True", "(", "matches", ")", "or", "False", "(", "no", "match", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/event.py#L521-L527
train
saltstack/salt
salt/utils/event.py
SaltEvent.get_event
def get_event(self, wait=5, tag='', full=False, match_type=None, no_block=False, auto_reconnect=False): ''' Get a single publication. If no publication is available, then block for up to ``wait`` seconds. Return publication if it is available or ``None`` if no publication is available. If wait is 0, then block forever. tag Only return events matching the given tag. If not specified, or set to an empty string, all events are returned. It is recommended to always be selective on what is to be returned in the event that multiple requests are being multiplexed. match_type Set the function to match the search tag with event tags. - 'startswith' : search for event tags that start with tag - 'endswith' : search for event tags that end with tag - 'find' : search for event tags that contain tag - 'regex' : regex search '^' + tag event tags - 'fnmatch' : fnmatch tag event tags matching Default is opts['event_match_type'] or 'startswith' .. versionadded:: 2015.8.0 no_block Define if getting the event should be a blocking call or not. Defaults to False to keep backwards compatibility. .. versionadded:: 2015.8.0 Notes: Searches cached publications first. If no cached publications are found that match the given tag specification, new publications are received and checked. If a publication is received that does not match the tag specification, it is DISCARDED unless it is subscribed to via subscribe() which will cause it to be cached. If a caller is not going to call get_event immediately after sending a request, it MUST subscribe the result to ensure the response is not lost should other regions of code call get_event for other purposes. ''' assert self._run_io_loop_sync match_func = self._get_match_func(match_type) ret = self._check_pending(tag, match_func) if ret is None: with salt.utils.asynchronous.current_ioloop(self.io_loop): if auto_reconnect: raise_errors = self.raise_errors self.raise_errors = True while True: try: ret = self._get_event(wait, tag, match_func, no_block) break except tornado.iostream.StreamClosedError: self.close_pub() self.connect_pub(timeout=wait) continue self.raise_errors = raise_errors else: ret = self._get_event(wait, tag, match_func, no_block) if ret is None or full: return ret else: return ret['data']
python
def get_event(self, wait=5, tag='', full=False, match_type=None, no_block=False, auto_reconnect=False): ''' Get a single publication. If no publication is available, then block for up to ``wait`` seconds. Return publication if it is available or ``None`` if no publication is available. If wait is 0, then block forever. tag Only return events matching the given tag. If not specified, or set to an empty string, all events are returned. It is recommended to always be selective on what is to be returned in the event that multiple requests are being multiplexed. match_type Set the function to match the search tag with event tags. - 'startswith' : search for event tags that start with tag - 'endswith' : search for event tags that end with tag - 'find' : search for event tags that contain tag - 'regex' : regex search '^' + tag event tags - 'fnmatch' : fnmatch tag event tags matching Default is opts['event_match_type'] or 'startswith' .. versionadded:: 2015.8.0 no_block Define if getting the event should be a blocking call or not. Defaults to False to keep backwards compatibility. .. versionadded:: 2015.8.0 Notes: Searches cached publications first. If no cached publications are found that match the given tag specification, new publications are received and checked. If a publication is received that does not match the tag specification, it is DISCARDED unless it is subscribed to via subscribe() which will cause it to be cached. If a caller is not going to call get_event immediately after sending a request, it MUST subscribe the result to ensure the response is not lost should other regions of code call get_event for other purposes. ''' assert self._run_io_loop_sync match_func = self._get_match_func(match_type) ret = self._check_pending(tag, match_func) if ret is None: with salt.utils.asynchronous.current_ioloop(self.io_loop): if auto_reconnect: raise_errors = self.raise_errors self.raise_errors = True while True: try: ret = self._get_event(wait, tag, match_func, no_block) break except tornado.iostream.StreamClosedError: self.close_pub() self.connect_pub(timeout=wait) continue self.raise_errors = raise_errors else: ret = self._get_event(wait, tag, match_func, no_block) if ret is None or full: return ret else: return ret['data']
[ "def", "get_event", "(", "self", ",", "wait", "=", "5", ",", "tag", "=", "''", ",", "full", "=", "False", ",", "match_type", "=", "None", ",", "no_block", "=", "False", ",", "auto_reconnect", "=", "False", ")", ":", "assert", "self", ".", "_run_io_lo...
Get a single publication. If no publication is available, then block for up to ``wait`` seconds. Return publication if it is available or ``None`` if no publication is available. If wait is 0, then block forever. tag Only return events matching the given tag. If not specified, or set to an empty string, all events are returned. It is recommended to always be selective on what is to be returned in the event that multiple requests are being multiplexed. match_type Set the function to match the search tag with event tags. - 'startswith' : search for event tags that start with tag - 'endswith' : search for event tags that end with tag - 'find' : search for event tags that contain tag - 'regex' : regex search '^' + tag event tags - 'fnmatch' : fnmatch tag event tags matching Default is opts['event_match_type'] or 'startswith' .. versionadded:: 2015.8.0 no_block Define if getting the event should be a blocking call or not. Defaults to False to keep backwards compatibility. .. versionadded:: 2015.8.0 Notes: Searches cached publications first. If no cached publications are found that match the given tag specification, new publications are received and checked. If a publication is received that does not match the tag specification, it is DISCARDED unless it is subscribed to via subscribe() which will cause it to be cached. If a caller is not going to call get_event immediately after sending a request, it MUST subscribe the result to ensure the response is not lost should other regions of code call get_event for other purposes.
[ "Get", "a", "single", "publication", ".", "If", "no", "publication", "is", "available", "then", "block", "for", "up", "to", "wait", "seconds", ".", "Return", "publication", "if", "it", "is", "available", "or", "None", "if", "no", "publication", "is", "avai...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/event.py#L590-L667
train
saltstack/salt
salt/utils/event.py
SaltEvent.get_event_noblock
def get_event_noblock(self): ''' Get the raw event without blocking or any other niceties ''' assert self._run_io_loop_sync if not self.cpub: if not self.connect_pub(): return None raw = self.subscriber.read_sync(timeout=0) if raw is None: return None mtag, data = self.unpack(raw, self.serial) return {'data': data, 'tag': mtag}
python
def get_event_noblock(self): ''' Get the raw event without blocking or any other niceties ''' assert self._run_io_loop_sync if not self.cpub: if not self.connect_pub(): return None raw = self.subscriber.read_sync(timeout=0) if raw is None: return None mtag, data = self.unpack(raw, self.serial) return {'data': data, 'tag': mtag}
[ "def", "get_event_noblock", "(", "self", ")", ":", "assert", "self", ".", "_run_io_loop_sync", "if", "not", "self", ".", "cpub", ":", "if", "not", "self", ".", "connect_pub", "(", ")", ":", "return", "None", "raw", "=", "self", ".", "subscriber", ".", ...
Get the raw event without blocking or any other niceties
[ "Get", "the", "raw", "event", "without", "blocking", "or", "any", "other", "niceties" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/event.py#L669-L682
train
saltstack/salt
salt/utils/event.py
SaltEvent.iter_events
def iter_events(self, tag='', full=False, match_type=None, auto_reconnect=False): ''' Creates a generator that continuously listens for events ''' while True: data = self.get_event(tag=tag, full=full, match_type=match_type, auto_reconnect=auto_reconnect) if data is None: continue yield data
python
def iter_events(self, tag='', full=False, match_type=None, auto_reconnect=False): ''' Creates a generator that continuously listens for events ''' while True: data = self.get_event(tag=tag, full=full, match_type=match_type, auto_reconnect=auto_reconnect) if data is None: continue yield data
[ "def", "iter_events", "(", "self", ",", "tag", "=", "''", ",", "full", "=", "False", ",", "match_type", "=", "None", ",", "auto_reconnect", "=", "False", ")", ":", "while", "True", ":", "data", "=", "self", ".", "get_event", "(", "tag", "=", "tag", ...
Creates a generator that continuously listens for events
[ "Creates", "a", "generator", "that", "continuously", "listens", "for", "events" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/event.py#L700-L709
train
saltstack/salt
salt/utils/event.py
SaltEvent.fire_event
def fire_event(self, data, tag, timeout=1000): ''' Send a single event into the publisher with payload dict "data" and event identifier "tag" The default is 1000 ms ''' if not six.text_type(tag): # no empty tags allowed raise ValueError('Empty tag.') if not isinstance(data, MutableMapping): # data must be dict raise ValueError( 'Dict object expected, not \'{0}\'.'.format(data) ) if not self.cpush: if timeout is not None: timeout_s = float(timeout) / 1000 else: timeout_s = None if not self.connect_pull(timeout=timeout_s): return False data['_stamp'] = datetime.datetime.utcnow().isoformat() tagend = TAGEND if six.PY2: dump_data = self.serial.dumps(data) else: # Since the pack / unpack logic here is for local events only, # it is safe to change the wire protocol. The mechanism # that sends events from minion to master is outside this # file. dump_data = self.serial.dumps(data, use_bin_type=True) serialized_data = salt.utils.dicttrim.trim_dict( dump_data, self.opts['max_event_size'], is_msgpacked=True, use_bin_type=six.PY3 ) log.debug('Sending event: tag = %s; data = %s', tag, data) event = b''.join([ salt.utils.stringutils.to_bytes(tag), salt.utils.stringutils.to_bytes(tagend), serialized_data]) msg = salt.utils.stringutils.to_bytes(event, 'utf-8') if self._run_io_loop_sync: with salt.utils.asynchronous.current_ioloop(self.io_loop): try: self.io_loop.run_sync(lambda: self.pusher.send(msg)) except Exception as ex: log.debug(ex) raise else: self.io_loop.spawn_callback(self.pusher.send, msg) return True
python
def fire_event(self, data, tag, timeout=1000): ''' Send a single event into the publisher with payload dict "data" and event identifier "tag" The default is 1000 ms ''' if not six.text_type(tag): # no empty tags allowed raise ValueError('Empty tag.') if not isinstance(data, MutableMapping): # data must be dict raise ValueError( 'Dict object expected, not \'{0}\'.'.format(data) ) if not self.cpush: if timeout is not None: timeout_s = float(timeout) / 1000 else: timeout_s = None if not self.connect_pull(timeout=timeout_s): return False data['_stamp'] = datetime.datetime.utcnow().isoformat() tagend = TAGEND if six.PY2: dump_data = self.serial.dumps(data) else: # Since the pack / unpack logic here is for local events only, # it is safe to change the wire protocol. The mechanism # that sends events from minion to master is outside this # file. dump_data = self.serial.dumps(data, use_bin_type=True) serialized_data = salt.utils.dicttrim.trim_dict( dump_data, self.opts['max_event_size'], is_msgpacked=True, use_bin_type=six.PY3 ) log.debug('Sending event: tag = %s; data = %s', tag, data) event = b''.join([ salt.utils.stringutils.to_bytes(tag), salt.utils.stringutils.to_bytes(tagend), serialized_data]) msg = salt.utils.stringutils.to_bytes(event, 'utf-8') if self._run_io_loop_sync: with salt.utils.asynchronous.current_ioloop(self.io_loop): try: self.io_loop.run_sync(lambda: self.pusher.send(msg)) except Exception as ex: log.debug(ex) raise else: self.io_loop.spawn_callback(self.pusher.send, msg) return True
[ "def", "fire_event", "(", "self", ",", "data", ",", "tag", ",", "timeout", "=", "1000", ")", ":", "if", "not", "six", ".", "text_type", "(", "tag", ")", ":", "# no empty tags allowed", "raise", "ValueError", "(", "'Empty tag.'", ")", "if", "not", "isinst...
Send a single event into the publisher with payload dict "data" and event identifier "tag" The default is 1000 ms
[ "Send", "a", "single", "event", "into", "the", "publisher", "with", "payload", "dict", "data", "and", "event", "identifier", "tag" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/event.py#L711-L767
train
saltstack/salt
salt/utils/event.py
SaltEvent.fire_master
def fire_master(self, data, tag, timeout=1000): '''' Send a single event to the master, with the payload "data" and the event identifier "tag". Default timeout is 1000ms ''' msg = { 'tag': tag, 'data': data, 'events': None, 'pretag': None } return self.fire_event(msg, "fire_master", timeout)
python
def fire_master(self, data, tag, timeout=1000): '''' Send a single event to the master, with the payload "data" and the event identifier "tag". Default timeout is 1000ms ''' msg = { 'tag': tag, 'data': data, 'events': None, 'pretag': None } return self.fire_event(msg, "fire_master", timeout)
[ "def", "fire_master", "(", "self", ",", "data", ",", "tag", ",", "timeout", "=", "1000", ")", ":", "msg", "=", "{", "'tag'", ":", "tag", ",", "'data'", ":", "data", ",", "'events'", ":", "None", ",", "'pretag'", ":", "None", "}", "return", "self", ...
Send a single event to the master, with the payload "data" and the event identifier "tag". Default timeout is 1000ms
[ "Send", "a", "single", "event", "to", "the", "master", "with", "the", "payload", "data", "and", "the", "event", "identifier", "tag", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/event.py#L769-L782
train
saltstack/salt
salt/utils/event.py
SaltEvent._fire_ret_load_specific_fun
def _fire_ret_load_specific_fun(self, load, fun_index=0): ''' Helper function for fire_ret_load ''' if isinstance(load['fun'], list): # Multi-function job fun = load['fun'][fun_index] # 'retcode' was already validated to exist and be non-zero # for the given function in the caller. if isinstance(load['retcode'], list): # Multi-function ordered ret = load.get('return') if isinstance(ret, list) and len(ret) > fun_index: ret = ret[fun_index] else: ret = {} retcode = load['retcode'][fun_index] else: ret = load.get('return', {}) ret = ret.get(fun, {}) retcode = load['retcode'][fun] else: # Single-function job fun = load['fun'] ret = load.get('return', {}) retcode = load['retcode'] try: for tag, data in six.iteritems(ret): data['retcode'] = retcode tags = tag.split('_|-') if data.get('result') is False: self.fire_event( data, '{0}.{1}'.format(tags[0], tags[-1]) ) # old dup event data['jid'] = load['jid'] data['id'] = load['id'] data['success'] = False data['return'] = 'Error: {0}.{1}'.format( tags[0], tags[-1]) data['fun'] = fun data['user'] = load['user'] self.fire_event( data, tagify([load['jid'], 'sub', load['id'], 'error', fun], 'job')) except Exception: pass
python
def _fire_ret_load_specific_fun(self, load, fun_index=0): ''' Helper function for fire_ret_load ''' if isinstance(load['fun'], list): # Multi-function job fun = load['fun'][fun_index] # 'retcode' was already validated to exist and be non-zero # for the given function in the caller. if isinstance(load['retcode'], list): # Multi-function ordered ret = load.get('return') if isinstance(ret, list) and len(ret) > fun_index: ret = ret[fun_index] else: ret = {} retcode = load['retcode'][fun_index] else: ret = load.get('return', {}) ret = ret.get(fun, {}) retcode = load['retcode'][fun] else: # Single-function job fun = load['fun'] ret = load.get('return', {}) retcode = load['retcode'] try: for tag, data in six.iteritems(ret): data['retcode'] = retcode tags = tag.split('_|-') if data.get('result') is False: self.fire_event( data, '{0}.{1}'.format(tags[0], tags[-1]) ) # old dup event data['jid'] = load['jid'] data['id'] = load['id'] data['success'] = False data['return'] = 'Error: {0}.{1}'.format( tags[0], tags[-1]) data['fun'] = fun data['user'] = load['user'] self.fire_event( data, tagify([load['jid'], 'sub', load['id'], 'error', fun], 'job')) except Exception: pass
[ "def", "_fire_ret_load_specific_fun", "(", "self", ",", "load", ",", "fun_index", "=", "0", ")", ":", "if", "isinstance", "(", "load", "[", "'fun'", "]", ",", "list", ")", ":", "# Multi-function job", "fun", "=", "load", "[", "'fun'", "]", "[", "fun_inde...
Helper function for fire_ret_load
[ "Helper", "function", "for", "fire_ret_load" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/event.py#L792-L844
train
saltstack/salt
salt/utils/event.py
SaltEvent.fire_ret_load
def fire_ret_load(self, load): ''' Fire events based on information in the return load ''' if load.get('retcode') and load.get('fun'): if isinstance(load['fun'], list): # Multi-function job if isinstance(load['retcode'], list): multifunc_ordered = True else: multifunc_ordered = False for fun_index in range(0, len(load['fun'])): fun = load['fun'][fun_index] if multifunc_ordered: if (len(load['retcode']) > fun_index and load['retcode'][fun_index] and fun in SUB_EVENT): # Minion fired a bad retcode, fire an event self._fire_ret_load_specific_fun(load, fun_index) else: if load['retcode'].get(fun, 0) and fun in SUB_EVENT: # Minion fired a bad retcode, fire an event self._fire_ret_load_specific_fun(load, fun_index) else: # Single-function job if load['fun'] in SUB_EVENT: # Minion fired a bad retcode, fire an event self._fire_ret_load_specific_fun(load)
python
def fire_ret_load(self, load): ''' Fire events based on information in the return load ''' if load.get('retcode') and load.get('fun'): if isinstance(load['fun'], list): # Multi-function job if isinstance(load['retcode'], list): multifunc_ordered = True else: multifunc_ordered = False for fun_index in range(0, len(load['fun'])): fun = load['fun'][fun_index] if multifunc_ordered: if (len(load['retcode']) > fun_index and load['retcode'][fun_index] and fun in SUB_EVENT): # Minion fired a bad retcode, fire an event self._fire_ret_load_specific_fun(load, fun_index) else: if load['retcode'].get(fun, 0) and fun in SUB_EVENT: # Minion fired a bad retcode, fire an event self._fire_ret_load_specific_fun(load, fun_index) else: # Single-function job if load['fun'] in SUB_EVENT: # Minion fired a bad retcode, fire an event self._fire_ret_load_specific_fun(load)
[ "def", "fire_ret_load", "(", "self", ",", "load", ")", ":", "if", "load", ".", "get", "(", "'retcode'", ")", "and", "load", ".", "get", "(", "'fun'", ")", ":", "if", "isinstance", "(", "load", "[", "'fun'", "]", ",", "list", ")", ":", "# Multi-func...
Fire events based on information in the return load
[ "Fire", "events", "based", "on", "information", "in", "the", "return", "load" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/event.py#L846-L874
train
saltstack/salt
salt/utils/event.py
SaltEvent.set_event_handler
def set_event_handler(self, event_handler): ''' Invoke the event_handler callback each time an event arrives. ''' assert not self._run_io_loop_sync if not self.cpub: self.connect_pub() self.subscriber.callbacks.add(event_handler) if not self.subscriber.reading: # This will handle reconnects return self.subscriber.read_async()
python
def set_event_handler(self, event_handler): ''' Invoke the event_handler callback each time an event arrives. ''' assert not self._run_io_loop_sync if not self.cpub: self.connect_pub() self.subscriber.callbacks.add(event_handler) if not self.subscriber.reading: # This will handle reconnects return self.subscriber.read_async()
[ "def", "set_event_handler", "(", "self", ",", "event_handler", ")", ":", "assert", "not", "self", ".", "_run_io_loop_sync", "if", "not", "self", ".", "cpub", ":", "self", ".", "connect_pub", "(", ")", "self", ".", "subscriber", ".", "callbacks", ".", "add"...
Invoke the event_handler callback each time an event arrives.
[ "Invoke", "the", "event_handler", "callback", "each", "time", "an", "event", "arrives", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/event.py#L880-L892
train
saltstack/salt
salt/utils/event.py
EventPublisher.run
def run(self): ''' Bind the pub and pull sockets for events ''' salt.utils.process.appendproctitle(self.__class__.__name__) self.io_loop = tornado.ioloop.IOLoop() with salt.utils.asynchronous.current_ioloop(self.io_loop): if self.opts['ipc_mode'] == 'tcp': epub_uri = int(self.opts['tcp_master_pub_port']) epull_uri = int(self.opts['tcp_master_pull_port']) else: epub_uri = os.path.join( self.opts['sock_dir'], 'master_event_pub.ipc' ) epull_uri = os.path.join( self.opts['sock_dir'], 'master_event_pull.ipc' ) self.publisher = salt.transport.ipc.IPCMessagePublisher( self.opts, epub_uri, io_loop=self.io_loop ) self.puller = salt.transport.ipc.IPCMessageServer( self.opts, epull_uri, io_loop=self.io_loop, payload_handler=self.handle_publish, ) # Start the master event publisher with salt.utils.files.set_umask(0o177): self.publisher.start() self.puller.start() if (self.opts['ipc_mode'] != 'tcp' and ( self.opts['publisher_acl'] or self.opts['external_auth'])): os.chmod(os.path.join( self.opts['sock_dir'], 'master_event_pub.ipc'), 0o666) # Make sure the IO loop and respective sockets are closed and # destroyed Finalize(self, self.close, exitpriority=15) self.io_loop.start()
python
def run(self): ''' Bind the pub and pull sockets for events ''' salt.utils.process.appendproctitle(self.__class__.__name__) self.io_loop = tornado.ioloop.IOLoop() with salt.utils.asynchronous.current_ioloop(self.io_loop): if self.opts['ipc_mode'] == 'tcp': epub_uri = int(self.opts['tcp_master_pub_port']) epull_uri = int(self.opts['tcp_master_pull_port']) else: epub_uri = os.path.join( self.opts['sock_dir'], 'master_event_pub.ipc' ) epull_uri = os.path.join( self.opts['sock_dir'], 'master_event_pull.ipc' ) self.publisher = salt.transport.ipc.IPCMessagePublisher( self.opts, epub_uri, io_loop=self.io_loop ) self.puller = salt.transport.ipc.IPCMessageServer( self.opts, epull_uri, io_loop=self.io_loop, payload_handler=self.handle_publish, ) # Start the master event publisher with salt.utils.files.set_umask(0o177): self.publisher.start() self.puller.start() if (self.opts['ipc_mode'] != 'tcp' and ( self.opts['publisher_acl'] or self.opts['external_auth'])): os.chmod(os.path.join( self.opts['sock_dir'], 'master_event_pub.ipc'), 0o666) # Make sure the IO loop and respective sockets are closed and # destroyed Finalize(self, self.close, exitpriority=15) self.io_loop.start()
[ "def", "run", "(", "self", ")", ":", "salt", ".", "utils", ".", "process", ".", "appendproctitle", "(", "self", ".", "__class__", ".", "__name__", ")", "self", ".", "io_loop", "=", "tornado", ".", "ioloop", ".", "IOLoop", "(", ")", "with", "salt", "....
Bind the pub and pull sockets for events
[ "Bind", "the", "pub", "and", "pull", "sockets", "for", "events" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/event.py#L1100-L1147
train
saltstack/salt
salt/utils/event.py
EventPublisher.handle_publish
def handle_publish(self, package, _): ''' Get something from epull, publish it out epub, and return the package (or None) ''' try: self.publisher.publish(package) return package # Add an extra fallback in case a forked process leeks through except Exception: log.critical('Unexpected error while polling master events', exc_info=True) return None
python
def handle_publish(self, package, _): ''' Get something from epull, publish it out epub, and return the package (or None) ''' try: self.publisher.publish(package) return package # Add an extra fallback in case a forked process leeks through except Exception: log.critical('Unexpected error while polling master events', exc_info=True) return None
[ "def", "handle_publish", "(", "self", ",", "package", ",", "_", ")", ":", "try", ":", "self", ".", "publisher", ".", "publish", "(", "package", ")", "return", "package", "# Add an extra fallback in case a forked process leeks through", "except", "Exception", ":", ...
Get something from epull, publish it out epub, and return the package (or None)
[ "Get", "something", "from", "epull", "publish", "it", "out", "epub", "and", "return", "the", "package", "(", "or", "None", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/event.py#L1149-L1160
train
saltstack/salt
salt/utils/event.py
EventReturn.run
def run(self): ''' Spin up the multiprocess event returner ''' salt.utils.process.appendproctitle(self.__class__.__name__) self.event = get_event('master', opts=self.opts, listen=True) events = self.event.iter_events(full=True) self.event.fire_event({}, 'salt/event_listen/start') try: for event in events: if event['tag'] == 'salt/event/exit': self.stop = True if self._filter(event): self.event_queue.append(event) if len(self.event_queue) >= self.event_return_queue: self.flush_events() if self.stop: break finally: # flush all we have at this moment if self.event_queue: self.flush_events()
python
def run(self): ''' Spin up the multiprocess event returner ''' salt.utils.process.appendproctitle(self.__class__.__name__) self.event = get_event('master', opts=self.opts, listen=True) events = self.event.iter_events(full=True) self.event.fire_event({}, 'salt/event_listen/start') try: for event in events: if event['tag'] == 'salt/event/exit': self.stop = True if self._filter(event): self.event_queue.append(event) if len(self.event_queue) >= self.event_return_queue: self.flush_events() if self.stop: break finally: # flush all we have at this moment if self.event_queue: self.flush_events()
[ "def", "run", "(", "self", ")", ":", "salt", ".", "utils", ".", "process", ".", "appendproctitle", "(", "self", ".", "__class__", ".", "__name__", ")", "self", ".", "event", "=", "get_event", "(", "'master'", ",", "opts", "=", "self", ".", "opts", ",...
Spin up the multiprocess event returner
[ "Spin", "up", "the", "multiprocess", "event", "returner" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/event.py#L1270-L1290
train
saltstack/salt
salt/utils/event.py
EventReturn._filter
def _filter(self, event): ''' Take an event and run it through configured filters. Returns True if event should be stored, else False ''' tag = event['tag'] if self.opts['event_return_whitelist']: ret = False else: ret = True for whitelist_match in self.opts['event_return_whitelist']: if fnmatch.fnmatch(tag, whitelist_match): ret = True break for blacklist_match in self.opts['event_return_blacklist']: if fnmatch.fnmatch(tag, blacklist_match): ret = False break return ret
python
def _filter(self, event): ''' Take an event and run it through configured filters. Returns True if event should be stored, else False ''' tag = event['tag'] if self.opts['event_return_whitelist']: ret = False else: ret = True for whitelist_match in self.opts['event_return_whitelist']: if fnmatch.fnmatch(tag, whitelist_match): ret = True break for blacklist_match in self.opts['event_return_blacklist']: if fnmatch.fnmatch(tag, blacklist_match): ret = False break return ret
[ "def", "_filter", "(", "self", ",", "event", ")", ":", "tag", "=", "event", "[", "'tag'", "]", "if", "self", ".", "opts", "[", "'event_return_whitelist'", "]", ":", "ret", "=", "False", "else", ":", "ret", "=", "True", "for", "whitelist_match", "in", ...
Take an event and run it through configured filters. Returns True if event should be stored, else False
[ "Take", "an", "event", "and", "run", "it", "through", "configured", "filters", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/event.py#L1292-L1311
train
saltstack/salt
salt/utils/event.py
StateFire.fire_master
def fire_master(self, data, tag, preload=None): ''' Fire an event off on the master server CLI Example: .. code-block:: bash salt '*' event.fire_master 'stuff to be in the event' 'tag' ''' load = {} if preload: load.update(preload) load.update({ 'id': self.opts['id'], 'tag': tag, 'data': data, 'cmd': '_minion_event', 'tok': self.auth.gen_token(b'salt'), }) channel = salt.transport.client.ReqChannel.factory(self.opts) try: channel.send(load) except Exception: pass finally: channel.close() return True
python
def fire_master(self, data, tag, preload=None): ''' Fire an event off on the master server CLI Example: .. code-block:: bash salt '*' event.fire_master 'stuff to be in the event' 'tag' ''' load = {} if preload: load.update(preload) load.update({ 'id': self.opts['id'], 'tag': tag, 'data': data, 'cmd': '_minion_event', 'tok': self.auth.gen_token(b'salt'), }) channel = salt.transport.client.ReqChannel.factory(self.opts) try: channel.send(load) except Exception: pass finally: channel.close() return True
[ "def", "fire_master", "(", "self", ",", "data", ",", "tag", ",", "preload", "=", "None", ")", ":", "load", "=", "{", "}", "if", "preload", ":", "load", ".", "update", "(", "preload", ")", "load", ".", "update", "(", "{", "'id'", ":", "self", ".",...
Fire an event off on the master server CLI Example: .. code-block:: bash salt '*' event.fire_master 'stuff to be in the event' 'tag'
[ "Fire", "an", "event", "off", "on", "the", "master", "server" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/event.py#L1327-L1356
train
saltstack/salt
salt/utils/event.py
StateFire.fire_running
def fire_running(self, running): ''' Pass in a state "running" dict, this is the return dict from a state call. The dict will be processed and fire events. By default yellows and reds fire events on the master and minion, but this can be configured. ''' load = {'id': self.opts['id'], 'events': [], 'cmd': '_minion_event'} for stag in sorted( running, key=lambda k: running[k].get('__run_num__', 0)): if running[stag]['result'] and not running[stag]['changes']: continue tag = 'state_{0}_{1}'.format( six.text_type(running[stag]['result']), 'True' if running[stag]['changes'] else 'False') load['events'].append({ 'tag': tag, 'data': running[stag], }) channel = salt.transport.client.ReqChannel.factory(self.opts) try: channel.send(load) except Exception: pass finally: channel.close() return True
python
def fire_running(self, running): ''' Pass in a state "running" dict, this is the return dict from a state call. The dict will be processed and fire events. By default yellows and reds fire events on the master and minion, but this can be configured. ''' load = {'id': self.opts['id'], 'events': [], 'cmd': '_minion_event'} for stag in sorted( running, key=lambda k: running[k].get('__run_num__', 0)): if running[stag]['result'] and not running[stag]['changes']: continue tag = 'state_{0}_{1}'.format( six.text_type(running[stag]['result']), 'True' if running[stag]['changes'] else 'False') load['events'].append({ 'tag': tag, 'data': running[stag], }) channel = salt.transport.client.ReqChannel.factory(self.opts) try: channel.send(load) except Exception: pass finally: channel.close() return True
[ "def", "fire_running", "(", "self", ",", "running", ")", ":", "load", "=", "{", "'id'", ":", "self", ".", "opts", "[", "'id'", "]", ",", "'events'", ":", "[", "]", ",", "'cmd'", ":", "'_minion_event'", "}", "for", "stag", "in", "sorted", "(", "runn...
Pass in a state "running" dict, this is the return dict from a state call. The dict will be processed and fire events. By default yellows and reds fire events on the master and minion, but this can be configured.
[ "Pass", "in", "a", "state", "running", "dict", "this", "is", "the", "return", "dict", "from", "a", "state", "call", ".", "The", "dict", "will", "be", "processed", "and", "fire", "events", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/event.py#L1358-L1388
train
saltstack/salt
salt/modules/inspectlib/kiwiproc.py
KiwiExporter.load
def load(self, **descr): ''' Load data by keys. :param data: :return: ''' for obj, data in descr.items(): setattr(self._data, obj, data) return self
python
def load(self, **descr): ''' Load data by keys. :param data: :return: ''' for obj, data in descr.items(): setattr(self._data, obj, data) return self
[ "def", "load", "(", "self", ",", "*", "*", "descr", ")", ":", "for", "obj", ",", "data", "in", "descr", ".", "items", "(", ")", ":", "setattr", "(", "self", ".", "_data", ",", "obj", ",", "data", ")", "return", "self" ]
Load data by keys. :param data: :return:
[ "Load", "data", "by", "keys", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/inspectlib/kiwiproc.py#L50-L60
train
saltstack/salt
salt/modules/inspectlib/kiwiproc.py
KiwiExporter.export
def export(self, name): ''' Export to the Kiwi config.xml as text. :return: ''' self.name = name root = self._create_doc() self._set_description(root) self._set_preferences(root) self._set_repositories(root) self._set_users(root) self._set_packages(root) return '\n'.join([line for line in minidom.parseString( etree.tostring(root, encoding='UTF-8', pretty_print=True)).toprettyxml(indent=" ").split("\n") if line.strip()])
python
def export(self, name): ''' Export to the Kiwi config.xml as text. :return: ''' self.name = name root = self._create_doc() self._set_description(root) self._set_preferences(root) self._set_repositories(root) self._set_users(root) self._set_packages(root) return '\n'.join([line for line in minidom.parseString( etree.tostring(root, encoding='UTF-8', pretty_print=True)).toprettyxml(indent=" ").split("\n") if line.strip()])
[ "def", "export", "(", "self", ",", "name", ")", ":", "self", ".", "name", "=", "name", "root", "=", "self", ".", "_create_doc", "(", ")", "self", ".", "_set_description", "(", "root", ")", "self", ".", "_set_preferences", "(", "root", ")", "self", "....
Export to the Kiwi config.xml as text. :return:
[ "Export", "to", "the", "Kiwi", "config", ".", "xml", "as", "text", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/inspectlib/kiwiproc.py#L62-L79
train
saltstack/salt
salt/modules/inspectlib/kiwiproc.py
KiwiExporter._get_package_manager
def _get_package_manager(self): ''' Get package manager. :return: ''' ret = None if self.__grains__.get('os_family') in ('Kali', 'Debian'): ret = 'apt-get' elif self.__grains__.get('os_family', '') == 'Suse': ret = 'zypper' elif self.__grains__.get('os_family', '') == 'redhat': ret = 'yum' if ret is None: raise InspectorKiwiProcessorException('Unsupported platform: {0}'.format(self.__grains__.get('os_family'))) return ret
python
def _get_package_manager(self): ''' Get package manager. :return: ''' ret = None if self.__grains__.get('os_family') in ('Kali', 'Debian'): ret = 'apt-get' elif self.__grains__.get('os_family', '') == 'Suse': ret = 'zypper' elif self.__grains__.get('os_family', '') == 'redhat': ret = 'yum' if ret is None: raise InspectorKiwiProcessorException('Unsupported platform: {0}'.format(self.__grains__.get('os_family'))) return ret
[ "def", "_get_package_manager", "(", "self", ")", ":", "ret", "=", "None", "if", "self", ".", "__grains__", ".", "get", "(", "'os_family'", ")", "in", "(", "'Kali'", ",", "'Debian'", ")", ":", "ret", "=", "'apt-get'", "elif", "self", ".", "__grains__", ...
Get package manager. :return:
[ "Get", "package", "manager", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/inspectlib/kiwiproc.py#L81-L98
train
saltstack/salt
salt/modules/inspectlib/kiwiproc.py
KiwiExporter._set_preferences
def _set_preferences(self, node): ''' Set preferences. :return: ''' pref = etree.SubElement(node, 'preferences') pacman = etree.SubElement(pref, 'packagemanager') pacman.text = self._get_package_manager() p_version = etree.SubElement(pref, 'version') p_version.text = '0.0.1' p_type = etree.SubElement(pref, 'type') p_type.set('image', 'vmx') for disk_id, disk_data in self._data.system.get('disks', {}).items(): if disk_id.startswith('/dev'): p_type.set('filesystem', disk_data.get('type') or 'ext3') break p_type.set('installiso', 'true') p_type.set('boot', "vmxboot/suse-leap42.1") p_type.set('format', self.format) p_type.set('bootloader', 'grub2') p_type.set('timezone', __salt__['timezone.get_zone']()) p_type.set('hwclock', __salt__['timezone.get_hwclock']()) return pref
python
def _set_preferences(self, node): ''' Set preferences. :return: ''' pref = etree.SubElement(node, 'preferences') pacman = etree.SubElement(pref, 'packagemanager') pacman.text = self._get_package_manager() p_version = etree.SubElement(pref, 'version') p_version.text = '0.0.1' p_type = etree.SubElement(pref, 'type') p_type.set('image', 'vmx') for disk_id, disk_data in self._data.system.get('disks', {}).items(): if disk_id.startswith('/dev'): p_type.set('filesystem', disk_data.get('type') or 'ext3') break p_type.set('installiso', 'true') p_type.set('boot', "vmxboot/suse-leap42.1") p_type.set('format', self.format) p_type.set('bootloader', 'grub2') p_type.set('timezone', __salt__['timezone.get_zone']()) p_type.set('hwclock', __salt__['timezone.get_hwclock']()) return pref
[ "def", "_set_preferences", "(", "self", ",", "node", ")", ":", "pref", "=", "etree", ".", "SubElement", "(", "node", ",", "'preferences'", ")", "pacman", "=", "etree", ".", "SubElement", "(", "pref", ",", "'packagemanager'", ")", "pacman", ".", "text", "...
Set preferences. :return:
[ "Set", "preferences", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/inspectlib/kiwiproc.py#L100-L126
train
saltstack/salt
salt/modules/inspectlib/kiwiproc.py
KiwiExporter._get_user_groups
def _get_user_groups(self, user): ''' Get user groups. :param user: :return: ''' return [g.gr_name for g in grp.getgrall() if user in g.gr_mem] + [grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name]
python
def _get_user_groups(self, user): ''' Get user groups. :param user: :return: ''' return [g.gr_name for g in grp.getgrall() if user in g.gr_mem] + [grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name]
[ "def", "_get_user_groups", "(", "self", ",", "user", ")", ":", "return", "[", "g", ".", "gr_name", "for", "g", "in", "grp", ".", "getgrall", "(", ")", "if", "user", "in", "g", ".", "gr_mem", "]", "+", "[", "grp", ".", "getgrgid", "(", "pwd", ".",...
Get user groups. :param user: :return:
[ "Get", "user", "groups", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/inspectlib/kiwiproc.py#L128-L136
train
saltstack/salt
salt/modules/inspectlib/kiwiproc.py
KiwiExporter._set_users
def _set_users(self, node): ''' Create existing local users. <users group="root"> <user password="$1$wYJUgpM5$RXMMeASDc035eX.NbYWFl0" home="/root" name="root"/> </users> :param node: :return: ''' # Get real local users with the local passwords shadow = {} with salt.utils.files.fopen('/etc/shadow') as rfh: for sh_line in rfh.read().split(os.linesep): if sh_line.strip(): login, pwd = sh_line.split(":")[:2] if pwd and pwd[0] not in '!*': shadow[login] = {'p': pwd} with salt.utils.files.fopen('/etc/passwd') as rfh: for ps_line in rfh.read().split(os.linesep): if ps_line.strip(): ps_line = ps_line.strip().split(':') if ps_line[0] in shadow: shadow[ps_line[0]]['h'] = ps_line[5] shadow[ps_line[0]]['s'] = ps_line[6] shadow[ps_line[0]]['g'] = self._get_user_groups(ps_line[0]) users_groups = [] users_node = etree.SubElement(node, 'users') for u_name, u_data in shadow.items(): user_node = etree.SubElement(users_node, 'user') user_node.set('password', u_data['p']) user_node.set('home', u_data['h']) user_node.set('name', u_name) users_groups.extend(u_data['g']) users_node.set('group', ','.join(users_groups)) return users_node
python
def _set_users(self, node): ''' Create existing local users. <users group="root"> <user password="$1$wYJUgpM5$RXMMeASDc035eX.NbYWFl0" home="/root" name="root"/> </users> :param node: :return: ''' # Get real local users with the local passwords shadow = {} with salt.utils.files.fopen('/etc/shadow') as rfh: for sh_line in rfh.read().split(os.linesep): if sh_line.strip(): login, pwd = sh_line.split(":")[:2] if pwd and pwd[0] not in '!*': shadow[login] = {'p': pwd} with salt.utils.files.fopen('/etc/passwd') as rfh: for ps_line in rfh.read().split(os.linesep): if ps_line.strip(): ps_line = ps_line.strip().split(':') if ps_line[0] in shadow: shadow[ps_line[0]]['h'] = ps_line[5] shadow[ps_line[0]]['s'] = ps_line[6] shadow[ps_line[0]]['g'] = self._get_user_groups(ps_line[0]) users_groups = [] users_node = etree.SubElement(node, 'users') for u_name, u_data in shadow.items(): user_node = etree.SubElement(users_node, 'user') user_node.set('password', u_data['p']) user_node.set('home', u_data['h']) user_node.set('name', u_name) users_groups.extend(u_data['g']) users_node.set('group', ','.join(users_groups)) return users_node
[ "def", "_set_users", "(", "self", ",", "node", ")", ":", "# Get real local users with the local passwords", "shadow", "=", "{", "}", "with", "salt", ".", "utils", ".", "files", ".", "fopen", "(", "'/etc/shadow'", ")", "as", "rfh", ":", "for", "sh_line", "in"...
Create existing local users. <users group="root"> <user password="$1$wYJUgpM5$RXMMeASDc035eX.NbYWFl0" home="/root" name="root"/> </users> :param node: :return:
[ "Create", "existing", "local", "users", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/inspectlib/kiwiproc.py#L138-L177
train
saltstack/salt
salt/modules/inspectlib/kiwiproc.py
KiwiExporter._set_repositories
def _set_repositories(self, node): ''' Create repositories. :param node: :return: ''' priority = 99 for repo_id, repo_data in self._data.software.get('repositories', {}).items(): if type(repo_data) == list: repo_data = repo_data[0] if repo_data.get('enabled') or not repo_data.get('disabled'): # RPM and Debian, respectively uri = repo_data.get('baseurl', repo_data.get('uri')) if not uri: continue repo = etree.SubElement(node, 'repository') if self.__grains__.get('os_family') in ('Kali', 'Debian'): repo.set('alias', repo_id) repo.set('distribution', repo_data['dist']) else: repo.set('alias', repo_data['alias']) if self.__grains__.get('os_family', '') == 'Suse': repo.set('type', 'yast2') # TODO: Check for options! repo.set('priority', str(priority)) source = etree.SubElement(repo, 'source') source.set('path', uri) # RPM and Debian, respectively priority -= 1
python
def _set_repositories(self, node): ''' Create repositories. :param node: :return: ''' priority = 99 for repo_id, repo_data in self._data.software.get('repositories', {}).items(): if type(repo_data) == list: repo_data = repo_data[0] if repo_data.get('enabled') or not repo_data.get('disabled'): # RPM and Debian, respectively uri = repo_data.get('baseurl', repo_data.get('uri')) if not uri: continue repo = etree.SubElement(node, 'repository') if self.__grains__.get('os_family') in ('Kali', 'Debian'): repo.set('alias', repo_id) repo.set('distribution', repo_data['dist']) else: repo.set('alias', repo_data['alias']) if self.__grains__.get('os_family', '') == 'Suse': repo.set('type', 'yast2') # TODO: Check for options! repo.set('priority', str(priority)) source = etree.SubElement(repo, 'source') source.set('path', uri) # RPM and Debian, respectively priority -= 1
[ "def", "_set_repositories", "(", "self", ",", "node", ")", ":", "priority", "=", "99", "for", "repo_id", ",", "repo_data", "in", "self", ".", "_data", ".", "software", ".", "get", "(", "'repositories'", ",", "{", "}", ")", ".", "items", "(", ")", ":"...
Create repositories. :param node: :return:
[ "Create", "repositories", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/inspectlib/kiwiproc.py#L179-L206
train
saltstack/salt
salt/modules/inspectlib/kiwiproc.py
KiwiExporter._set_packages
def _set_packages(self, node): ''' Set packages and collections. :param node: :return: ''' pkgs = etree.SubElement(node, 'packages') for pkg_name, pkg_version in sorted(self._data.software.get('packages', {}).items()): pkg = etree.SubElement(pkgs, 'package') pkg.set('name', pkg_name) # Add collections (SUSE) if self.__grains__.get('os_family', '') == 'Suse': for ptn_id, ptn_data in self._data.software.get('patterns', {}).items(): if ptn_data.get('installed'): ptn = etree.SubElement(pkgs, 'namedCollection') ptn.set('name', ptn_id) return pkgs
python
def _set_packages(self, node): ''' Set packages and collections. :param node: :return: ''' pkgs = etree.SubElement(node, 'packages') for pkg_name, pkg_version in sorted(self._data.software.get('packages', {}).items()): pkg = etree.SubElement(pkgs, 'package') pkg.set('name', pkg_name) # Add collections (SUSE) if self.__grains__.get('os_family', '') == 'Suse': for ptn_id, ptn_data in self._data.software.get('patterns', {}).items(): if ptn_data.get('installed'): ptn = etree.SubElement(pkgs, 'namedCollection') ptn.set('name', ptn_id) return pkgs
[ "def", "_set_packages", "(", "self", ",", "node", ")", ":", "pkgs", "=", "etree", ".", "SubElement", "(", "node", ",", "'packages'", ")", "for", "pkg_name", ",", "pkg_version", "in", "sorted", "(", "self", ".", "_data", ".", "software", ".", "get", "("...
Set packages and collections. :param node: :return:
[ "Set", "packages", "and", "collections", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/inspectlib/kiwiproc.py#L208-L227
train
saltstack/salt
salt/modules/inspectlib/kiwiproc.py
KiwiExporter._set_description
def _set_description(self, node): ''' Create a system description. :return: ''' hostname = socket.getfqdn() or platform.node() descr = etree.SubElement(node, 'description') author = etree.SubElement(descr, 'author') author.text = "salt.modules.node on {0}".format(hostname) contact = etree.SubElement(descr, 'contact') contact.text = 'root@{0}'.format(hostname) specs = etree.SubElement(descr, 'specification') specs.text = 'Rebuild of {0}, based on Salt inspection.'.format(hostname) return descr
python
def _set_description(self, node): ''' Create a system description. :return: ''' hostname = socket.getfqdn() or platform.node() descr = etree.SubElement(node, 'description') author = etree.SubElement(descr, 'author') author.text = "salt.modules.node on {0}".format(hostname) contact = etree.SubElement(descr, 'contact') contact.text = 'root@{0}'.format(hostname) specs = etree.SubElement(descr, 'specification') specs.text = 'Rebuild of {0}, based on Salt inspection.'.format(hostname) return descr
[ "def", "_set_description", "(", "self", ",", "node", ")", ":", "hostname", "=", "socket", ".", "getfqdn", "(", ")", "or", "platform", ".", "node", "(", ")", "descr", "=", "etree", ".", "SubElement", "(", "node", ",", "'description'", ")", "author", "="...
Create a system description. :return:
[ "Create", "a", "system", "description", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/inspectlib/kiwiproc.py#L229-L245
train
saltstack/salt
salt/modules/inspectlib/kiwiproc.py
KiwiExporter._create_doc
def _create_doc(self): ''' Create document. :return: ''' root = etree.Element('image') root.set('schemaversion', '6.3') root.set('name', self.name) return root
python
def _create_doc(self): ''' Create document. :return: ''' root = etree.Element('image') root.set('schemaversion', '6.3') root.set('name', self.name) return root
[ "def", "_create_doc", "(", "self", ")", ":", "root", "=", "etree", ".", "Element", "(", "'image'", ")", "root", ".", "set", "(", "'schemaversion'", ",", "'6.3'", ")", "root", ".", "set", "(", "'name'", ",", "self", ".", "name", ")", "return", "root" ...
Create document. :return:
[ "Create", "document", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/inspectlib/kiwiproc.py#L247-L257
train
saltstack/salt
salt/sdb/vault.py
set_
def set_(key, value, profile=None): ''' Set a key/value pair in the vault service ''' if '?' in key: __utils__['versions.warn_until']( 'Neon', ( 'Using ? to seperate between the path and key for vault has been deprecated ' 'and will be removed in {version}. Please just use a /.' ), ) path, key = key.split('?') else: path, key = key.rsplit('/', 1) try: url = 'v1/{0}'.format(path) data = {key: value} response = __utils__['vault.make_request']( 'POST', url, profile, json=data) if response.status_code != 204: response.raise_for_status() return True except Exception as e: log.error('Failed to write secret! %s: %s', type(e).__name__, e) raise salt.exceptions.CommandExecutionError(e)
python
def set_(key, value, profile=None): ''' Set a key/value pair in the vault service ''' if '?' in key: __utils__['versions.warn_until']( 'Neon', ( 'Using ? to seperate between the path and key for vault has been deprecated ' 'and will be removed in {version}. Please just use a /.' ), ) path, key = key.split('?') else: path, key = key.rsplit('/', 1) try: url = 'v1/{0}'.format(path) data = {key: value} response = __utils__['vault.make_request']( 'POST', url, profile, json=data) if response.status_code != 204: response.raise_for_status() return True except Exception as e: log.error('Failed to write secret! %s: %s', type(e).__name__, e) raise salt.exceptions.CommandExecutionError(e)
[ "def", "set_", "(", "key", ",", "value", ",", "profile", "=", "None", ")", ":", "if", "'?'", "in", "key", ":", "__utils__", "[", "'versions.warn_until'", "]", "(", "'Neon'", ",", "(", "'Using ? to seperate between the path and key for vault has been deprecated '", ...
Set a key/value pair in the vault service
[ "Set", "a", "key", "/", "value", "pair", "in", "the", "vault", "service" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/sdb/vault.py#L55-L85
train
saltstack/salt
salt/thorium/timer.py
hold
def hold(name, seconds): ''' Wait for a given period of time, then fire a result of True, requiring this state allows for an action to be blocked for evaluation based on time USAGE: .. code-block:: yaml hold_on_a_moment: timer.hold: - seconds: 30 ''' ret = {'name': name, 'result': False, 'comment': '', 'changes': {}} start = time.time() if 'timer' not in __context__: __context__['timer'] = {} if name not in __context__['timer']: __context__['timer'][name] = start if (start - __context__['timer'][name]) > seconds: ret['result'] = True __context__['timer'][name] = start return ret
python
def hold(name, seconds): ''' Wait for a given period of time, then fire a result of True, requiring this state allows for an action to be blocked for evaluation based on time USAGE: .. code-block:: yaml hold_on_a_moment: timer.hold: - seconds: 30 ''' ret = {'name': name, 'result': False, 'comment': '', 'changes': {}} start = time.time() if 'timer' not in __context__: __context__['timer'] = {} if name not in __context__['timer']: __context__['timer'][name] = start if (start - __context__['timer'][name]) > seconds: ret['result'] = True __context__['timer'][name] = start return ret
[ "def", "hold", "(", "name", ",", "seconds", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "False", ",", "'comment'", ":", "''", ",", "'changes'", ":", "{", "}", "}", "start", "=", "time", ".", "time", "(", ")", "if", "...
Wait for a given period of time, then fire a result of True, requiring this state allows for an action to be blocked for evaluation based on time USAGE: .. code-block:: yaml hold_on_a_moment: timer.hold: - seconds: 30
[ "Wait", "for", "a", "given", "period", "of", "time", "then", "fire", "a", "result", "of", "True", "requiring", "this", "state", "allows", "for", "an", "action", "to", "be", "blocked", "for", "evaluation", "based", "on", "time" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/timer.py#L11-L37
train
saltstack/salt
salt/modules/mongodb.py
_connect
def _connect(user=None, password=None, host=None, port=None, database='admin', authdb=None): ''' Returns a tuple of (user, host, port) with config, pillar, or default values assigned to missing values. ''' if not user: user = __salt__['config.option']('mongodb.user') if not password: password = __salt__['config.option']('mongodb.password') if not host: host = __salt__['config.option']('mongodb.host') if not port: port = __salt__['config.option']('mongodb.port') if not authdb: authdb = database try: conn = pymongo.MongoClient(host=host, port=port) mdb = pymongo.database.Database(conn, database) if user and password: mdb.authenticate(user, password, source=authdb) except pymongo.errors.PyMongoError: log.error('Error connecting to database %s', database) return False return conn
python
def _connect(user=None, password=None, host=None, port=None, database='admin', authdb=None): ''' Returns a tuple of (user, host, port) with config, pillar, or default values assigned to missing values. ''' if not user: user = __salt__['config.option']('mongodb.user') if not password: password = __salt__['config.option']('mongodb.password') if not host: host = __salt__['config.option']('mongodb.host') if not port: port = __salt__['config.option']('mongodb.port') if not authdb: authdb = database try: conn = pymongo.MongoClient(host=host, port=port) mdb = pymongo.database.Database(conn, database) if user and password: mdb.authenticate(user, password, source=authdb) except pymongo.errors.PyMongoError: log.error('Error connecting to database %s', database) return False return conn
[ "def", "_connect", "(", "user", "=", "None", ",", "password", "=", "None", ",", "host", "=", "None", ",", "port", "=", "None", ",", "database", "=", "'admin'", ",", "authdb", "=", "None", ")", ":", "if", "not", "user", ":", "user", "=", "__salt__",...
Returns a tuple of (user, host, port) with config, pillar, or default values assigned to missing values.
[ "Returns", "a", "tuple", "of", "(", "user", "host", "port", ")", "with", "config", "pillar", "or", "default", "values", "assigned", "to", "missing", "values", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mongodb.py#L49-L74
train
saltstack/salt
salt/modules/mongodb.py
_to_dict
def _to_dict(objects): ''' Potentially interprets a string as JSON for usage with mongo ''' try: if isinstance(objects, six.string_types): objects = salt.utils.json.loads(objects) except ValueError as err: log.error("Could not parse objects: %s", err) raise err return objects
python
def _to_dict(objects): ''' Potentially interprets a string as JSON for usage with mongo ''' try: if isinstance(objects, six.string_types): objects = salt.utils.json.loads(objects) except ValueError as err: log.error("Could not parse objects: %s", err) raise err return objects
[ "def", "_to_dict", "(", "objects", ")", ":", "try", ":", "if", "isinstance", "(", "objects", ",", "six", ".", "string_types", ")", ":", "objects", "=", "salt", ".", "utils", ".", "json", ".", "loads", "(", "objects", ")", "except", "ValueError", "as", ...
Potentially interprets a string as JSON for usage with mongo
[ "Potentially", "interprets", "a", "string", "as", "JSON", "for", "usage", "with", "mongo" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mongodb.py#L77-L88
train
saltstack/salt
salt/modules/mongodb.py
db_list
def db_list(user=None, password=None, host=None, port=None, authdb=None): ''' List all MongoDB databases CLI Example: .. code-block:: bash salt '*' mongodb.db_list <user> <password> <host> <port> ''' conn = _connect(user, password, host, port, authdb=authdb) if not conn: return 'Failed to connect to mongo database' try: log.info('Listing databases') return conn.database_names() except pymongo.errors.PyMongoError as err: log.error(err) return six.text_type(err)
python
def db_list(user=None, password=None, host=None, port=None, authdb=None): ''' List all MongoDB databases CLI Example: .. code-block:: bash salt '*' mongodb.db_list <user> <password> <host> <port> ''' conn = _connect(user, password, host, port, authdb=authdb) if not conn: return 'Failed to connect to mongo database' try: log.info('Listing databases') return conn.database_names() except pymongo.errors.PyMongoError as err: log.error(err) return six.text_type(err)
[ "def", "db_list", "(", "user", "=", "None", ",", "password", "=", "None", ",", "host", "=", "None", ",", "port", "=", "None", ",", "authdb", "=", "None", ")", ":", "conn", "=", "_connect", "(", "user", ",", "password", ",", "host", ",", "port", "...
List all MongoDB databases CLI Example: .. code-block:: bash salt '*' mongodb.db_list <user> <password> <host> <port>
[ "List", "all", "MongoDB", "databases" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mongodb.py#L91-L110
train
saltstack/salt
salt/modules/mongodb.py
db_exists
def db_exists(name, user=None, password=None, host=None, port=None, authdb=None): ''' Checks if a database exists in MongoDB CLI Example: .. code-block:: bash salt '*' mongodb.db_exists <name> <user> <password> <host> <port> ''' dbs = db_list(user, password, host, port, authdb=authdb) if isinstance(dbs, six.string_types): return False return name in dbs
python
def db_exists(name, user=None, password=None, host=None, port=None, authdb=None): ''' Checks if a database exists in MongoDB CLI Example: .. code-block:: bash salt '*' mongodb.db_exists <name> <user> <password> <host> <port> ''' dbs = db_list(user, password, host, port, authdb=authdb) if isinstance(dbs, six.string_types): return False return name in dbs
[ "def", "db_exists", "(", "name", ",", "user", "=", "None", ",", "password", "=", "None", ",", "host", "=", "None", ",", "port", "=", "None", ",", "authdb", "=", "None", ")", ":", "dbs", "=", "db_list", "(", "user", ",", "password", ",", "host", "...
Checks if a database exists in MongoDB CLI Example: .. code-block:: bash salt '*' mongodb.db_exists <name> <user> <password> <host> <port>
[ "Checks", "if", "a", "database", "exists", "in", "MongoDB" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mongodb.py#L113-L128
train
saltstack/salt
salt/modules/mongodb.py
db_remove
def db_remove(name, user=None, password=None, host=None, port=None, authdb=None): ''' Remove a MongoDB database CLI Example: .. code-block:: bash salt '*' mongodb.db_remove <name> <user> <password> <host> <port> ''' conn = _connect(user, password, host, port, authdb=authdb) if not conn: return 'Failed to connect to mongo database' try: log.info('Removing database %s', name) conn.drop_database(name) except pymongo.errors.PyMongoError as err: log.error('Removing database %s failed with error: %s', name, err) return six.text_type(err) return True
python
def db_remove(name, user=None, password=None, host=None, port=None, authdb=None): ''' Remove a MongoDB database CLI Example: .. code-block:: bash salt '*' mongodb.db_remove <name> <user> <password> <host> <port> ''' conn = _connect(user, password, host, port, authdb=authdb) if not conn: return 'Failed to connect to mongo database' try: log.info('Removing database %s', name) conn.drop_database(name) except pymongo.errors.PyMongoError as err: log.error('Removing database %s failed with error: %s', name, err) return six.text_type(err) return True
[ "def", "db_remove", "(", "name", ",", "user", "=", "None", ",", "password", "=", "None", ",", "host", "=", "None", ",", "port", "=", "None", ",", "authdb", "=", "None", ")", ":", "conn", "=", "_connect", "(", "user", ",", "password", ",", "host", ...
Remove a MongoDB database CLI Example: .. code-block:: bash salt '*' mongodb.db_remove <name> <user> <password> <host> <port>
[ "Remove", "a", "MongoDB", "database" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mongodb.py#L131-L152
train
saltstack/salt
salt/modules/mongodb.py
version
def version(user=None, password=None, host=None, port=None, database='admin', authdb=None): ''' Get MongoDB instance version CLI Example: .. code-block:: bash salt '*' mongodb.version <user> <password> <host> <port> <database> ''' conn = _connect(user, password, host, port, authdb=authdb) if not conn: err_msg = "Failed to connect to MongoDB database {0}:{1}".format(host, port) log.error(err_msg) return (False, err_msg) try: mdb = pymongo.database.Database(conn, database) return _version(mdb) except pymongo.errors.PyMongoError as err: log.error('Listing users failed with error: %s', err) return six.text_type(err)
python
def version(user=None, password=None, host=None, port=None, database='admin', authdb=None): ''' Get MongoDB instance version CLI Example: .. code-block:: bash salt '*' mongodb.version <user> <password> <host> <port> <database> ''' conn = _connect(user, password, host, port, authdb=authdb) if not conn: err_msg = "Failed to connect to MongoDB database {0}:{1}".format(host, port) log.error(err_msg) return (False, err_msg) try: mdb = pymongo.database.Database(conn, database) return _version(mdb) except pymongo.errors.PyMongoError as err: log.error('Listing users failed with error: %s', err) return six.text_type(err)
[ "def", "version", "(", "user", "=", "None", ",", "password", "=", "None", ",", "host", "=", "None", ",", "port", "=", "None", ",", "database", "=", "'admin'", ",", "authdb", "=", "None", ")", ":", "conn", "=", "_connect", "(", "user", ",", "passwor...
Get MongoDB instance version CLI Example: .. code-block:: bash salt '*' mongodb.version <user> <password> <host> <port> <database>
[ "Get", "MongoDB", "instance", "version" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mongodb.py#L159-L180
train
saltstack/salt
salt/modules/mongodb.py
user_list
def user_list(user=None, password=None, host=None, port=None, database='admin', authdb=None): ''' List users of a MongoDB database CLI Example: .. code-block:: bash salt '*' mongodb.user_list <user> <password> <host> <port> <database> ''' conn = _connect(user, password, host, port, authdb=authdb) if not conn: return 'Failed to connect to mongo database' try: log.info('Listing users') mdb = pymongo.database.Database(conn, database) output = [] mongodb_version = _version(mdb) if _LooseVersion(mongodb_version) >= _LooseVersion('2.6'): for user in mdb.command('usersInfo')['users']: output.append( {'user': user['user'], 'roles': user['roles']} ) else: for user in mdb.system.users.find(): output.append( {'user': user['user'], 'readOnly': user.get('readOnly', 'None')} ) return output except pymongo.errors.PyMongoError as err: log.error('Listing users failed with error: %s', err) return six.text_type(err)
python
def user_list(user=None, password=None, host=None, port=None, database='admin', authdb=None): ''' List users of a MongoDB database CLI Example: .. code-block:: bash salt '*' mongodb.user_list <user> <password> <host> <port> <database> ''' conn = _connect(user, password, host, port, authdb=authdb) if not conn: return 'Failed to connect to mongo database' try: log.info('Listing users') mdb = pymongo.database.Database(conn, database) output = [] mongodb_version = _version(mdb) if _LooseVersion(mongodb_version) >= _LooseVersion('2.6'): for user in mdb.command('usersInfo')['users']: output.append( {'user': user['user'], 'roles': user['roles']} ) else: for user in mdb.system.users.find(): output.append( {'user': user['user'], 'readOnly': user.get('readOnly', 'None')} ) return output except pymongo.errors.PyMongoError as err: log.error('Listing users failed with error: %s', err) return six.text_type(err)
[ "def", "user_list", "(", "user", "=", "None", ",", "password", "=", "None", ",", "host", "=", "None", ",", "port", "=", "None", ",", "database", "=", "'admin'", ",", "authdb", "=", "None", ")", ":", "conn", "=", "_connect", "(", "user", ",", "passw...
List users of a MongoDB database CLI Example: .. code-block:: bash salt '*' mongodb.user_list <user> <password> <host> <port> <database>
[ "List", "users", "of", "a", "MongoDB", "database" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mongodb.py#L208-L245
train
saltstack/salt
salt/modules/mongodb.py
user_exists
def user_exists(name, user=None, password=None, host=None, port=None, database='admin', authdb=None): ''' Checks if a user exists in MongoDB CLI Example: .. code-block:: bash salt '*' mongodb.user_exists <name> <user> <password> <host> <port> <database> ''' users = user_list(user, password, host, port, database, authdb) if isinstance(users, six.string_types): return 'Failed to connect to mongo database' for user in users: if name == dict(user).get('user'): return True return False
python
def user_exists(name, user=None, password=None, host=None, port=None, database='admin', authdb=None): ''' Checks if a user exists in MongoDB CLI Example: .. code-block:: bash salt '*' mongodb.user_exists <name> <user> <password> <host> <port> <database> ''' users = user_list(user, password, host, port, database, authdb) if isinstance(users, six.string_types): return 'Failed to connect to mongo database' for user in users: if name == dict(user).get('user'): return True return False
[ "def", "user_exists", "(", "name", ",", "user", "=", "None", ",", "password", "=", "None", ",", "host", "=", "None", ",", "port", "=", "None", ",", "database", "=", "'admin'", ",", "authdb", "=", "None", ")", ":", "users", "=", "user_list", "(", "u...
Checks if a user exists in MongoDB CLI Example: .. code-block:: bash salt '*' mongodb.user_exists <name> <user> <password> <host> <port> <database>
[ "Checks", "if", "a", "user", "exists", "in", "MongoDB" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mongodb.py#L248-L268
train
saltstack/salt
salt/modules/mongodb.py
user_create
def user_create(name, passwd, user=None, password=None, host=None, port=None, database='admin', authdb=None, roles=None): ''' Create a MongoDB user CLI Example: .. code-block:: bash salt '*' mongodb.user_create <user_name> <user_password> <roles> <user> <password> <host> <port> <database> ''' conn = _connect(user, password, host, port, authdb=authdb) if not conn: return 'Failed to connect to mongo database' if not roles: roles = [] try: log.info('Creating user %s', name) mdb = pymongo.database.Database(conn, database) mdb.add_user(name, passwd, roles=roles) except pymongo.errors.PyMongoError as err: log.error('Creating database %s failed with error: %s', name, err) return six.text_type(err) return True
python
def user_create(name, passwd, user=None, password=None, host=None, port=None, database='admin', authdb=None, roles=None): ''' Create a MongoDB user CLI Example: .. code-block:: bash salt '*' mongodb.user_create <user_name> <user_password> <roles> <user> <password> <host> <port> <database> ''' conn = _connect(user, password, host, port, authdb=authdb) if not conn: return 'Failed to connect to mongo database' if not roles: roles = [] try: log.info('Creating user %s', name) mdb = pymongo.database.Database(conn, database) mdb.add_user(name, passwd, roles=roles) except pymongo.errors.PyMongoError as err: log.error('Creating database %s failed with error: %s', name, err) return six.text_type(err) return True
[ "def", "user_create", "(", "name", ",", "passwd", ",", "user", "=", "None", ",", "password", "=", "None", ",", "host", "=", "None", ",", "port", "=", "None", ",", "database", "=", "'admin'", ",", "authdb", "=", "None", ",", "roles", "=", "None", ")...
Create a MongoDB user CLI Example: .. code-block:: bash salt '*' mongodb.user_create <user_name> <user_password> <roles> <user> <password> <host> <port> <database>
[ "Create", "a", "MongoDB", "user" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mongodb.py#L271-L296
train
saltstack/salt
salt/modules/mongodb.py
user_remove
def user_remove(name, user=None, password=None, host=None, port=None, database='admin', authdb=None): ''' Remove a MongoDB user CLI Example: .. code-block:: bash salt '*' mongodb.user_remove <name> <user> <password> <host> <port> <database> ''' conn = _connect(user, password, host, port) if not conn: return 'Failed to connect to mongo database' try: log.info('Removing user %s', name) mdb = pymongo.database.Database(conn, database) mdb.remove_user(name) except pymongo.errors.PyMongoError as err: log.error('Creating database %s failed with error: %s', name, err) return six.text_type(err) return True
python
def user_remove(name, user=None, password=None, host=None, port=None, database='admin', authdb=None): ''' Remove a MongoDB user CLI Example: .. code-block:: bash salt '*' mongodb.user_remove <name> <user> <password> <host> <port> <database> ''' conn = _connect(user, password, host, port) if not conn: return 'Failed to connect to mongo database' try: log.info('Removing user %s', name) mdb = pymongo.database.Database(conn, database) mdb.remove_user(name) except pymongo.errors.PyMongoError as err: log.error('Creating database %s failed with error: %s', name, err) return six.text_type(err) return True
[ "def", "user_remove", "(", "name", ",", "user", "=", "None", ",", "password", "=", "None", ",", "host", "=", "None", ",", "port", "=", "None", ",", "database", "=", "'admin'", ",", "authdb", "=", "None", ")", ":", "conn", "=", "_connect", "(", "use...
Remove a MongoDB user CLI Example: .. code-block:: bash salt '*' mongodb.user_remove <name> <user> <password> <host> <port> <database>
[ "Remove", "a", "MongoDB", "user" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mongodb.py#L299-L322
train
saltstack/salt
salt/modules/mongodb.py
user_roles_exists
def user_roles_exists(name, roles, database, user=None, password=None, host=None, port=None, authdb=None): ''' Checks if a user of a MongoDB database has specified roles CLI Examples: .. code-block:: bash salt '*' mongodb.user_roles_exists johndoe '["readWrite"]' dbname admin adminpwd localhost 27017 .. code-block:: bash salt '*' mongodb.user_roles_exists johndoe '[{"role": "readWrite", "db": "dbname" }, {"role": "read", "db": "otherdb"}]' dbname admin adminpwd localhost 27017 ''' try: roles = _to_dict(roles) except Exception: return 'Roles provided in wrong format' users = user_list(user, password, host, port, database, authdb) if isinstance(users, six.string_types): return 'Failed to connect to mongo database' for user in users: if name == dict(user).get('user'): for role in roles: # if the role was provided in the shortened form, we convert it to a long form if not isinstance(role, dict): role = {'role': role, 'db': database} if role not in dict(user).get('roles', []): return False return True return False
python
def user_roles_exists(name, roles, database, user=None, password=None, host=None, port=None, authdb=None): ''' Checks if a user of a MongoDB database has specified roles CLI Examples: .. code-block:: bash salt '*' mongodb.user_roles_exists johndoe '["readWrite"]' dbname admin adminpwd localhost 27017 .. code-block:: bash salt '*' mongodb.user_roles_exists johndoe '[{"role": "readWrite", "db": "dbname" }, {"role": "read", "db": "otherdb"}]' dbname admin adminpwd localhost 27017 ''' try: roles = _to_dict(roles) except Exception: return 'Roles provided in wrong format' users = user_list(user, password, host, port, database, authdb) if isinstance(users, six.string_types): return 'Failed to connect to mongo database' for user in users: if name == dict(user).get('user'): for role in roles: # if the role was provided in the shortened form, we convert it to a long form if not isinstance(role, dict): role = {'role': role, 'db': database} if role not in dict(user).get('roles', []): return False return True return False
[ "def", "user_roles_exists", "(", "name", ",", "roles", ",", "database", ",", "user", "=", "None", ",", "password", "=", "None", ",", "host", "=", "None", ",", "port", "=", "None", ",", "authdb", "=", "None", ")", ":", "try", ":", "roles", "=", "_to...
Checks if a user of a MongoDB database has specified roles CLI Examples: .. code-block:: bash salt '*' mongodb.user_roles_exists johndoe '["readWrite"]' dbname admin adminpwd localhost 27017 .. code-block:: bash salt '*' mongodb.user_roles_exists johndoe '[{"role": "readWrite", "db": "dbname" }, {"role": "read", "db": "otherdb"}]' dbname admin adminpwd localhost 27017
[ "Checks", "if", "a", "user", "of", "a", "MongoDB", "database", "has", "specified", "roles" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mongodb.py#L325-L360
train
saltstack/salt
salt/modules/mongodb.py
user_grant_roles
def user_grant_roles(name, roles, database, user=None, password=None, host=None, port=None, authdb=None): ''' Grant one or many roles to a MongoDB user CLI Examples: .. code-block:: bash salt '*' mongodb.user_grant_roles johndoe '["readWrite"]' dbname admin adminpwd localhost 27017 .. code-block:: bash salt '*' mongodb.user_grant_roles janedoe '[{"role": "readWrite", "db": "dbname" }, {"role": "read", "db": "otherdb"}]' dbname admin adminpwd localhost 27017 ''' conn = _connect(user, password, host, port, authdb=authdb) if not conn: return 'Failed to connect to mongo database' try: roles = _to_dict(roles) except Exception: return 'Roles provided in wrong format' try: log.info('Granting roles %s to user %s', roles, name) mdb = pymongo.database.Database(conn, database) mdb.command("grantRolesToUser", name, roles=roles) except pymongo.errors.PyMongoError as err: log.error('Granting roles %s to user %s failed with error: %s', roles, name, err) return six.text_type(err) return True
python
def user_grant_roles(name, roles, database, user=None, password=None, host=None, port=None, authdb=None): ''' Grant one or many roles to a MongoDB user CLI Examples: .. code-block:: bash salt '*' mongodb.user_grant_roles johndoe '["readWrite"]' dbname admin adminpwd localhost 27017 .. code-block:: bash salt '*' mongodb.user_grant_roles janedoe '[{"role": "readWrite", "db": "dbname" }, {"role": "read", "db": "otherdb"}]' dbname admin adminpwd localhost 27017 ''' conn = _connect(user, password, host, port, authdb=authdb) if not conn: return 'Failed to connect to mongo database' try: roles = _to_dict(roles) except Exception: return 'Roles provided in wrong format' try: log.info('Granting roles %s to user %s', roles, name) mdb = pymongo.database.Database(conn, database) mdb.command("grantRolesToUser", name, roles=roles) except pymongo.errors.PyMongoError as err: log.error('Granting roles %s to user %s failed with error: %s', roles, name, err) return six.text_type(err) return True
[ "def", "user_grant_roles", "(", "name", ",", "roles", ",", "database", ",", "user", "=", "None", ",", "password", "=", "None", ",", "host", "=", "None", ",", "port", "=", "None", ",", "authdb", "=", "None", ")", ":", "conn", "=", "_connect", "(", "...
Grant one or many roles to a MongoDB user CLI Examples: .. code-block:: bash salt '*' mongodb.user_grant_roles johndoe '["readWrite"]' dbname admin adminpwd localhost 27017 .. code-block:: bash salt '*' mongodb.user_grant_roles janedoe '[{"role": "readWrite", "db": "dbname" }, {"role": "read", "db": "otherdb"}]' dbname admin adminpwd localhost 27017
[ "Grant", "one", "or", "many", "roles", "to", "a", "MongoDB", "user" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mongodb.py#L363-L395
train
saltstack/salt
salt/modules/mongodb.py
insert
def insert(objects, collection, user=None, password=None, host=None, port=None, database='admin', authdb=None): ''' Insert an object or list of objects into a collection CLI Example: .. code-block:: bash salt '*' mongodb.insert '[{"foo": "FOO", "bar": "BAR"}, {"foo": "BAZ", "bar": "BAM"}]' mycollection <user> <password> <host> <port> <database> ''' conn = _connect(user, password, host, port, database, authdb) if not conn: return "Failed to connect to mongo database" try: objects = _to_dict(objects) except Exception as err: return err try: log.info("Inserting %r into %s.%s", objects, database, collection) mdb = pymongo.database.Database(conn, database) col = getattr(mdb, collection) ids = col.insert(objects) return ids except pymongo.errors.PyMongoError as err: log.error("Inserting objects %r failed with error %s", objects, err) return err
python
def insert(objects, collection, user=None, password=None, host=None, port=None, database='admin', authdb=None): ''' Insert an object or list of objects into a collection CLI Example: .. code-block:: bash salt '*' mongodb.insert '[{"foo": "FOO", "bar": "BAR"}, {"foo": "BAZ", "bar": "BAM"}]' mycollection <user> <password> <host> <port> <database> ''' conn = _connect(user, password, host, port, database, authdb) if not conn: return "Failed to connect to mongo database" try: objects = _to_dict(objects) except Exception as err: return err try: log.info("Inserting %r into %s.%s", objects, database, collection) mdb = pymongo.database.Database(conn, database) col = getattr(mdb, collection) ids = col.insert(objects) return ids except pymongo.errors.PyMongoError as err: log.error("Inserting objects %r failed with error %s", objects, err) return err
[ "def", "insert", "(", "objects", ",", "collection", ",", "user", "=", "None", ",", "password", "=", "None", ",", "host", "=", "None", ",", "port", "=", "None", ",", "database", "=", "'admin'", ",", "authdb", "=", "None", ")", ":", "conn", "=", "_co...
Insert an object or list of objects into a collection CLI Example: .. code-block:: bash salt '*' mongodb.insert '[{"foo": "FOO", "bar": "BAR"}, {"foo": "BAZ", "bar": "BAM"}]' mycollection <user> <password> <host> <port> <database>
[ "Insert", "an", "object", "or", "list", "of", "objects", "into", "a", "collection" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mongodb.py#L433-L462
train
saltstack/salt
salt/modules/mongodb.py
update_one
def update_one(objects, collection, user=None, password=None, host=None, port=None, database='admin', authdb=None): ''' Update an object into a collection http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.update_one .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt '*' mongodb.update_one '{"_id": "my_minion"} {"bar": "BAR"}' mycollection <user> <password> <host> <port> <database> ''' conn = _connect(user, password, host, port, database, authdb) if not conn: return "Failed to connect to mongo database" objects = six.text_type(objects) objs = re.split(r'}\s+{', objects) if len(objs) is not 2: return "Your request does not contain a valid " + \ "'{_\"id\": \"my_id\"} {\"my_doc\": \"my_val\"}'" objs[0] = objs[0] + '}' objs[1] = '{' + objs[1] document = [] for obj in objs: try: obj = _to_dict(obj) document.append(obj) except Exception as err: return err _id_field = document[0] _update_doc = document[1] # need a string to perform the test, so using objs[0] test_f = find(collection, objs[0], user, password, host, port, database, authdb) if not isinstance(test_f, list): return 'The find result is not well formatted. An error appears; cannot update.' elif not test_f: return 'Did not find any result. You should try an insert before.' elif len(test_f) > 1: return 'Too many results. Please try to be more specific.' else: try: log.info("Updating %r into %s.%s", _id_field, database, collection) mdb = pymongo.database.Database(conn, database) col = getattr(mdb, collection) ids = col.update_one(_id_field, {'$set': _update_doc}) nb_mod = ids.modified_count return "{0} objects updated".format(nb_mod) except pymongo.errors.PyMongoError as err: log.error('Updating object %s failed with error %s', objects, err) return err
python
def update_one(objects, collection, user=None, password=None, host=None, port=None, database='admin', authdb=None): ''' Update an object into a collection http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.update_one .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt '*' mongodb.update_one '{"_id": "my_minion"} {"bar": "BAR"}' mycollection <user> <password> <host> <port> <database> ''' conn = _connect(user, password, host, port, database, authdb) if not conn: return "Failed to connect to mongo database" objects = six.text_type(objects) objs = re.split(r'}\s+{', objects) if len(objs) is not 2: return "Your request does not contain a valid " + \ "'{_\"id\": \"my_id\"} {\"my_doc\": \"my_val\"}'" objs[0] = objs[0] + '}' objs[1] = '{' + objs[1] document = [] for obj in objs: try: obj = _to_dict(obj) document.append(obj) except Exception as err: return err _id_field = document[0] _update_doc = document[1] # need a string to perform the test, so using objs[0] test_f = find(collection, objs[0], user, password, host, port, database, authdb) if not isinstance(test_f, list): return 'The find result is not well formatted. An error appears; cannot update.' elif not test_f: return 'Did not find any result. You should try an insert before.' elif len(test_f) > 1: return 'Too many results. Please try to be more specific.' else: try: log.info("Updating %r into %s.%s", _id_field, database, collection) mdb = pymongo.database.Database(conn, database) col = getattr(mdb, collection) ids = col.update_one(_id_field, {'$set': _update_doc}) nb_mod = ids.modified_count return "{0} objects updated".format(nb_mod) except pymongo.errors.PyMongoError as err: log.error('Updating object %s failed with error %s', objects, err) return err
[ "def", "update_one", "(", "objects", ",", "collection", ",", "user", "=", "None", ",", "password", "=", "None", ",", "host", "=", "None", ",", "port", "=", "None", ",", "database", "=", "'admin'", ",", "authdb", "=", "None", ")", ":", "conn", "=", ...
Update an object into a collection http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.update_one .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt '*' mongodb.update_one '{"_id": "my_minion"} {"bar": "BAR"}' mycollection <user> <password> <host> <port> <database>
[ "Update", "an", "object", "into", "a", "collection", "http", ":", "//", "api", ".", "mongodb", ".", "com", "/", "python", "/", "current", "/", "api", "/", "pymongo", "/", "collection", ".", "html#pymongo", ".", "collection", ".", "Collection", ".", "upda...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mongodb.py#L465-L530
train
saltstack/salt
salt/modules/mongodb.py
find
def find(collection, query=None, user=None, password=None, host=None, port=None, database='admin', authdb=None): ''' Find an object or list of objects in a collection CLI Example: .. code-block:: bash salt '*' mongodb.find mycollection '[{"foo": "FOO", "bar": "BAR"}]' <user> <password> <host> <port> <database> ''' conn = _connect(user, password, host, port, database, authdb) if not conn: return 'Failed to connect to mongo database' try: query = _to_dict(query) except Exception as err: return err try: log.info("Searching for %r in %s", query, collection) mdb = pymongo.database.Database(conn, database) col = getattr(mdb, collection) ret = col.find(query) return list(ret) except pymongo.errors.PyMongoError as err: log.error("Searching objects failed with error: %s", err) return err
python
def find(collection, query=None, user=None, password=None, host=None, port=None, database='admin', authdb=None): ''' Find an object or list of objects in a collection CLI Example: .. code-block:: bash salt '*' mongodb.find mycollection '[{"foo": "FOO", "bar": "BAR"}]' <user> <password> <host> <port> <database> ''' conn = _connect(user, password, host, port, database, authdb) if not conn: return 'Failed to connect to mongo database' try: query = _to_dict(query) except Exception as err: return err try: log.info("Searching for %r in %s", query, collection) mdb = pymongo.database.Database(conn, database) col = getattr(mdb, collection) ret = col.find(query) return list(ret) except pymongo.errors.PyMongoError as err: log.error("Searching objects failed with error: %s", err) return err
[ "def", "find", "(", "collection", ",", "query", "=", "None", ",", "user", "=", "None", ",", "password", "=", "None", ",", "host", "=", "None", ",", "port", "=", "None", ",", "database", "=", "'admin'", ",", "authdb", "=", "None", ")", ":", "conn", ...
Find an object or list of objects in a collection CLI Example: .. code-block:: bash salt '*' mongodb.find mycollection '[{"foo": "FOO", "bar": "BAR"}]' <user> <password> <host> <port> <database>
[ "Find", "an", "object", "or", "list", "of", "objects", "in", "a", "collection" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mongodb.py#L533-L562
train
saltstack/salt
salt/states/infoblox_host_record.py
present
def present(name=None, data=None, ensure_data=True, **api_opts): ''' This will ensure that a host with the provided name exists. This will try to ensure that the state of the host matches the given data If the host is not found then one will be created. When trying to update a hostname ensure `name` is set to the hostname of the current record. You can give a new name in the `data.name`. Avoid race conditions, use func:nextavailableip: - func:nextavailableip:network/ZG54dfgsrDFEFfsfsLzA:10.0.0.0/8/default - func:nextavailableip:10.0.0.0/8 - func:nextavailableip:10.0.0.0/8,externalconfigure_for_dns - func:nextavailableip:10.0.0.3-10.0.0.10 State Example: .. code-block:: yaml # this would update `original_hostname.example.ca` to changed `data`. infoblox_host_record.present: - name: original_hostname.example.ca - data: {'namhostname.example.cae': 'hostname.example.ca', 'aliases': ['hostname.math.example.ca'], 'extattrs': [{'Business Contact': {'value': 'EXAMPLE@example.ca'}}], 'ipv4addrs': [{'configure_for_dhcp': True, 'ipv4addr': 'func:nextavailableip:129.97.139.0/24', 'mac': '00:50:56:84:6e:ae'}], 'ipv6addrs': [], } ''' ret = {'name': name, 'result': False, 'comment': '', 'changes': {}} if data is None: data = {} if 'name' not in data: data.update({'name': name}) obj = __salt__['infoblox.get_host'](name=name, **api_opts) if obj is None: # perhaps the user updated the name obj = __salt__['infoblox.get_host'](name=data['name'], **api_opts) if obj: # warn user that the host name was updated and does not match ret['result'] = False ret['comment'] = 'please update the name: {0} to equal the updated data name {1}'.format(name, data['name']) return ret if obj: if not ensure_data: ret['result'] = True ret['comment'] = 'infoblox record already created (supplied fields not ensured to match)' return ret obj = __salt__['infoblox.get_host_advanced'](name=name, **api_opts) diff = __salt__['infoblox.diff_objects'](data, obj) if not diff: ret['result'] = True ret['comment'] = 'supplied fields already updated (note: removing fields might not update)' return ret if diff: ret['changes'] = {'diff': diff} if __opts__['test']: ret['result'] = None ret['comment'] = 'would attempt to update infoblox record' return ret # replace func:nextavailableip with current ip address if in range # get list of ipaddresses that are defined. obj_addrs = [] if 'ipv4addrs' in obj: for addr in obj['ipv4addrs']: if 'ipv4addr' in addr: obj_addrs.append(addr['ipv4addr']) if 'ipv6addrs' in obj: for addr in obj['ipv6addrs']: if 'ipv6addr' in addr: obj_addrs.append(addr['ipv6addr']) # replace func:nextavailableip: if an ip address is already found in that range. if 'ipv4addrs' in data: for addr in data['ipv4addrs']: if 'ipv4addr' in addr: addrobj = addr['ipv4addr'] if addrobj.startswith('func:nextavailableip:'): found_matches = 0 for ip in obj_addrs: if __salt__['infoblox.is_ipaddr_in_ipfunc_range'](ip, addrobj): addr['ipv4addr'] = ip found_matches += 1 if found_matches > 1: ret['comment'] = 'infoblox record cant updated because ipaddress {0} matches multiple func:nextavailableip'.format(ip) ret['result'] = False return ret new_obj = __salt__['infoblox.update_object'](obj['_ref'], data=data, **api_opts) ret['result'] = True ret['comment'] = 'infoblox record fields updated (note: removing fields might not update)' #ret['changes'] = {'diff': diff } return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'would attempt to create infoblox record {0}'.format(name) return ret new_obj_ref = __salt__['infoblox.create_host'](data=data, **api_opts) new_obj = __salt__['infoblox.get_host'](name=name, **api_opts) ret['result'] = True ret['comment'] = 'infoblox record created' ret['changes'] = {'old': 'None', 'new': {'_ref': new_obj_ref, 'data': new_obj}} return ret
python
def present(name=None, data=None, ensure_data=True, **api_opts): ''' This will ensure that a host with the provided name exists. This will try to ensure that the state of the host matches the given data If the host is not found then one will be created. When trying to update a hostname ensure `name` is set to the hostname of the current record. You can give a new name in the `data.name`. Avoid race conditions, use func:nextavailableip: - func:nextavailableip:network/ZG54dfgsrDFEFfsfsLzA:10.0.0.0/8/default - func:nextavailableip:10.0.0.0/8 - func:nextavailableip:10.0.0.0/8,externalconfigure_for_dns - func:nextavailableip:10.0.0.3-10.0.0.10 State Example: .. code-block:: yaml # this would update `original_hostname.example.ca` to changed `data`. infoblox_host_record.present: - name: original_hostname.example.ca - data: {'namhostname.example.cae': 'hostname.example.ca', 'aliases': ['hostname.math.example.ca'], 'extattrs': [{'Business Contact': {'value': 'EXAMPLE@example.ca'}}], 'ipv4addrs': [{'configure_for_dhcp': True, 'ipv4addr': 'func:nextavailableip:129.97.139.0/24', 'mac': '00:50:56:84:6e:ae'}], 'ipv6addrs': [], } ''' ret = {'name': name, 'result': False, 'comment': '', 'changes': {}} if data is None: data = {} if 'name' not in data: data.update({'name': name}) obj = __salt__['infoblox.get_host'](name=name, **api_opts) if obj is None: # perhaps the user updated the name obj = __salt__['infoblox.get_host'](name=data['name'], **api_opts) if obj: # warn user that the host name was updated and does not match ret['result'] = False ret['comment'] = 'please update the name: {0} to equal the updated data name {1}'.format(name, data['name']) return ret if obj: if not ensure_data: ret['result'] = True ret['comment'] = 'infoblox record already created (supplied fields not ensured to match)' return ret obj = __salt__['infoblox.get_host_advanced'](name=name, **api_opts) diff = __salt__['infoblox.diff_objects'](data, obj) if not diff: ret['result'] = True ret['comment'] = 'supplied fields already updated (note: removing fields might not update)' return ret if diff: ret['changes'] = {'diff': diff} if __opts__['test']: ret['result'] = None ret['comment'] = 'would attempt to update infoblox record' return ret # replace func:nextavailableip with current ip address if in range # get list of ipaddresses that are defined. obj_addrs = [] if 'ipv4addrs' in obj: for addr in obj['ipv4addrs']: if 'ipv4addr' in addr: obj_addrs.append(addr['ipv4addr']) if 'ipv6addrs' in obj: for addr in obj['ipv6addrs']: if 'ipv6addr' in addr: obj_addrs.append(addr['ipv6addr']) # replace func:nextavailableip: if an ip address is already found in that range. if 'ipv4addrs' in data: for addr in data['ipv4addrs']: if 'ipv4addr' in addr: addrobj = addr['ipv4addr'] if addrobj.startswith('func:nextavailableip:'): found_matches = 0 for ip in obj_addrs: if __salt__['infoblox.is_ipaddr_in_ipfunc_range'](ip, addrobj): addr['ipv4addr'] = ip found_matches += 1 if found_matches > 1: ret['comment'] = 'infoblox record cant updated because ipaddress {0} matches multiple func:nextavailableip'.format(ip) ret['result'] = False return ret new_obj = __salt__['infoblox.update_object'](obj['_ref'], data=data, **api_opts) ret['result'] = True ret['comment'] = 'infoblox record fields updated (note: removing fields might not update)' #ret['changes'] = {'diff': diff } return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'would attempt to create infoblox record {0}'.format(name) return ret new_obj_ref = __salt__['infoblox.create_host'](data=data, **api_opts) new_obj = __salt__['infoblox.get_host'](name=name, **api_opts) ret['result'] = True ret['comment'] = 'infoblox record created' ret['changes'] = {'old': 'None', 'new': {'_ref': new_obj_ref, 'data': new_obj}} return ret
[ "def", "present", "(", "name", "=", "None", ",", "data", "=", "None", ",", "ensure_data", "=", "True", ",", "*", "*", "api_opts", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "False", ",", "'comment'", ":", "''", ",", "...
This will ensure that a host with the provided name exists. This will try to ensure that the state of the host matches the given data If the host is not found then one will be created. When trying to update a hostname ensure `name` is set to the hostname of the current record. You can give a new name in the `data.name`. Avoid race conditions, use func:nextavailableip: - func:nextavailableip:network/ZG54dfgsrDFEFfsfsLzA:10.0.0.0/8/default - func:nextavailableip:10.0.0.0/8 - func:nextavailableip:10.0.0.0/8,externalconfigure_for_dns - func:nextavailableip:10.0.0.3-10.0.0.10 State Example: .. code-block:: yaml # this would update `original_hostname.example.ca` to changed `data`. infoblox_host_record.present: - name: original_hostname.example.ca - data: {'namhostname.example.cae': 'hostname.example.ca', 'aliases': ['hostname.math.example.ca'], 'extattrs': [{'Business Contact': {'value': 'EXAMPLE@example.ca'}}], 'ipv4addrs': [{'configure_for_dhcp': True, 'ipv4addr': 'func:nextavailableip:129.97.139.0/24', 'mac': '00:50:56:84:6e:ae'}], 'ipv6addrs': [], }
[ "This", "will", "ensure", "that", "a", "host", "with", "the", "provided", "name", "exists", ".", "This", "will", "try", "to", "ensure", "that", "the", "state", "of", "the", "host", "matches", "the", "given", "data", "If", "the", "host", "is", "not", "f...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/infoblox_host_record.py#L17-L128
train
saltstack/salt
salt/proxy/marathon.py
init
def init(opts): ''' Perform any needed setup. ''' if CONFIG_BASE_URL in opts['proxy']: CONFIG[CONFIG_BASE_URL] = opts['proxy'][CONFIG_BASE_URL] else: log.error('missing proxy property %s', CONFIG_BASE_URL) log.debug('CONFIG: %s', CONFIG)
python
def init(opts): ''' Perform any needed setup. ''' if CONFIG_BASE_URL in opts['proxy']: CONFIG[CONFIG_BASE_URL] = opts['proxy'][CONFIG_BASE_URL] else: log.error('missing proxy property %s', CONFIG_BASE_URL) log.debug('CONFIG: %s', CONFIG)
[ "def", "init", "(", "opts", ")", ":", "if", "CONFIG_BASE_URL", "in", "opts", "[", "'proxy'", "]", ":", "CONFIG", "[", "CONFIG_BASE_URL", "]", "=", "opts", "[", "'proxy'", "]", "[", "CONFIG_BASE_URL", "]", "else", ":", "log", ".", "error", "(", "'missin...
Perform any needed setup.
[ "Perform", "any", "needed", "setup", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/marathon.py#L43-L51
train
saltstack/salt
salt/proxy/marathon.py
ping
def ping(): ''' Is the marathon api responding? ''' try: response = salt.utils.http.query( "{0}/ping".format(CONFIG[CONFIG_BASE_URL]), decode_type='plain', decode=True, ) log.debug( 'marathon.info returned successfully: %s', response, ) if 'text' in response and response['text'].strip() == 'pong': return True except Exception as ex: log.error( 'error calling marathon.info with base_url %s: %s', CONFIG[CONFIG_BASE_URL], ex, ) return False
python
def ping(): ''' Is the marathon api responding? ''' try: response = salt.utils.http.query( "{0}/ping".format(CONFIG[CONFIG_BASE_URL]), decode_type='plain', decode=True, ) log.debug( 'marathon.info returned successfully: %s', response, ) if 'text' in response and response['text'].strip() == 'pong': return True except Exception as ex: log.error( 'error calling marathon.info with base_url %s: %s', CONFIG[CONFIG_BASE_URL], ex, ) return False
[ "def", "ping", "(", ")", ":", "try", ":", "response", "=", "salt", ".", "utils", ".", "http", ".", "query", "(", "\"{0}/ping\"", ".", "format", "(", "CONFIG", "[", "CONFIG_BASE_URL", "]", ")", ",", "decode_type", "=", "'plain'", ",", "decode", "=", "...
Is the marathon api responding?
[ "Is", "the", "marathon", "api", "responding?" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/marathon.py#L54-L76
train
saltstack/salt
salt/modules/glance.py
_auth
def _auth(profile=None, api_version=2, **connection_args): ''' Set up glance credentials, returns `glanceclient.client.Client`. Optional parameter "api_version" defaults to 2. Only intended to be used within glance-enabled modules ''' __utils__['versions.warn_until']( 'Neon', ( 'The glance module has been deprecated and will be removed in {version}. ' 'Please update to using the glanceng module' ), ) if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' Checks connection_args, then salt-minion config, falls back to specified default value. ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', None) tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0') insecure = get('insecure', False) admin_token = get('token') region = get('region') ks_endpoint = get('endpoint', 'http://127.0.0.1:9292/') g_endpoint_url = __salt__['keystone.endpoint_get']('glance', profile) # The trailing 'v2' causes URLs like thise one: # http://127.0.0.1:9292/v2/v1/images g_endpoint_url = re.sub('/v2', '', g_endpoint_url['internalurl']) if admin_token and api_version != 1 and not password: # If we had a password we could just # ignore the admin-token and move on... raise SaltInvocationError('Only can use keystone admin token ' + 'with Glance API v1') elif password: # Can't use the admin-token anyway kwargs = {'username': user, 'password': password, 'tenant_id': tenant_id, 'auth_url': auth_url, 'endpoint_url': g_endpoint_url, 'region_name': region, 'tenant_name': tenant} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True elif api_version == 1 and admin_token: kwargs = {'token': admin_token, 'auth_url': auth_url, 'endpoint_url': g_endpoint_url} else: raise SaltInvocationError('No credentials to authenticate with.') if HAS_KEYSTONE: log.debug('Calling keystoneclient.v2_0.client.Client(%s, **%s)', ks_endpoint, kwargs) keystone = kstone.Client(**kwargs) kwargs['token'] = keystone.get_token(keystone.session) # This doesn't realy prevent the password to show up # in the minion log as keystoneclient.session is # logging it anyway when in debug-mode kwargs.pop('password') log.debug('Calling glanceclient.client.Client(%s, %s, **%s)', api_version, g_endpoint_url, kwargs) # may raise exc.HTTPUnauthorized, exc.HTTPNotFound # but we deal with those elsewhere return client.Client(api_version, g_endpoint_url, **kwargs) else: raise NotImplementedError( "Can't retrieve a auth_token without keystone")
python
def _auth(profile=None, api_version=2, **connection_args): ''' Set up glance credentials, returns `glanceclient.client.Client`. Optional parameter "api_version" defaults to 2. Only intended to be used within glance-enabled modules ''' __utils__['versions.warn_until']( 'Neon', ( 'The glance module has been deprecated and will be removed in {version}. ' 'Please update to using the glanceng module' ), ) if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' Checks connection_args, then salt-minion config, falls back to specified default value. ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', None) tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0') insecure = get('insecure', False) admin_token = get('token') region = get('region') ks_endpoint = get('endpoint', 'http://127.0.0.1:9292/') g_endpoint_url = __salt__['keystone.endpoint_get']('glance', profile) # The trailing 'v2' causes URLs like thise one: # http://127.0.0.1:9292/v2/v1/images g_endpoint_url = re.sub('/v2', '', g_endpoint_url['internalurl']) if admin_token and api_version != 1 and not password: # If we had a password we could just # ignore the admin-token and move on... raise SaltInvocationError('Only can use keystone admin token ' + 'with Glance API v1') elif password: # Can't use the admin-token anyway kwargs = {'username': user, 'password': password, 'tenant_id': tenant_id, 'auth_url': auth_url, 'endpoint_url': g_endpoint_url, 'region_name': region, 'tenant_name': tenant} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True elif api_version == 1 and admin_token: kwargs = {'token': admin_token, 'auth_url': auth_url, 'endpoint_url': g_endpoint_url} else: raise SaltInvocationError('No credentials to authenticate with.') if HAS_KEYSTONE: log.debug('Calling keystoneclient.v2_0.client.Client(%s, **%s)', ks_endpoint, kwargs) keystone = kstone.Client(**kwargs) kwargs['token'] = keystone.get_token(keystone.session) # This doesn't realy prevent the password to show up # in the minion log as keystoneclient.session is # logging it anyway when in debug-mode kwargs.pop('password') log.debug('Calling glanceclient.client.Client(%s, %s, **%s)', api_version, g_endpoint_url, kwargs) # may raise exc.HTTPUnauthorized, exc.HTTPNotFound # but we deal with those elsewhere return client.Client(api_version, g_endpoint_url, **kwargs) else: raise NotImplementedError( "Can't retrieve a auth_token without keystone")
[ "def", "_auth", "(", "profile", "=", "None", ",", "api_version", "=", "2", ",", "*", "*", "connection_args", ")", ":", "__utils__", "[", "'versions.warn_until'", "]", "(", "'Neon'", ",", "(", "'The glance module has been deprecated and will be removed in {version}. '...
Set up glance credentials, returns `glanceclient.client.Client`. Optional parameter "api_version" defaults to 2. Only intended to be used within glance-enabled modules
[ "Set", "up", "glance", "credentials", "returns", "glanceclient", ".", "client", ".", "Client", ".", "Optional", "parameter", "api_version", "defaults", "to", "2", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/glance.py#L98-L182
train
saltstack/salt
salt/modules/glance.py
_add_image
def _add_image(collection, image): ''' Add image to given dictionary ''' image_prep = { 'id': image.id, 'name': image.name, 'created_at': image.created_at, 'file': image.file, 'min_disk': image.min_disk, 'min_ram': image.min_ram, 'owner': image.owner, 'protected': image.protected, 'status': image.status, 'tags': image.tags, 'updated_at': image.updated_at, 'visibility': image.visibility, } # Those cause AttributeErrors in Icehouse' glanceclient for attr in ['container_format', 'disk_format', 'size']: if attr in image: image_prep[attr] = image[attr] if type(collection) is dict: collection[image.name] = image_prep elif type(collection) is list: collection.append(image_prep) else: msg = '"collection" is {0}'.format(type(collection)) +\ 'instead of dict or list.' log.error(msg) raise TypeError(msg) return collection
python
def _add_image(collection, image): ''' Add image to given dictionary ''' image_prep = { 'id': image.id, 'name': image.name, 'created_at': image.created_at, 'file': image.file, 'min_disk': image.min_disk, 'min_ram': image.min_ram, 'owner': image.owner, 'protected': image.protected, 'status': image.status, 'tags': image.tags, 'updated_at': image.updated_at, 'visibility': image.visibility, } # Those cause AttributeErrors in Icehouse' glanceclient for attr in ['container_format', 'disk_format', 'size']: if attr in image: image_prep[attr] = image[attr] if type(collection) is dict: collection[image.name] = image_prep elif type(collection) is list: collection.append(image_prep) else: msg = '"collection" is {0}'.format(type(collection)) +\ 'instead of dict or list.' log.error(msg) raise TypeError(msg) return collection
[ "def", "_add_image", "(", "collection", ",", "image", ")", ":", "image_prep", "=", "{", "'id'", ":", "image", ".", "id", ",", "'name'", ":", "image", ".", "name", ",", "'created_at'", ":", "image", ".", "created_at", ",", "'file'", ":", "image", ".", ...
Add image to given dictionary
[ "Add", "image", "to", "given", "dictionary" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/glance.py#L185-L216
train
saltstack/salt
salt/modules/glance.py
image_create
def image_create(name, location=None, profile=None, visibility=None, container_format='bare', disk_format='raw', protected=None,): ''' Create an image (glance image-create) CLI Example, old format: .. code-block:: bash salt '*' glance.image_create name=f16-jeos \\ disk_format=qcow2 container_format=ovf CLI Example, new format resembling Glance API v2: .. code-block:: bash salt '*' glance.image_create name=f16-jeos visibility=public \\ disk_format=qcow2 container_format=ovf The parameter 'visibility' defaults to 'public' if not specified. ''' kwargs = {} # valid options for "visibility": v_list = ['public', 'private'] # valid options for "container_format": cf_list = ['ami', 'ari', 'aki', 'bare', 'ovf'] # valid options for "disk_format": df_list = ['ami', 'ari', 'aki', 'vhd', 'vmdk', 'raw', 'qcow2', 'vdi', 'iso'] kwargs['copy_from'] = location if visibility is not None: if visibility not in v_list: raise SaltInvocationError('"visibility" needs to be one ' + 'of the following: {0}'.format(', '.join(v_list))) elif visibility == 'public': kwargs['is_public'] = True else: kwargs['is_public'] = False else: kwargs['is_public'] = True if container_format not in cf_list: raise SaltInvocationError('"container_format" needs to be ' + 'one of the following: {0}'.format(', '.join(cf_list))) else: kwargs['container_format'] = container_format if disk_format not in df_list: raise SaltInvocationError('"disk_format" needs to be one ' + 'of the following: {0}'.format(', '.join(df_list))) else: kwargs['disk_format'] = disk_format if protected is not None: kwargs['protected'] = protected # Icehouse's glanceclient doesn't have add_location() and # glanceclient.v2 doesn't implement Client.images.create() # in a usable fashion. Thus we have to use v1 for now. g_client = _auth(profile, api_version=1) image = g_client.images.create(name=name, **kwargs) return image_show(image.id, profile=profile)
python
def image_create(name, location=None, profile=None, visibility=None, container_format='bare', disk_format='raw', protected=None,): ''' Create an image (glance image-create) CLI Example, old format: .. code-block:: bash salt '*' glance.image_create name=f16-jeos \\ disk_format=qcow2 container_format=ovf CLI Example, new format resembling Glance API v2: .. code-block:: bash salt '*' glance.image_create name=f16-jeos visibility=public \\ disk_format=qcow2 container_format=ovf The parameter 'visibility' defaults to 'public' if not specified. ''' kwargs = {} # valid options for "visibility": v_list = ['public', 'private'] # valid options for "container_format": cf_list = ['ami', 'ari', 'aki', 'bare', 'ovf'] # valid options for "disk_format": df_list = ['ami', 'ari', 'aki', 'vhd', 'vmdk', 'raw', 'qcow2', 'vdi', 'iso'] kwargs['copy_from'] = location if visibility is not None: if visibility not in v_list: raise SaltInvocationError('"visibility" needs to be one ' + 'of the following: {0}'.format(', '.join(v_list))) elif visibility == 'public': kwargs['is_public'] = True else: kwargs['is_public'] = False else: kwargs['is_public'] = True if container_format not in cf_list: raise SaltInvocationError('"container_format" needs to be ' + 'one of the following: {0}'.format(', '.join(cf_list))) else: kwargs['container_format'] = container_format if disk_format not in df_list: raise SaltInvocationError('"disk_format" needs to be one ' + 'of the following: {0}'.format(', '.join(df_list))) else: kwargs['disk_format'] = disk_format if protected is not None: kwargs['protected'] = protected # Icehouse's glanceclient doesn't have add_location() and # glanceclient.v2 doesn't implement Client.images.create() # in a usable fashion. Thus we have to use v1 for now. g_client = _auth(profile, api_version=1) image = g_client.images.create(name=name, **kwargs) return image_show(image.id, profile=profile)
[ "def", "image_create", "(", "name", ",", "location", "=", "None", ",", "profile", "=", "None", ",", "visibility", "=", "None", ",", "container_format", "=", "'bare'", ",", "disk_format", "=", "'raw'", ",", "protected", "=", "None", ",", ")", ":", "kwargs...
Create an image (glance image-create) CLI Example, old format: .. code-block:: bash salt '*' glance.image_create name=f16-jeos \\ disk_format=qcow2 container_format=ovf CLI Example, new format resembling Glance API v2: .. code-block:: bash salt '*' glance.image_create name=f16-jeos visibility=public \\ disk_format=qcow2 container_format=ovf The parameter 'visibility' defaults to 'public' if not specified.
[ "Create", "an", "image", "(", "glance", "image", "-", "create", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/glance.py#L219-L282
train
saltstack/salt
salt/modules/glance.py
image_delete
def image_delete(id=None, name=None, profile=None): # pylint: disable=C0103 ''' Delete an image (glance image-delete) CLI Examples: .. code-block:: bash salt '*' glance.image_delete c2eb2eb0-53e1-4a80-b990-8ec887eae7df salt '*' glance.image_delete id=c2eb2eb0-53e1-4a80-b990-8ec887eae7df salt '*' glance.image_delete name=f16-jeos ''' g_client = _auth(profile) image = {'id': False, 'name': None} if name: for image in g_client.images.list(): if image.name == name: id = image.id # pylint: disable=C0103 continue if not id: return { 'result': False, 'comment': 'Unable to resolve image id ' 'for name {0}'.format(name) } elif not name: name = image['name'] try: g_client.images.delete(id) except exc.HTTPNotFound: return { 'result': False, 'comment': 'No image with ID {0}'.format(id) } except exc.HTTPForbidden as forbidden: log.error(six.text_type(forbidden)) return { 'result': False, 'comment': six.text_type(forbidden) } return { 'result': True, 'comment': 'Deleted image \'{0}\' ({1}).'.format(name, id), }
python
def image_delete(id=None, name=None, profile=None): # pylint: disable=C0103 ''' Delete an image (glance image-delete) CLI Examples: .. code-block:: bash salt '*' glance.image_delete c2eb2eb0-53e1-4a80-b990-8ec887eae7df salt '*' glance.image_delete id=c2eb2eb0-53e1-4a80-b990-8ec887eae7df salt '*' glance.image_delete name=f16-jeos ''' g_client = _auth(profile) image = {'id': False, 'name': None} if name: for image in g_client.images.list(): if image.name == name: id = image.id # pylint: disable=C0103 continue if not id: return { 'result': False, 'comment': 'Unable to resolve image id ' 'for name {0}'.format(name) } elif not name: name = image['name'] try: g_client.images.delete(id) except exc.HTTPNotFound: return { 'result': False, 'comment': 'No image with ID {0}'.format(id) } except exc.HTTPForbidden as forbidden: log.error(six.text_type(forbidden)) return { 'result': False, 'comment': six.text_type(forbidden) } return { 'result': True, 'comment': 'Deleted image \'{0}\' ({1}).'.format(name, id), }
[ "def", "image_delete", "(", "id", "=", "None", ",", "name", "=", "None", ",", "profile", "=", "None", ")", ":", "# pylint: disable=C0103", "g_client", "=", "_auth", "(", "profile", ")", "image", "=", "{", "'id'", ":", "False", ",", "'name'", ":", "None...
Delete an image (glance image-delete) CLI Examples: .. code-block:: bash salt '*' glance.image_delete c2eb2eb0-53e1-4a80-b990-8ec887eae7df salt '*' glance.image_delete id=c2eb2eb0-53e1-4a80-b990-8ec887eae7df salt '*' glance.image_delete name=f16-jeos
[ "Delete", "an", "image", "(", "glance", "image", "-", "delete", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/glance.py#L285-L329
train
saltstack/salt
salt/modules/glance.py
image_show
def image_show(id=None, name=None, profile=None): # pylint: disable=C0103 ''' Return details about a specific image (glance image-show) CLI Example: .. code-block:: bash salt '*' glance.image_show ''' g_client = _auth(profile) ret = {} if name: for image in g_client.images.list(): if image.name == name: id = image.id # pylint: disable=C0103 continue if not id: return { 'result': False, 'comment': 'Unable to resolve image ID ' 'for name \'{0}\''.format(name) } try: image = g_client.images.get(id) except exc.HTTPNotFound: return { 'result': False, 'comment': 'No image with ID {0}'.format(id) } log.debug( 'Properties of image %s:\n%s', image.name, pprint.PrettyPrinter(indent=4).pformat(image) ) schema = image_schema(profile=profile) if len(schema.keys()) == 1: schema = schema['image'] for key in schema: if key in image: ret[key] = image[key] return ret
python
def image_show(id=None, name=None, profile=None): # pylint: disable=C0103 ''' Return details about a specific image (glance image-show) CLI Example: .. code-block:: bash salt '*' glance.image_show ''' g_client = _auth(profile) ret = {} if name: for image in g_client.images.list(): if image.name == name: id = image.id # pylint: disable=C0103 continue if not id: return { 'result': False, 'comment': 'Unable to resolve image ID ' 'for name \'{0}\''.format(name) } try: image = g_client.images.get(id) except exc.HTTPNotFound: return { 'result': False, 'comment': 'No image with ID {0}'.format(id) } log.debug( 'Properties of image %s:\n%s', image.name, pprint.PrettyPrinter(indent=4).pformat(image) ) schema = image_schema(profile=profile) if len(schema.keys()) == 1: schema = schema['image'] for key in schema: if key in image: ret[key] = image[key] return ret
[ "def", "image_show", "(", "id", "=", "None", ",", "name", "=", "None", ",", "profile", "=", "None", ")", ":", "# pylint: disable=C0103", "g_client", "=", "_auth", "(", "profile", ")", "ret", "=", "{", "}", "if", "name", ":", "for", "image", "in", "g_...
Return details about a specific image (glance image-show) CLI Example: .. code-block:: bash salt '*' glance.image_show
[ "Return", "details", "about", "a", "specific", "image", "(", "glance", "image", "-", "show", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/glance.py#L332-L374
train
saltstack/salt
salt/modules/glance.py
image_list
def image_list(id=None, profile=None, name=None): # pylint: disable=C0103 ''' Return a list of available images (glance image-list) CLI Example: .. code-block:: bash salt '*' glance.image_list ''' g_client = _auth(profile) ret = [] for image in g_client.images.list(): if id is None and name is None: _add_image(ret, image) else: if id is not None and id == image.id: _add_image(ret, image) return ret if name == image.name: if name in ret and CUR_VER < BORON: # Not really worth an exception return { 'result': False, 'comment': 'More than one image with ' 'name "{0}"'.format(name) } _add_image(ret, image) log.debug('Returning images: %s', ret) return ret
python
def image_list(id=None, profile=None, name=None): # pylint: disable=C0103 ''' Return a list of available images (glance image-list) CLI Example: .. code-block:: bash salt '*' glance.image_list ''' g_client = _auth(profile) ret = [] for image in g_client.images.list(): if id is None and name is None: _add_image(ret, image) else: if id is not None and id == image.id: _add_image(ret, image) return ret if name == image.name: if name in ret and CUR_VER < BORON: # Not really worth an exception return { 'result': False, 'comment': 'More than one image with ' 'name "{0}"'.format(name) } _add_image(ret, image) log.debug('Returning images: %s', ret) return ret
[ "def", "image_list", "(", "id", "=", "None", ",", "profile", "=", "None", ",", "name", "=", "None", ")", ":", "# pylint: disable=C0103", "g_client", "=", "_auth", "(", "profile", ")", "ret", "=", "[", "]", "for", "image", "in", "g_client", ".", "images...
Return a list of available images (glance image-list) CLI Example: .. code-block:: bash salt '*' glance.image_list
[ "Return", "a", "list", "of", "available", "images", "(", "glance", "image", "-", "list", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/glance.py#L377-L407
train
saltstack/salt
salt/modules/glance.py
image_update
def image_update(id=None, name=None, profile=None, **kwargs): # pylint: disable=C0103 ''' Update properties of given image. Known to work for: - min_ram (in MB) - protected (bool) - visibility ('public' or 'private') CLI Example: .. code-block:: bash salt '*' glance.image_update id=c2eb2eb0-53e1-4a80-b990-8ec887eae7df salt '*' glance.image_update name=f16-jeos ''' if id: image = image_show(id=id, profile=profile) if 'result' in image and not image['result']: return image elif len(image) == 1: image = image.values()[0] elif name: img_list = image_list(name=name, profile=profile) if img_list is dict and 'result' in img_list: return img_list elif not img_list: return { 'result': False, 'comment': 'No image with name \'{0}\' ' 'found.'.format(name) } elif len(img_list) == 1: try: image = img_list[0] except KeyError: image = img_list[name] else: raise SaltInvocationError log.debug('Found image:\n%s', image) to_update = {} for key, value in kwargs.items(): if key.startswith('_'): continue if key not in image or image[key] != value: log.debug('add <%s=%s> to to_update', key, value) to_update[key] = value g_client = _auth(profile) updated = g_client.images.update(image['id'], **to_update) return updated
python
def image_update(id=None, name=None, profile=None, **kwargs): # pylint: disable=C0103 ''' Update properties of given image. Known to work for: - min_ram (in MB) - protected (bool) - visibility ('public' or 'private') CLI Example: .. code-block:: bash salt '*' glance.image_update id=c2eb2eb0-53e1-4a80-b990-8ec887eae7df salt '*' glance.image_update name=f16-jeos ''' if id: image = image_show(id=id, profile=profile) if 'result' in image and not image['result']: return image elif len(image) == 1: image = image.values()[0] elif name: img_list = image_list(name=name, profile=profile) if img_list is dict and 'result' in img_list: return img_list elif not img_list: return { 'result': False, 'comment': 'No image with name \'{0}\' ' 'found.'.format(name) } elif len(img_list) == 1: try: image = img_list[0] except KeyError: image = img_list[name] else: raise SaltInvocationError log.debug('Found image:\n%s', image) to_update = {} for key, value in kwargs.items(): if key.startswith('_'): continue if key not in image or image[key] != value: log.debug('add <%s=%s> to to_update', key, value) to_update[key] = value g_client = _auth(profile) updated = g_client.images.update(image['id'], **to_update) return updated
[ "def", "image_update", "(", "id", "=", "None", ",", "name", "=", "None", ",", "profile", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=C0103", "if", "id", ":", "image", "=", "image_show", "(", "id", "=", "id", ",", "profile", "="...
Update properties of given image. Known to work for: - min_ram (in MB) - protected (bool) - visibility ('public' or 'private') CLI Example: .. code-block:: bash salt '*' glance.image_update id=c2eb2eb0-53e1-4a80-b990-8ec887eae7df salt '*' glance.image_update name=f16-jeos
[ "Update", "properties", "of", "given", "image", ".", "Known", "to", "work", "for", ":", "-", "min_ram", "(", "in", "MB", ")", "-", "protected", "(", "bool", ")", "-", "visibility", "(", "public", "or", "private", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/glance.py#L424-L473
train
saltstack/salt
salt/modules/glance.py
schema_get
def schema_get(name, profile=None): ''' Known valid names of schemas are: - image - images - member - members CLI Example: .. code-block:: bash salt '*' glance.schema_get name=f16-jeos ''' g_client = _auth(profile) schema_props = {} for prop in g_client.schemas.get(name).properties: schema_props[prop.name] = prop.description log.debug( 'Properties of schema %s:\n%s', name, pprint.PrettyPrinter(indent=4).pformat(schema_props) ) return {name: schema_props}
python
def schema_get(name, profile=None): ''' Known valid names of schemas are: - image - images - member - members CLI Example: .. code-block:: bash salt '*' glance.schema_get name=f16-jeos ''' g_client = _auth(profile) schema_props = {} for prop in g_client.schemas.get(name).properties: schema_props[prop.name] = prop.description log.debug( 'Properties of schema %s:\n%s', name, pprint.PrettyPrinter(indent=4).pformat(schema_props) ) return {name: schema_props}
[ "def", "schema_get", "(", "name", ",", "profile", "=", "None", ")", ":", "g_client", "=", "_auth", "(", "profile", ")", "schema_props", "=", "{", "}", "for", "prop", "in", "g_client", ".", "schemas", ".", "get", "(", "name", ")", ".", "properties", "...
Known valid names of schemas are: - image - images - member - members CLI Example: .. code-block:: bash salt '*' glance.schema_get name=f16-jeos
[ "Known", "valid", "names", "of", "schemas", "are", ":", "-", "image", "-", "images", "-", "member", "-", "members" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/glance.py#L476-L498
train
saltstack/salt
salt/modules/glance.py
_item_list
def _item_list(profile=None): ''' Template for writing list functions Return a list of available items (glance items-list) CLI Example: .. code-block:: bash salt '*' glance.item_list ''' g_client = _auth(profile) ret = [] for item in g_client.items.list(): ret.append(item.__dict__) #ret[item.name] = { # 'name': item.name, # } return ret
python
def _item_list(profile=None): ''' Template for writing list functions Return a list of available items (glance items-list) CLI Example: .. code-block:: bash salt '*' glance.item_list ''' g_client = _auth(profile) ret = [] for item in g_client.items.list(): ret.append(item.__dict__) #ret[item.name] = { # 'name': item.name, # } return ret
[ "def", "_item_list", "(", "profile", "=", "None", ")", ":", "g_client", "=", "_auth", "(", "profile", ")", "ret", "=", "[", "]", "for", "item", "in", "g_client", ".", "items", ".", "list", "(", ")", ":", "ret", ".", "append", "(", "item", ".", "_...
Template for writing list functions Return a list of available items (glance items-list) CLI Example: .. code-block:: bash salt '*' glance.item_list
[ "Template", "for", "writing", "list", "functions", "Return", "a", "list", "of", "available", "items", "(", "glance", "items", "-", "list", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/glance.py#L501-L519
train
saltstack/salt
salt/states/loop.py
until
def until(name, m_args=None, m_kwargs=None, condition=None, period=0, timeout=604800): ''' Loop over an execution module until a condition is met. name The name of the execution module m_args The execution module's positional arguments m_kwargs The execution module's keyword arguments condition The condition which must be met for the loop to break. This should contain ``m_ret`` which is the return from the execution module. period The number of seconds to wait between executions timeout The timeout in seconds ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if name not in __salt__: ret['comment'] = 'Cannot find module {0}'.format(name) return ret if condition is None: ret['comment'] = 'An exit condition must be specified' return ret if not isinstance(period, int): ret['comment'] = 'Period must be specified as an integer in seconds' return ret if not isinstance(timeout, int): ret['comment'] = 'Timeout must be specified as an integer in seconds' return ret if __opts__['test']: ret['comment'] = 'The execution module {0} will be run'.format(name) ret['result'] = None return ret if not m_args: m_args = [] if not m_kwargs: m_kwargs = {} def timed_out(): if time.time() >= timeout: return True return False timeout = time.time() + timeout while not timed_out(): m_ret = __salt__[name](*m_args, **m_kwargs) if eval(condition): # pylint: disable=W0123 ret['result'] = True ret['comment'] = 'Condition {0} was met'.format(condition) return ret time.sleep(period) ret['comment'] = 'Timed out while waiting for condition {0}'.format(condition) return ret
python
def until(name, m_args=None, m_kwargs=None, condition=None, period=0, timeout=604800): ''' Loop over an execution module until a condition is met. name The name of the execution module m_args The execution module's positional arguments m_kwargs The execution module's keyword arguments condition The condition which must be met for the loop to break. This should contain ``m_ret`` which is the return from the execution module. period The number of seconds to wait between executions timeout The timeout in seconds ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if name not in __salt__: ret['comment'] = 'Cannot find module {0}'.format(name) return ret if condition is None: ret['comment'] = 'An exit condition must be specified' return ret if not isinstance(period, int): ret['comment'] = 'Period must be specified as an integer in seconds' return ret if not isinstance(timeout, int): ret['comment'] = 'Timeout must be specified as an integer in seconds' return ret if __opts__['test']: ret['comment'] = 'The execution module {0} will be run'.format(name) ret['result'] = None return ret if not m_args: m_args = [] if not m_kwargs: m_kwargs = {} def timed_out(): if time.time() >= timeout: return True return False timeout = time.time() + timeout while not timed_out(): m_ret = __salt__[name](*m_args, **m_kwargs) if eval(condition): # pylint: disable=W0123 ret['result'] = True ret['comment'] = 'Condition {0} was met'.format(condition) return ret time.sleep(period) ret['comment'] = 'Timed out while waiting for condition {0}'.format(condition) return ret
[ "def", "until", "(", "name", ",", "m_args", "=", "None", ",", "m_kwargs", "=", "None", ",", "condition", "=", "None", ",", "period", "=", "0", ",", "timeout", "=", "604800", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", ...
Loop over an execution module until a condition is met. name The name of the execution module m_args The execution module's positional arguments m_kwargs The execution module's keyword arguments condition The condition which must be met for the loop to break. This should contain ``m_ret`` which is the return from the execution module. period The number of seconds to wait between executions timeout The timeout in seconds
[ "Loop", "over", "an", "execution", "module", "until", "a", "condition", "is", "met", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/loop.py#L47-L118
train
saltstack/salt
salt/cloud/clouds/proxmox.py
_authenticate
def _authenticate(): ''' Retrieve CSRF and API tickets for the Proxmox API ''' global url, port, ticket, csrf, verify_ssl url = config.get_cloud_config_value( 'url', get_configured_provider(), __opts__, search_global=False ) port = config.get_cloud_config_value( 'port', get_configured_provider(), __opts__, default=8006, search_global=False ) username = config.get_cloud_config_value( 'user', get_configured_provider(), __opts__, search_global=False ), passwd = config.get_cloud_config_value( 'password', get_configured_provider(), __opts__, search_global=False ) verify_ssl = config.get_cloud_config_value( 'verify_ssl', get_configured_provider(), __opts__, default=True, search_global=False ) connect_data = {'username': username, 'password': passwd} full_url = 'https://{0}:{1}/api2/json/access/ticket'.format(url, port) returned_data = requests.post( full_url, verify=verify_ssl, data=connect_data).json() ticket = {'PVEAuthCookie': returned_data['data']['ticket']} csrf = six.text_type(returned_data['data']['CSRFPreventionToken'])
python
def _authenticate(): ''' Retrieve CSRF and API tickets for the Proxmox API ''' global url, port, ticket, csrf, verify_ssl url = config.get_cloud_config_value( 'url', get_configured_provider(), __opts__, search_global=False ) port = config.get_cloud_config_value( 'port', get_configured_provider(), __opts__, default=8006, search_global=False ) username = config.get_cloud_config_value( 'user', get_configured_provider(), __opts__, search_global=False ), passwd = config.get_cloud_config_value( 'password', get_configured_provider(), __opts__, search_global=False ) verify_ssl = config.get_cloud_config_value( 'verify_ssl', get_configured_provider(), __opts__, default=True, search_global=False ) connect_data = {'username': username, 'password': passwd} full_url = 'https://{0}:{1}/api2/json/access/ticket'.format(url, port) returned_data = requests.post( full_url, verify=verify_ssl, data=connect_data).json() ticket = {'PVEAuthCookie': returned_data['data']['ticket']} csrf = six.text_type(returned_data['data']['CSRFPreventionToken'])
[ "def", "_authenticate", "(", ")", ":", "global", "url", ",", "port", ",", "ticket", ",", "csrf", ",", "verify_ssl", "url", "=", "config", ".", "get_cloud_config_value", "(", "'url'", ",", "get_configured_provider", "(", ")", ",", "__opts__", ",", "search_glo...
Retrieve CSRF and API tickets for the Proxmox API
[ "Retrieve", "CSRF", "and", "API", "tickets", "for", "the", "Proxmox", "API" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/proxmox.py#L116-L146
train
saltstack/salt
salt/cloud/clouds/proxmox.py
query
def query(conn_type, option, post_data=None): ''' Execute the HTTP request to the API ''' if ticket is None or csrf is None or url is None: log.debug('Not authenticated yet, doing that now..') _authenticate() full_url = 'https://{0}:{1}/api2/json/{2}'.format(url, port, option) log.debug('%s: %s (%s)', conn_type, full_url, post_data) httpheaders = {'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'salt-cloud-proxmox'} if conn_type == 'post': httpheaders['CSRFPreventionToken'] = csrf response = requests.post(full_url, verify=verify_ssl, data=post_data, cookies=ticket, headers=httpheaders) elif conn_type == 'put': httpheaders['CSRFPreventionToken'] = csrf response = requests.put(full_url, verify=verify_ssl, data=post_data, cookies=ticket, headers=httpheaders) elif conn_type == 'delete': httpheaders['CSRFPreventionToken'] = csrf response = requests.delete(full_url, verify=verify_ssl, data=post_data, cookies=ticket, headers=httpheaders) elif conn_type == 'get': response = requests.get(full_url, verify=verify_ssl, cookies=ticket) response.raise_for_status() try: returned_data = response.json() if 'data' not in returned_data: raise SaltCloudExecutionFailure return returned_data['data'] except Exception: log.error('Error in trying to process JSON') log.error(response)
python
def query(conn_type, option, post_data=None): ''' Execute the HTTP request to the API ''' if ticket is None or csrf is None or url is None: log.debug('Not authenticated yet, doing that now..') _authenticate() full_url = 'https://{0}:{1}/api2/json/{2}'.format(url, port, option) log.debug('%s: %s (%s)', conn_type, full_url, post_data) httpheaders = {'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'salt-cloud-proxmox'} if conn_type == 'post': httpheaders['CSRFPreventionToken'] = csrf response = requests.post(full_url, verify=verify_ssl, data=post_data, cookies=ticket, headers=httpheaders) elif conn_type == 'put': httpheaders['CSRFPreventionToken'] = csrf response = requests.put(full_url, verify=verify_ssl, data=post_data, cookies=ticket, headers=httpheaders) elif conn_type == 'delete': httpheaders['CSRFPreventionToken'] = csrf response = requests.delete(full_url, verify=verify_ssl, data=post_data, cookies=ticket, headers=httpheaders) elif conn_type == 'get': response = requests.get(full_url, verify=verify_ssl, cookies=ticket) response.raise_for_status() try: returned_data = response.json() if 'data' not in returned_data: raise SaltCloudExecutionFailure return returned_data['data'] except Exception: log.error('Error in trying to process JSON') log.error(response)
[ "def", "query", "(", "conn_type", ",", "option", ",", "post_data", "=", "None", ")", ":", "if", "ticket", "is", "None", "or", "csrf", "is", "None", "or", "url", "is", "None", ":", "log", ".", "debug", "(", "'Not authenticated yet, doing that now..'", ")", ...
Execute the HTTP request to the API
[ "Execute", "the", "HTTP", "request", "to", "the", "API" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/proxmox.py#L149-L196
train
saltstack/salt
salt/cloud/clouds/proxmox.py
_get_vm_by_name
def _get_vm_by_name(name, allDetails=False): ''' Since Proxmox works based op id's rather than names as identifiers this requires some filtering to retrieve the required information. ''' vms = get_resources_vms(includeConfig=allDetails) if name in vms: return vms[name] log.info('VM with name "%s" could not be found.', name) return False
python
def _get_vm_by_name(name, allDetails=False): ''' Since Proxmox works based op id's rather than names as identifiers this requires some filtering to retrieve the required information. ''' vms = get_resources_vms(includeConfig=allDetails) if name in vms: return vms[name] log.info('VM with name "%s" could not be found.', name) return False
[ "def", "_get_vm_by_name", "(", "name", ",", "allDetails", "=", "False", ")", ":", "vms", "=", "get_resources_vms", "(", "includeConfig", "=", "allDetails", ")", "if", "name", "in", "vms", ":", "return", "vms", "[", "name", "]", "log", ".", "info", "(", ...
Since Proxmox works based op id's rather than names as identifiers this requires some filtering to retrieve the required information.
[ "Since", "Proxmox", "works", "based", "op", "id", "s", "rather", "than", "names", "as", "identifiers", "this", "requires", "some", "filtering", "to", "retrieve", "the", "required", "information", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/proxmox.py#L199-L209
train
saltstack/salt
salt/cloud/clouds/proxmox.py
_get_vm_by_id
def _get_vm_by_id(vmid, allDetails=False): ''' Retrieve a VM based on the ID. ''' for vm_name, vm_details in six.iteritems(get_resources_vms(includeConfig=allDetails)): if six.text_type(vm_details['vmid']) == six.text_type(vmid): return vm_details log.info('VM with ID "%s" could not be found.', vmid) return False
python
def _get_vm_by_id(vmid, allDetails=False): ''' Retrieve a VM based on the ID. ''' for vm_name, vm_details in six.iteritems(get_resources_vms(includeConfig=allDetails)): if six.text_type(vm_details['vmid']) == six.text_type(vmid): return vm_details log.info('VM with ID "%s" could not be found.', vmid) return False
[ "def", "_get_vm_by_id", "(", "vmid", ",", "allDetails", "=", "False", ")", ":", "for", "vm_name", ",", "vm_details", "in", "six", ".", "iteritems", "(", "get_resources_vms", "(", "includeConfig", "=", "allDetails", ")", ")", ":", "if", "six", ".", "text_ty...
Retrieve a VM based on the ID.
[ "Retrieve", "a", "VM", "based", "on", "the", "ID", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/proxmox.py#L212-L221
train
saltstack/salt
salt/cloud/clouds/proxmox.py
_check_ip_available
def _check_ip_available(ip_addr): ''' Proxmox VMs refuse to start when the IP is already being used. This function can be used to prevent VMs being created with duplicate IP's or to generate a warning. ''' for vm_name, vm_details in six.iteritems(get_resources_vms(includeConfig=True)): vm_config = vm_details['config'] if ip_addr in vm_config['ip_address'] or vm_config['ip_address'] == ip_addr: log.debug('IP "%s" is already defined', ip_addr) return False log.debug('IP \'%s\' is available to be defined', ip_addr) return True
python
def _check_ip_available(ip_addr): ''' Proxmox VMs refuse to start when the IP is already being used. This function can be used to prevent VMs being created with duplicate IP's or to generate a warning. ''' for vm_name, vm_details in six.iteritems(get_resources_vms(includeConfig=True)): vm_config = vm_details['config'] if ip_addr in vm_config['ip_address'] or vm_config['ip_address'] == ip_addr: log.debug('IP "%s" is already defined', ip_addr) return False log.debug('IP \'%s\' is available to be defined', ip_addr) return True
[ "def", "_check_ip_available", "(", "ip_addr", ")", ":", "for", "vm_name", ",", "vm_details", "in", "six", ".", "iteritems", "(", "get_resources_vms", "(", "includeConfig", "=", "True", ")", ")", ":", "vm_config", "=", "vm_details", "[", "'config'", "]", "if"...
Proxmox VMs refuse to start when the IP is already being used. This function can be used to prevent VMs being created with duplicate IP's or to generate a warning.
[ "Proxmox", "VMs", "refuse", "to", "start", "when", "the", "IP", "is", "already", "being", "used", ".", "This", "function", "can", "be", "used", "to", "prevent", "VMs", "being", "created", "with", "duplicate", "IP", "s", "or", "to", "generate", "a", "warn...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/proxmox.py#L232-L245
train
saltstack/salt
salt/cloud/clouds/proxmox.py
_parse_proxmox_upid
def _parse_proxmox_upid(node, vm_=None): ''' Upon requesting a task that runs for a longer period of time a UPID is given. This includes information about the job and can be used to lookup information in the log. ''' ret = {} upid = node # Parse node response node = node.split(':') if node[0] == 'UPID': ret['node'] = six.text_type(node[1]) ret['pid'] = six.text_type(node[2]) ret['pstart'] = six.text_type(node[3]) ret['starttime'] = six.text_type(node[4]) ret['type'] = six.text_type(node[5]) ret['vmid'] = six.text_type(node[6]) ret['user'] = six.text_type(node[7]) # include the upid again in case we'll need it again ret['upid'] = six.text_type(upid) if vm_ is not None and 'technology' in vm_: ret['technology'] = six.text_type(vm_['technology']) return ret
python
def _parse_proxmox_upid(node, vm_=None): ''' Upon requesting a task that runs for a longer period of time a UPID is given. This includes information about the job and can be used to lookup information in the log. ''' ret = {} upid = node # Parse node response node = node.split(':') if node[0] == 'UPID': ret['node'] = six.text_type(node[1]) ret['pid'] = six.text_type(node[2]) ret['pstart'] = six.text_type(node[3]) ret['starttime'] = six.text_type(node[4]) ret['type'] = six.text_type(node[5]) ret['vmid'] = six.text_type(node[6]) ret['user'] = six.text_type(node[7]) # include the upid again in case we'll need it again ret['upid'] = six.text_type(upid) if vm_ is not None and 'technology' in vm_: ret['technology'] = six.text_type(vm_['technology']) return ret
[ "def", "_parse_proxmox_upid", "(", "node", ",", "vm_", "=", "None", ")", ":", "ret", "=", "{", "}", "upid", "=", "node", "# Parse node response", "node", "=", "node", ".", "split", "(", "':'", ")", "if", "node", "[", "0", "]", "==", "'UPID'", ":", ...
Upon requesting a task that runs for a longer period of time a UPID is given. This includes information about the job and can be used to lookup information in the log.
[ "Upon", "requesting", "a", "task", "that", "runs", "for", "a", "longer", "period", "of", "time", "a", "UPID", "is", "given", ".", "This", "includes", "information", "about", "the", "job", "and", "can", "be", "used", "to", "lookup", "information", "in", "...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/proxmox.py#L248-L272
train
saltstack/salt
salt/cloud/clouds/proxmox.py
_lookup_proxmox_task
def _lookup_proxmox_task(upid): ''' Retrieve the (latest) logs and retrieve the status for a UPID. This can be used to verify whether a task has completed. ''' log.debug('Getting creation status for upid: %s', upid) tasks = query('get', 'cluster/tasks') if tasks: for task in tasks: if task['upid'] == upid: log.debug('Found upid task: %s', task) return task return False
python
def _lookup_proxmox_task(upid): ''' Retrieve the (latest) logs and retrieve the status for a UPID. This can be used to verify whether a task has completed. ''' log.debug('Getting creation status for upid: %s', upid) tasks = query('get', 'cluster/tasks') if tasks: for task in tasks: if task['upid'] == upid: log.debug('Found upid task: %s', task) return task return False
[ "def", "_lookup_proxmox_task", "(", "upid", ")", ":", "log", ".", "debug", "(", "'Getting creation status for upid: %s'", ",", "upid", ")", "tasks", "=", "query", "(", "'get'", ",", "'cluster/tasks'", ")", "if", "tasks", ":", "for", "task", "in", "tasks", ":...
Retrieve the (latest) logs and retrieve the status for a UPID. This can be used to verify whether a task has completed.
[ "Retrieve", "the", "(", "latest", ")", "logs", "and", "retrieve", "the", "status", "for", "a", "UPID", ".", "This", "can", "be", "used", "to", "verify", "whether", "a", "task", "has", "completed", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/proxmox.py#L275-L289
train
saltstack/salt
salt/cloud/clouds/proxmox.py
get_resources_nodes
def get_resources_nodes(call=None, resFilter=None): ''' Retrieve all hypervisors (nodes) available on this environment CLI Example: .. code-block:: bash salt-cloud -f get_resources_nodes my-proxmox-config ''' log.debug('Getting resource: nodes.. (filter: %s)', resFilter) resources = query('get', 'cluster/resources') ret = {} for resource in resources: if 'type' in resource and resource['type'] == 'node': name = resource['node'] ret[name] = resource if resFilter is not None: log.debug('Filter given: %s, returning requested ' 'resource: nodes', resFilter) return ret[resFilter] log.debug('Filter not given: %s, returning all resource: nodes', ret) return ret
python
def get_resources_nodes(call=None, resFilter=None): ''' Retrieve all hypervisors (nodes) available on this environment CLI Example: .. code-block:: bash salt-cloud -f get_resources_nodes my-proxmox-config ''' log.debug('Getting resource: nodes.. (filter: %s)', resFilter) resources = query('get', 'cluster/resources') ret = {} for resource in resources: if 'type' in resource and resource['type'] == 'node': name = resource['node'] ret[name] = resource if resFilter is not None: log.debug('Filter given: %s, returning requested ' 'resource: nodes', resFilter) return ret[resFilter] log.debug('Filter not given: %s, returning all resource: nodes', ret) return ret
[ "def", "get_resources_nodes", "(", "call", "=", "None", ",", "resFilter", "=", "None", ")", ":", "log", ".", "debug", "(", "'Getting resource: nodes.. (filter: %s)'", ",", "resFilter", ")", "resources", "=", "query", "(", "'get'", ",", "'cluster/resources'", ")"...
Retrieve all hypervisors (nodes) available on this environment CLI Example: .. code-block:: bash salt-cloud -f get_resources_nodes my-proxmox-config
[ "Retrieve", "all", "hypervisors", "(", "nodes", ")", "available", "on", "this", "environment", "CLI", "Example", ":" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/proxmox.py#L292-L316
train
saltstack/salt
salt/cloud/clouds/proxmox.py
get_resources_vms
def get_resources_vms(call=None, resFilter=None, includeConfig=True): ''' Retrieve all VMs available on this environment CLI Example: .. code-block:: bash salt-cloud -f get_resources_vms my-proxmox-config ''' timeoutTime = time.time() + 60 while True: log.debug('Getting resource: vms.. (filter: %s)', resFilter) resources = query('get', 'cluster/resources') ret = {} badResource = False for resource in resources: if 'type' in resource and resource['type'] in ['openvz', 'qemu', 'lxc']: try: name = resource['name'] except KeyError: badResource = True log.debug('No name in VM resource %s', repr(resource)) break ret[name] = resource if includeConfig: # Requested to include the detailed configuration of a VM ret[name]['config'] = get_vmconfig( ret[name]['vmid'], ret[name]['node'], ret[name]['type'] ) if time.time() > timeoutTime: raise SaltCloudExecutionTimeout('FAILED to get the proxmox ' 'resources vms') # Carry on if there wasn't a bad resource return from Proxmox if not badResource: break time.sleep(0.5) if resFilter is not None: log.debug('Filter given: %s, returning requested ' 'resource: nodes', resFilter) return ret[resFilter] log.debug('Filter not given: %s, returning all resource: nodes', ret) return ret
python
def get_resources_vms(call=None, resFilter=None, includeConfig=True): ''' Retrieve all VMs available on this environment CLI Example: .. code-block:: bash salt-cloud -f get_resources_vms my-proxmox-config ''' timeoutTime = time.time() + 60 while True: log.debug('Getting resource: vms.. (filter: %s)', resFilter) resources = query('get', 'cluster/resources') ret = {} badResource = False for resource in resources: if 'type' in resource and resource['type'] in ['openvz', 'qemu', 'lxc']: try: name = resource['name'] except KeyError: badResource = True log.debug('No name in VM resource %s', repr(resource)) break ret[name] = resource if includeConfig: # Requested to include the detailed configuration of a VM ret[name]['config'] = get_vmconfig( ret[name]['vmid'], ret[name]['node'], ret[name]['type'] ) if time.time() > timeoutTime: raise SaltCloudExecutionTimeout('FAILED to get the proxmox ' 'resources vms') # Carry on if there wasn't a bad resource return from Proxmox if not badResource: break time.sleep(0.5) if resFilter is not None: log.debug('Filter given: %s, returning requested ' 'resource: nodes', resFilter) return ret[resFilter] log.debug('Filter not given: %s, returning all resource: nodes', ret) return ret
[ "def", "get_resources_vms", "(", "call", "=", "None", ",", "resFilter", "=", "None", ",", "includeConfig", "=", "True", ")", ":", "timeoutTime", "=", "time", ".", "time", "(", ")", "+", "60", "while", "True", ":", "log", ".", "debug", "(", "'Getting re...
Retrieve all VMs available on this environment CLI Example: .. code-block:: bash salt-cloud -f get_resources_vms my-proxmox-config
[ "Retrieve", "all", "VMs", "available", "on", "this", "environment" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/proxmox.py#L319-L372
train
saltstack/salt
salt/cloud/clouds/proxmox.py
script
def script(vm_): ''' Return the script deployment object ''' script_name = config.get_cloud_config_value('script', vm_, __opts__) if not script_name: script_name = 'bootstrap-salt' return salt.utils.cloud.os_script( script_name, vm_, __opts__, salt.utils.cloud.salt_config_to_yaml( salt.utils.cloud.minion_config(__opts__, vm_) ) )
python
def script(vm_): ''' Return the script deployment object ''' script_name = config.get_cloud_config_value('script', vm_, __opts__) if not script_name: script_name = 'bootstrap-salt' return salt.utils.cloud.os_script( script_name, vm_, __opts__, salt.utils.cloud.salt_config_to_yaml( salt.utils.cloud.minion_config(__opts__, vm_) ) )
[ "def", "script", "(", "vm_", ")", ":", "script_name", "=", "config", ".", "get_cloud_config_value", "(", "'script'", ",", "vm_", ",", "__opts__", ")", "if", "not", "script_name", ":", "script_name", "=", "'bootstrap-salt'", "return", "salt", ".", "utils", "....
Return the script deployment object
[ "Return", "the", "script", "deployment", "object" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/proxmox.py#L375-L390
train
saltstack/salt
salt/cloud/clouds/proxmox.py
avail_locations
def avail_locations(call=None): ''' Return a list of the hypervisors (nodes) which this Proxmox PVE machine manages CLI Example: .. code-block:: bash salt-cloud --list-locations my-proxmox-config ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option' ) # could also use the get_resources_nodes but speed is ~the same nodes = query('get', 'nodes') ret = {} for node in nodes: name = node['node'] ret[name] = node return ret
python
def avail_locations(call=None): ''' Return a list of the hypervisors (nodes) which this Proxmox PVE machine manages CLI Example: .. code-block:: bash salt-cloud --list-locations my-proxmox-config ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option' ) # could also use the get_resources_nodes but speed is ~the same nodes = query('get', 'nodes') ret = {} for node in nodes: name = node['node'] ret[name] = node return ret
[ "def", "avail_locations", "(", "call", "=", "None", ")", ":", "if", "call", "==", "'action'", ":", "raise", "SaltCloudSystemExit", "(", "'The avail_locations function must be called with '", "'-f or --function, or with the --list-locations option'", ")", "# could also use the g...
Return a list of the hypervisors (nodes) which this Proxmox PVE machine manages CLI Example: .. code-block:: bash salt-cloud --list-locations my-proxmox-config
[ "Return", "a", "list", "of", "the", "hypervisors", "(", "nodes", ")", "which", "this", "Proxmox", "PVE", "machine", "manages" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/proxmox.py#L393-L417
train
saltstack/salt
salt/cloud/clouds/proxmox.py
avail_images
def avail_images(call=None, location='local'): ''' Return a list of the images that are on the provider CLI Example: .. code-block:: bash salt-cloud --list-images my-proxmox-config ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) ret = {} for host_name, host_details in six.iteritems(avail_locations()): for item in query('get', 'nodes/{0}/storage/{1}/content'.format(host_name, location)): ret[item['volid']] = item return ret
python
def avail_images(call=None, location='local'): ''' Return a list of the images that are on the provider CLI Example: .. code-block:: bash salt-cloud --list-images my-proxmox-config ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) ret = {} for host_name, host_details in six.iteritems(avail_locations()): for item in query('get', 'nodes/{0}/storage/{1}/content'.format(host_name, location)): ret[item['volid']] = item return ret
[ "def", "avail_images", "(", "call", "=", "None", ",", "location", "=", "'local'", ")", ":", "if", "call", "==", "'action'", ":", "raise", "SaltCloudSystemExit", "(", "'The avail_images function must be called with '", "'-f or --function, or with the --list-images option'", ...
Return a list of the images that are on the provider CLI Example: .. code-block:: bash salt-cloud --list-images my-proxmox-config
[ "Return", "a", "list", "of", "the", "images", "that", "are", "on", "the", "provider" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/proxmox.py#L420-L440
train
saltstack/salt
salt/cloud/clouds/proxmox.py
list_nodes
def list_nodes(call=None): ''' Return a list of the VMs that are managed by the provider CLI Example: .. code-block:: bash salt-cloud -Q my-proxmox-config ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) ret = {} for vm_name, vm_details in six.iteritems(get_resources_vms(includeConfig=True)): log.debug('VM_Name: %s', vm_name) log.debug('vm_details: %s', vm_details) # Limit resultset on what Salt-cloud demands: ret[vm_name] = {} ret[vm_name]['id'] = six.text_type(vm_details['vmid']) ret[vm_name]['image'] = six.text_type(vm_details['vmid']) ret[vm_name]['size'] = six.text_type(vm_details['disk']) ret[vm_name]['state'] = six.text_type(vm_details['status']) # Figure out which is which to put it in the right column private_ips = [] public_ips = [] if 'ip_address' in vm_details['config'] and vm_details['config']['ip_address'] != '-': ips = vm_details['config']['ip_address'].split(' ') for ip_ in ips: if IP(ip_).iptype() == 'PRIVATE': private_ips.append(six.text_type(ip_)) else: public_ips.append(six.text_type(ip_)) ret[vm_name]['private_ips'] = private_ips ret[vm_name]['public_ips'] = public_ips return ret
python
def list_nodes(call=None): ''' Return a list of the VMs that are managed by the provider CLI Example: .. code-block:: bash salt-cloud -Q my-proxmox-config ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) ret = {} for vm_name, vm_details in six.iteritems(get_resources_vms(includeConfig=True)): log.debug('VM_Name: %s', vm_name) log.debug('vm_details: %s', vm_details) # Limit resultset on what Salt-cloud demands: ret[vm_name] = {} ret[vm_name]['id'] = six.text_type(vm_details['vmid']) ret[vm_name]['image'] = six.text_type(vm_details['vmid']) ret[vm_name]['size'] = six.text_type(vm_details['disk']) ret[vm_name]['state'] = six.text_type(vm_details['status']) # Figure out which is which to put it in the right column private_ips = [] public_ips = [] if 'ip_address' in vm_details['config'] and vm_details['config']['ip_address'] != '-': ips = vm_details['config']['ip_address'].split(' ') for ip_ in ips: if IP(ip_).iptype() == 'PRIVATE': private_ips.append(six.text_type(ip_)) else: public_ips.append(six.text_type(ip_)) ret[vm_name]['private_ips'] = private_ips ret[vm_name]['public_ips'] = public_ips return ret
[ "def", "list_nodes", "(", "call", "=", "None", ")", ":", "if", "call", "==", "'action'", ":", "raise", "SaltCloudSystemExit", "(", "'The list_nodes function must be called with -f or --function.'", ")", "ret", "=", "{", "}", "for", "vm_name", ",", "vm_details", "i...
Return a list of the VMs that are managed by the provider CLI Example: .. code-block:: bash salt-cloud -Q my-proxmox-config
[ "Return", "a", "list", "of", "the", "VMs", "that", "are", "managed", "by", "the", "provider" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/proxmox.py#L443-L485
train
saltstack/salt
salt/cloud/clouds/proxmox.py
_stringlist_to_dictionary
def _stringlist_to_dictionary(input_string): ''' Convert a stringlist (comma separated settings) to a dictionary The result of the string setting1=value1,setting2=value2 will be a python dictionary: {'setting1':'value1','setting2':'value2'} ''' li = str(input_string).split(',') ret = {} for item in li: pair = str(item).replace(' ', '').split('=') if len(pair) != 2: log.warning('Cannot process stringlist item %s', item) continue ret[pair[0]] = pair[1] return ret
python
def _stringlist_to_dictionary(input_string): ''' Convert a stringlist (comma separated settings) to a dictionary The result of the string setting1=value1,setting2=value2 will be a python dictionary: {'setting1':'value1','setting2':'value2'} ''' li = str(input_string).split(',') ret = {} for item in li: pair = str(item).replace(' ', '').split('=') if len(pair) != 2: log.warning('Cannot process stringlist item %s', item) continue ret[pair[0]] = pair[1] return ret
[ "def", "_stringlist_to_dictionary", "(", "input_string", ")", ":", "li", "=", "str", "(", "input_string", ")", ".", "split", "(", "','", ")", "ret", "=", "{", "}", "for", "item", "in", "li", ":", "pair", "=", "str", "(", "item", ")", ".", "replace", ...
Convert a stringlist (comma separated settings) to a dictionary The result of the string setting1=value1,setting2=value2 will be a python dictionary: {'setting1':'value1','setting2':'value2'}
[ "Convert", "a", "stringlist", "(", "comma", "separated", "settings", ")", "to", "a", "dictionary" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/proxmox.py#L521-L538
train
saltstack/salt
salt/cloud/clouds/proxmox.py
_dictionary_to_stringlist
def _dictionary_to_stringlist(input_dict): ''' Convert a dictionary to a stringlist (comma separated settings) The result of the dictionary {'setting1':'value1','setting2':'value2'} will be: setting1=value1,setting2=value2 ''' string_value = "" for s in input_dict: string_value += "{0}={1},".format(s, input_dict[s]) string_value = string_value[:-1] return string_value
python
def _dictionary_to_stringlist(input_dict): ''' Convert a dictionary to a stringlist (comma separated settings) The result of the dictionary {'setting1':'value1','setting2':'value2'} will be: setting1=value1,setting2=value2 ''' string_value = "" for s in input_dict: string_value += "{0}={1},".format(s, input_dict[s]) string_value = string_value[:-1] return string_value
[ "def", "_dictionary_to_stringlist", "(", "input_dict", ")", ":", "string_value", "=", "\"\"", "for", "s", "in", "input_dict", ":", "string_value", "+=", "\"{0}={1},\"", ".", "format", "(", "s", ",", "input_dict", "[", "s", "]", ")", "string_value", "=", "str...
Convert a dictionary to a stringlist (comma separated settings) The result of the dictionary {'setting1':'value1','setting2':'value2'} will be: setting1=value1,setting2=value2
[ "Convert", "a", "dictionary", "to", "a", "stringlist", "(", "comma", "separated", "settings", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/proxmox.py#L541-L553
train
saltstack/salt
salt/cloud/clouds/proxmox.py
create
def create(vm_): ''' Create a single VM from a data dict CLI Example: .. code-block:: bash salt-cloud -p proxmox-ubuntu vmhostname ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'proxmox', vm_['profile'], vm_=vm_) is False: return False except AttributeError: pass ret = {} __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']( 'creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) if 'use_dns' in vm_ and 'ip_address' not in vm_: use_dns = vm_['use_dns'] if use_dns: from socket import gethostbyname, gaierror try: ip_address = gethostbyname(six.text_type(vm_['name'])) except gaierror: log.debug('Resolving of %s failed', vm_['name']) else: vm_['ip_address'] = six.text_type(ip_address) try: newid = _get_next_vmid() data = create_node(vm_, newid) except Exception as exc: log.error( 'Error creating %s on PROXMOX\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: \n%s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False ret['creation_data'] = data name = vm_['name'] # hostname which we know if 'clone' in vm_ and vm_['clone'] is True: vmid = newid else: vmid = data['vmid'] # vmid which we have received host = data['node'] # host which we have received nodeType = data['technology'] # VM tech (Qemu / OpenVZ) if 'agent_get_ip' not in vm_ or vm_['agent_get_ip'] == 0: # Determine which IP to use in order of preference: if 'ip_address' in vm_: ip_address = six.text_type(vm_['ip_address']) elif 'public_ips' in data: ip_address = six.text_type(data['public_ips'][0]) # first IP elif 'private_ips' in data: ip_address = six.text_type(data['private_ips'][0]) # first IP else: raise SaltCloudExecutionFailure("Could not determine an IP address to use") # wait until the vm has been created so we can start it if not wait_for_created(data['upid'], timeout=300): return {'Error': 'Unable to create {0}, command timed out'.format(name)} if 'clone' in vm_ and vm_['clone'] is True and vm_['technology'] == 'qemu': # If we cloned a machine, see if we need to reconfigure any of the options such as net0, # ide2, etc. This enables us to have a different cloud-init ISO mounted for each VM that's # brought up log.info('Configuring cloned VM') # Modify the settings for the VM one at a time so we can see any problems with the values # as quickly as possible for setting in 'sockets', 'cores', 'cpulimit', 'memory', 'onboot', 'agent': if setting in vm_: # if the property is set, use it for the VM request postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) # cloud-init settings for setting in 'ciuser', 'cipassword', 'sshkeys', 'nameserver', 'searchdomain': if setting in vm_: # if the property is set, use it for the VM request postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) for setting_number in range(3): setting = 'ide{0}'.format(setting_number) if setting in vm_: postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) for setting_number in range(5): setting = 'sata{0}'.format(setting_number) if setting in vm_: vm_config = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid)) if setting in vm_config: setting_params = vm_[setting] setting_storage = setting_params.split(':')[0] setting_size = _stringlist_to_dictionary(setting_params)['size'] vm_disk_params = vm_config[setting] vm_disk_storage = vm_disk_params.split(':')[0] vm_disk_size = _stringlist_to_dictionary(vm_disk_params)['size'] # if storage is different, move the disk if setting_storage != vm_disk_storage: postParams = {} postParams['disk'] = setting postParams['storage'] = setting_storage postParams['delete'] = 1 node = query('post', 'nodes/{0}/qemu/{1}/move_disk'.format( vm_['host'], vmid), postParams) data = _parse_proxmox_upid(node, vm_) # wait until the disk has been moved if not wait_for_task(data['upid'], timeout=300): return {'Error': 'Unable to move disk {0}, command timed out'.format( setting)} # if storage is different, move the disk if setting_size != vm_disk_size: postParams = {} postParams['disk'] = setting postParams['size'] = setting_size query('put', 'nodes/{0}/qemu/{1}/resize'.format( vm_['host'], vmid), postParams) else: postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) for setting_number in range(13): setting = 'scsi{0}'.format(setting_number) if setting in vm_: vm_config = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid)) if setting in vm_config: setting_params = vm_[setting] setting_storage = setting_params.split(':')[0] setting_size = _stringlist_to_dictionary(setting_params)['size'] vm_disk_params = vm_config[setting] vm_disk_storage = vm_disk_params.split(':')[0] vm_disk_size = _stringlist_to_dictionary(vm_disk_params)['size'] # if storage is different, move the disk if setting_storage != vm_disk_storage: postParams = {} postParams['disk'] = setting postParams['storage'] = setting_storage postParams['delete'] = 1 node = query('post', 'nodes/{0}/qemu/{1}/move_disk'.format( vm_['host'], vmid), postParams) data = _parse_proxmox_upid(node, vm_) # wait until the disk has been moved if not wait_for_task(data['upid'], timeout=300): return {'Error': 'Unable to move disk {0}, command timed out'.format( setting)} # if storage is different, move the disk if setting_size != vm_disk_size: postParams = {} postParams['disk'] = setting postParams['size'] = setting_size query('put', 'nodes/{0}/qemu/{1}/resize'.format( vm_['host'], vmid), postParams) else: postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) # net strings are a list of comma seperated settings. We need to merge the settings so that # the setting in the profile only changes the settings it touches and the other settings # are left alone. An example of why this is necessary is because the MAC address is set # in here and generally you don't want to alter or have to know the MAC address of the new # instance, but you may want to set the VLAN bridge for example for setting_number in range(20): setting = 'net{0}'.format(setting_number) if setting in vm_: data = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid)) # Generate a dictionary of settings from the existing string new_setting = {} if setting in data: new_setting.update(_stringlist_to_dictionary(data[setting])) # Merge the new settings (as a dictionary) into the existing dictionary to get the # new merged settings new_setting.update(_stringlist_to_dictionary(vm_[setting])) # Convert the dictionary back into a string list postParams = {setting: _dictionary_to_stringlist(new_setting)} query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) for setting_number in range(20): setting = 'ipconfig{0}'.format(setting_number) if setting in vm_: data = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid)) # Generate a dictionary of settings from the existing string new_setting = {} if setting in data: new_setting.update(_stringlist_to_dictionary(data[setting])) # Merge the new settings (as a dictionary) into the existing dictionary to get the # new merged settings if setting_number == 0 and 'ip_address' in vm_: if 'gw' in _stringlist_to_dictionary(vm_[setting]): new_setting.update(_stringlist_to_dictionary( 'ip={0}/24,gw={1}'.format( vm_['ip_address'], _stringlist_to_dictionary(vm_[setting])['gw']))) else: new_setting.update( _stringlist_to_dictionary('ip={0}/24'.format(vm_['ip_address']))) else: new_setting.update(_stringlist_to_dictionary(vm_[setting])) # Convert the dictionary back into a string list postParams = {setting: _dictionary_to_stringlist(new_setting)} query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) # VM has been created. Starting.. if not start(name, vmid, call='action'): log.error('Node %s (%s) failed to start!', name, vmid) raise SaltCloudExecutionFailure # Wait until the VM has fully started log.debug('Waiting for state "running" for vm %s on %s', vmid, host) if not wait_for_state(vmid, 'running'): return {'Error': 'Unable to start {0}, command timed out'.format(name)} # For QEMU VMs, we can get the IP Address from qemu-agent if 'agent_get_ip' in vm_ and vm_['agent_get_ip'] == 1: def __find_agent_ip(vm_): log.debug("Waiting for qemu-agent to start...") endpoint = 'nodes/{0}/qemu/{1}/agent/network-get-interfaces'.format(vm_['host'], vmid) interfaces = query('get', endpoint) # If we get a result from the agent, parse it if 'result' in interfaces: for interface in interfaces['result']: if_name = interface['name'] # Only check ethernet type interfaces, as they are not returned in any order if if_name.startswith('eth') or if_name.startswith('ens'): for if_addr in interface['ip-addresses']: ip_addr = if_addr['ip-address'] # Ensure interface has a valid IPv4 address if if_addr['ip-address-type'] == 'ipv4' and ip_addr is not None: return six.text_type(ip_addr) raise SaltCloudExecutionFailure # We have to wait for a bit for qemu-agent to start try: ip_address = __utils__['cloud.wait_for_fun']( __find_agent_ip, vm_=vm_ ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # If VM was created but we can't connect, destroy it. destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) log.debug('Using IP address %s', ip_address) ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) ssh_password = config.get_cloud_config_value( 'password', vm_, __opts__, ) ret['ip_address'] = ip_address ret['username'] = ssh_username ret['password'] = ssh_password vm_['ssh_host'] = ip_address vm_['password'] = ssh_password ret = __utils__['cloud.bootstrap'](vm_, __opts__) # Report success! log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']( 'created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret
python
def create(vm_): ''' Create a single VM from a data dict CLI Example: .. code-block:: bash salt-cloud -p proxmox-ubuntu vmhostname ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'proxmox', vm_['profile'], vm_=vm_) is False: return False except AttributeError: pass ret = {} __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']( 'creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) if 'use_dns' in vm_ and 'ip_address' not in vm_: use_dns = vm_['use_dns'] if use_dns: from socket import gethostbyname, gaierror try: ip_address = gethostbyname(six.text_type(vm_['name'])) except gaierror: log.debug('Resolving of %s failed', vm_['name']) else: vm_['ip_address'] = six.text_type(ip_address) try: newid = _get_next_vmid() data = create_node(vm_, newid) except Exception as exc: log.error( 'Error creating %s on PROXMOX\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: \n%s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False ret['creation_data'] = data name = vm_['name'] # hostname which we know if 'clone' in vm_ and vm_['clone'] is True: vmid = newid else: vmid = data['vmid'] # vmid which we have received host = data['node'] # host which we have received nodeType = data['technology'] # VM tech (Qemu / OpenVZ) if 'agent_get_ip' not in vm_ or vm_['agent_get_ip'] == 0: # Determine which IP to use in order of preference: if 'ip_address' in vm_: ip_address = six.text_type(vm_['ip_address']) elif 'public_ips' in data: ip_address = six.text_type(data['public_ips'][0]) # first IP elif 'private_ips' in data: ip_address = six.text_type(data['private_ips'][0]) # first IP else: raise SaltCloudExecutionFailure("Could not determine an IP address to use") # wait until the vm has been created so we can start it if not wait_for_created(data['upid'], timeout=300): return {'Error': 'Unable to create {0}, command timed out'.format(name)} if 'clone' in vm_ and vm_['clone'] is True and vm_['technology'] == 'qemu': # If we cloned a machine, see if we need to reconfigure any of the options such as net0, # ide2, etc. This enables us to have a different cloud-init ISO mounted for each VM that's # brought up log.info('Configuring cloned VM') # Modify the settings for the VM one at a time so we can see any problems with the values # as quickly as possible for setting in 'sockets', 'cores', 'cpulimit', 'memory', 'onboot', 'agent': if setting in vm_: # if the property is set, use it for the VM request postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) # cloud-init settings for setting in 'ciuser', 'cipassword', 'sshkeys', 'nameserver', 'searchdomain': if setting in vm_: # if the property is set, use it for the VM request postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) for setting_number in range(3): setting = 'ide{0}'.format(setting_number) if setting in vm_: postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) for setting_number in range(5): setting = 'sata{0}'.format(setting_number) if setting in vm_: vm_config = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid)) if setting in vm_config: setting_params = vm_[setting] setting_storage = setting_params.split(':')[0] setting_size = _stringlist_to_dictionary(setting_params)['size'] vm_disk_params = vm_config[setting] vm_disk_storage = vm_disk_params.split(':')[0] vm_disk_size = _stringlist_to_dictionary(vm_disk_params)['size'] # if storage is different, move the disk if setting_storage != vm_disk_storage: postParams = {} postParams['disk'] = setting postParams['storage'] = setting_storage postParams['delete'] = 1 node = query('post', 'nodes/{0}/qemu/{1}/move_disk'.format( vm_['host'], vmid), postParams) data = _parse_proxmox_upid(node, vm_) # wait until the disk has been moved if not wait_for_task(data['upid'], timeout=300): return {'Error': 'Unable to move disk {0}, command timed out'.format( setting)} # if storage is different, move the disk if setting_size != vm_disk_size: postParams = {} postParams['disk'] = setting postParams['size'] = setting_size query('put', 'nodes/{0}/qemu/{1}/resize'.format( vm_['host'], vmid), postParams) else: postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) for setting_number in range(13): setting = 'scsi{0}'.format(setting_number) if setting in vm_: vm_config = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid)) if setting in vm_config: setting_params = vm_[setting] setting_storage = setting_params.split(':')[0] setting_size = _stringlist_to_dictionary(setting_params)['size'] vm_disk_params = vm_config[setting] vm_disk_storage = vm_disk_params.split(':')[0] vm_disk_size = _stringlist_to_dictionary(vm_disk_params)['size'] # if storage is different, move the disk if setting_storage != vm_disk_storage: postParams = {} postParams['disk'] = setting postParams['storage'] = setting_storage postParams['delete'] = 1 node = query('post', 'nodes/{0}/qemu/{1}/move_disk'.format( vm_['host'], vmid), postParams) data = _parse_proxmox_upid(node, vm_) # wait until the disk has been moved if not wait_for_task(data['upid'], timeout=300): return {'Error': 'Unable to move disk {0}, command timed out'.format( setting)} # if storage is different, move the disk if setting_size != vm_disk_size: postParams = {} postParams['disk'] = setting postParams['size'] = setting_size query('put', 'nodes/{0}/qemu/{1}/resize'.format( vm_['host'], vmid), postParams) else: postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) # net strings are a list of comma seperated settings. We need to merge the settings so that # the setting in the profile only changes the settings it touches and the other settings # are left alone. An example of why this is necessary is because the MAC address is set # in here and generally you don't want to alter or have to know the MAC address of the new # instance, but you may want to set the VLAN bridge for example for setting_number in range(20): setting = 'net{0}'.format(setting_number) if setting in vm_: data = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid)) # Generate a dictionary of settings from the existing string new_setting = {} if setting in data: new_setting.update(_stringlist_to_dictionary(data[setting])) # Merge the new settings (as a dictionary) into the existing dictionary to get the # new merged settings new_setting.update(_stringlist_to_dictionary(vm_[setting])) # Convert the dictionary back into a string list postParams = {setting: _dictionary_to_stringlist(new_setting)} query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) for setting_number in range(20): setting = 'ipconfig{0}'.format(setting_number) if setting in vm_: data = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid)) # Generate a dictionary of settings from the existing string new_setting = {} if setting in data: new_setting.update(_stringlist_to_dictionary(data[setting])) # Merge the new settings (as a dictionary) into the existing dictionary to get the # new merged settings if setting_number == 0 and 'ip_address' in vm_: if 'gw' in _stringlist_to_dictionary(vm_[setting]): new_setting.update(_stringlist_to_dictionary( 'ip={0}/24,gw={1}'.format( vm_['ip_address'], _stringlist_to_dictionary(vm_[setting])['gw']))) else: new_setting.update( _stringlist_to_dictionary('ip={0}/24'.format(vm_['ip_address']))) else: new_setting.update(_stringlist_to_dictionary(vm_[setting])) # Convert the dictionary back into a string list postParams = {setting: _dictionary_to_stringlist(new_setting)} query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) # VM has been created. Starting.. if not start(name, vmid, call='action'): log.error('Node %s (%s) failed to start!', name, vmid) raise SaltCloudExecutionFailure # Wait until the VM has fully started log.debug('Waiting for state "running" for vm %s on %s', vmid, host) if not wait_for_state(vmid, 'running'): return {'Error': 'Unable to start {0}, command timed out'.format(name)} # For QEMU VMs, we can get the IP Address from qemu-agent if 'agent_get_ip' in vm_ and vm_['agent_get_ip'] == 1: def __find_agent_ip(vm_): log.debug("Waiting for qemu-agent to start...") endpoint = 'nodes/{0}/qemu/{1}/agent/network-get-interfaces'.format(vm_['host'], vmid) interfaces = query('get', endpoint) # If we get a result from the agent, parse it if 'result' in interfaces: for interface in interfaces['result']: if_name = interface['name'] # Only check ethernet type interfaces, as they are not returned in any order if if_name.startswith('eth') or if_name.startswith('ens'): for if_addr in interface['ip-addresses']: ip_addr = if_addr['ip-address'] # Ensure interface has a valid IPv4 address if if_addr['ip-address-type'] == 'ipv4' and ip_addr is not None: return six.text_type(ip_addr) raise SaltCloudExecutionFailure # We have to wait for a bit for qemu-agent to start try: ip_address = __utils__['cloud.wait_for_fun']( __find_agent_ip, vm_=vm_ ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # If VM was created but we can't connect, destroy it. destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) log.debug('Using IP address %s', ip_address) ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) ssh_password = config.get_cloud_config_value( 'password', vm_, __opts__, ) ret['ip_address'] = ip_address ret['username'] = ssh_username ret['password'] = ssh_password vm_['ssh_host'] = ip_address vm_['password'] = ssh_password ret = __utils__['cloud.bootstrap'](vm_, __opts__) # Report success! log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']( 'created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret
[ "def", "create", "(", "vm_", ")", ":", "try", ":", "# Check for required profile parameters before sending any API calls.", "if", "vm_", "[", "'profile'", "]", "and", "config", ".", "is_profile_configured", "(", "__opts__", ",", "__active_provider_name__", "or", "'proxm...
Create a single VM from a data dict CLI Example: .. code-block:: bash salt-cloud -p proxmox-ubuntu vmhostname
[ "Create", "a", "single", "VM", "from", "a", "data", "dict" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/proxmox.py#L556-L867
train
saltstack/salt
salt/cloud/clouds/proxmox.py
_import_api
def _import_api(): ''' Download https://<url>/pve-docs/api-viewer/apidoc.js Extract content of pveapi var (json formated) Load this json content into global variable "api" ''' global api full_url = 'https://{0}:{1}/pve-docs/api-viewer/apidoc.js'.format(url, port) returned_data = requests.get(full_url, verify=verify_ssl) re_filter = re.compile('(?<=pveapi =)(.*)(?=^;)', re.DOTALL | re.MULTILINE) api_json = re_filter.findall(returned_data.text)[0] api = salt.utils.json.loads(api_json)
python
def _import_api(): ''' Download https://<url>/pve-docs/api-viewer/apidoc.js Extract content of pveapi var (json formated) Load this json content into global variable "api" ''' global api full_url = 'https://{0}:{1}/pve-docs/api-viewer/apidoc.js'.format(url, port) returned_data = requests.get(full_url, verify=verify_ssl) re_filter = re.compile('(?<=pveapi =)(.*)(?=^;)', re.DOTALL | re.MULTILINE) api_json = re_filter.findall(returned_data.text)[0] api = salt.utils.json.loads(api_json)
[ "def", "_import_api", "(", ")", ":", "global", "api", "full_url", "=", "'https://{0}:{1}/pve-docs/api-viewer/apidoc.js'", ".", "format", "(", "url", ",", "port", ")", "returned_data", "=", "requests", ".", "get", "(", "full_url", ",", "verify", "=", "verify_ssl"...
Download https://<url>/pve-docs/api-viewer/apidoc.js Extract content of pveapi var (json formated) Load this json content into global variable "api"
[ "Download", "https", ":", "//", "<url", ">", "/", "pve", "-", "docs", "/", "api", "-", "viewer", "/", "apidoc", ".", "js", "Extract", "content", "of", "pveapi", "var", "(", "json", "formated", ")", "Load", "this", "json", "content", "into", "global", ...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/proxmox.py#L870-L882
train
saltstack/salt
salt/cloud/clouds/proxmox.py
_get_properties
def _get_properties(path="", method="GET", forced_params=None): ''' Return the parameter list from api for defined path and HTTP method ''' if api is None: _import_api() sub = api path_levels = [level for level in path.split('/') if level != ''] search_path = '' props = [] parameters = set([] if forced_params is None else forced_params) # Browse all path elements but last for elem in path_levels[:-1]: search_path += '/' + elem # Lookup for a dictionary with path = "requested path" in list" and return its children sub = (item for item in sub if item["path"] == search_path).next()['children'] # Get leaf element in path search_path += '/' + path_levels[-1] sub = next((item for item in sub if item["path"] == search_path)) try: # get list of properties for requested method props = sub['info'][method]['parameters']['properties'].keys() except KeyError as exc: log.error('method not found: "%s"', exc) for prop in props: numerical = re.match(r'(\w+)\[n\]', prop) # generate (arbitrarily) 10 properties for duplicatable properties identified by: # "prop[n]" if numerical: for i in range(10): parameters.add(numerical.group(1) + six.text_type(i)) else: parameters.add(prop) return parameters
python
def _get_properties(path="", method="GET", forced_params=None): ''' Return the parameter list from api for defined path and HTTP method ''' if api is None: _import_api() sub = api path_levels = [level for level in path.split('/') if level != ''] search_path = '' props = [] parameters = set([] if forced_params is None else forced_params) # Browse all path elements but last for elem in path_levels[:-1]: search_path += '/' + elem # Lookup for a dictionary with path = "requested path" in list" and return its children sub = (item for item in sub if item["path"] == search_path).next()['children'] # Get leaf element in path search_path += '/' + path_levels[-1] sub = next((item for item in sub if item["path"] == search_path)) try: # get list of properties for requested method props = sub['info'][method]['parameters']['properties'].keys() except KeyError as exc: log.error('method not found: "%s"', exc) for prop in props: numerical = re.match(r'(\w+)\[n\]', prop) # generate (arbitrarily) 10 properties for duplicatable properties identified by: # "prop[n]" if numerical: for i in range(10): parameters.add(numerical.group(1) + six.text_type(i)) else: parameters.add(prop) return parameters
[ "def", "_get_properties", "(", "path", "=", "\"\"", ",", "method", "=", "\"GET\"", ",", "forced_params", "=", "None", ")", ":", "if", "api", "is", "None", ":", "_import_api", "(", ")", "sub", "=", "api", "path_levels", "=", "[", "level", "for", "level"...
Return the parameter list from api for defined path and HTTP method
[ "Return", "the", "parameter", "list", "from", "api", "for", "defined", "path", "and", "HTTP", "method" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/proxmox.py#L885-L919
train
saltstack/salt
salt/cloud/clouds/proxmox.py
create_node
def create_node(vm_, newid): ''' Build and submit the requestdata to create a new node ''' newnode = {} if 'technology' not in vm_: vm_['technology'] = 'openvz' # default virt tech if none is given if vm_['technology'] not in ['qemu', 'openvz', 'lxc']: # Wrong VM type given log.error('Wrong VM type. Valid options are: qemu, openvz (proxmox3) or lxc (proxmox4)') raise SaltCloudExecutionFailure if 'host' not in vm_: # Use globally configured/default location vm_['host'] = config.get_cloud_config_value( 'default_host', get_configured_provider(), __opts__, search_global=False ) if vm_['host'] is None: # No location given for the profile log.error('No host given to create this VM on') raise SaltCloudExecutionFailure # Required by both OpenVZ and Qemu (KVM) vmhost = vm_['host'] newnode['vmid'] = newid for prop in 'cpuunits', 'description', 'memory', 'onboot': if prop in vm_: # if the property is set, use it for the VM request newnode[prop] = vm_[prop] if vm_['technology'] == 'openvz': # OpenVZ related settings, using non-default names: newnode['hostname'] = vm_['name'] newnode['ostemplate'] = vm_['image'] # optional VZ settings for prop in ['cpus', 'disk', 'ip_address', 'nameserver', 'password', 'swap', 'poolid', 'storage']: if prop in vm_: # if the property is set, use it for the VM request newnode[prop] = vm_[prop] elif vm_['technology'] == 'lxc': # LXC related settings, using non-default names: newnode['hostname'] = vm_['name'] newnode['ostemplate'] = vm_['image'] static_props = ('cpuunits', 'cpulimit', 'rootfs', 'cores', 'description', 'memory', 'onboot', 'net0', 'password', 'nameserver', 'swap', 'storage', 'rootfs') for prop in _get_properties('/nodes/{node}/lxc', 'POST', static_props): if prop in vm_: # if the property is set, use it for the VM request newnode[prop] = vm_[prop] if 'pubkey' in vm_: newnode['ssh-public-keys'] = vm_['pubkey'] # inform user the "disk" option is not supported for LXC hosts if 'disk' in vm_: log.warning('The "disk" option is not supported for LXC hosts and was ignored') # LXC specific network config # OpenVZ allowed specifying IP and gateway. To ease migration from # Proxmox 3, I've mapped the ip_address and gw to a generic net0 config. # If you need more control, please use the net0 option directly. # This also assumes a /24 subnet. if 'ip_address' in vm_ and 'net0' not in vm_: newnode['net0'] = 'bridge=vmbr0,ip=' + vm_['ip_address'] + '/24,name=eth0,type=veth' # gateway is optional and does not assume a default if 'gw' in vm_: newnode['net0'] = newnode['net0'] + ',gw=' + vm_['gw'] elif vm_['technology'] == 'qemu': # optional Qemu settings static_props = ( 'acpi', 'cores', 'cpu', 'pool', 'storage', 'sata0', 'ostype', 'ide2', 'net0') for prop in _get_properties('/nodes/{node}/qemu', 'POST', static_props): if prop in vm_: # if the property is set, use it for the VM request newnode[prop] = vm_[prop] # The node is ready. Lets request it to be added __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', newnode, list(newnode)), }, sock_dir=__opts__['sock_dir'], ) log.debug('Preparing to generate a node using these parameters: %s ', newnode) if 'clone' in vm_ and vm_['clone'] is True and vm_['technology'] == 'qemu': postParams = {} postParams['newid'] = newnode['vmid'] for prop in 'description', 'format', 'full', 'name': if 'clone_' + prop in vm_: # if the property is set, use it for the VM request postParams[prop] = vm_['clone_' + prop] if 'host' in vm_: postParams['target'] = vm_['host'] try: int(vm_['clone_from']) except ValueError: if ':' in vm_['clone_from']: vmhost = vm_['clone_from'].split(':')[0] vm_['clone_from'] = vm_['clone_from'].split(':')[1] node = query('post', 'nodes/{0}/qemu/{1}/clone'.format( vmhost, vm_['clone_from']), postParams) else: node = query('post', 'nodes/{0}/{1}'.format(vmhost, vm_['technology']), newnode) return _parse_proxmox_upid(node, vm_)
python
def create_node(vm_, newid): ''' Build and submit the requestdata to create a new node ''' newnode = {} if 'technology' not in vm_: vm_['technology'] = 'openvz' # default virt tech if none is given if vm_['technology'] not in ['qemu', 'openvz', 'lxc']: # Wrong VM type given log.error('Wrong VM type. Valid options are: qemu, openvz (proxmox3) or lxc (proxmox4)') raise SaltCloudExecutionFailure if 'host' not in vm_: # Use globally configured/default location vm_['host'] = config.get_cloud_config_value( 'default_host', get_configured_provider(), __opts__, search_global=False ) if vm_['host'] is None: # No location given for the profile log.error('No host given to create this VM on') raise SaltCloudExecutionFailure # Required by both OpenVZ and Qemu (KVM) vmhost = vm_['host'] newnode['vmid'] = newid for prop in 'cpuunits', 'description', 'memory', 'onboot': if prop in vm_: # if the property is set, use it for the VM request newnode[prop] = vm_[prop] if vm_['technology'] == 'openvz': # OpenVZ related settings, using non-default names: newnode['hostname'] = vm_['name'] newnode['ostemplate'] = vm_['image'] # optional VZ settings for prop in ['cpus', 'disk', 'ip_address', 'nameserver', 'password', 'swap', 'poolid', 'storage']: if prop in vm_: # if the property is set, use it for the VM request newnode[prop] = vm_[prop] elif vm_['technology'] == 'lxc': # LXC related settings, using non-default names: newnode['hostname'] = vm_['name'] newnode['ostemplate'] = vm_['image'] static_props = ('cpuunits', 'cpulimit', 'rootfs', 'cores', 'description', 'memory', 'onboot', 'net0', 'password', 'nameserver', 'swap', 'storage', 'rootfs') for prop in _get_properties('/nodes/{node}/lxc', 'POST', static_props): if prop in vm_: # if the property is set, use it for the VM request newnode[prop] = vm_[prop] if 'pubkey' in vm_: newnode['ssh-public-keys'] = vm_['pubkey'] # inform user the "disk" option is not supported for LXC hosts if 'disk' in vm_: log.warning('The "disk" option is not supported for LXC hosts and was ignored') # LXC specific network config # OpenVZ allowed specifying IP and gateway. To ease migration from # Proxmox 3, I've mapped the ip_address and gw to a generic net0 config. # If you need more control, please use the net0 option directly. # This also assumes a /24 subnet. if 'ip_address' in vm_ and 'net0' not in vm_: newnode['net0'] = 'bridge=vmbr0,ip=' + vm_['ip_address'] + '/24,name=eth0,type=veth' # gateway is optional and does not assume a default if 'gw' in vm_: newnode['net0'] = newnode['net0'] + ',gw=' + vm_['gw'] elif vm_['technology'] == 'qemu': # optional Qemu settings static_props = ( 'acpi', 'cores', 'cpu', 'pool', 'storage', 'sata0', 'ostype', 'ide2', 'net0') for prop in _get_properties('/nodes/{node}/qemu', 'POST', static_props): if prop in vm_: # if the property is set, use it for the VM request newnode[prop] = vm_[prop] # The node is ready. Lets request it to be added __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', newnode, list(newnode)), }, sock_dir=__opts__['sock_dir'], ) log.debug('Preparing to generate a node using these parameters: %s ', newnode) if 'clone' in vm_ and vm_['clone'] is True and vm_['technology'] == 'qemu': postParams = {} postParams['newid'] = newnode['vmid'] for prop in 'description', 'format', 'full', 'name': if 'clone_' + prop in vm_: # if the property is set, use it for the VM request postParams[prop] = vm_['clone_' + prop] if 'host' in vm_: postParams['target'] = vm_['host'] try: int(vm_['clone_from']) except ValueError: if ':' in vm_['clone_from']: vmhost = vm_['clone_from'].split(':')[0] vm_['clone_from'] = vm_['clone_from'].split(':')[1] node = query('post', 'nodes/{0}/qemu/{1}/clone'.format( vmhost, vm_['clone_from']), postParams) else: node = query('post', 'nodes/{0}/{1}'.format(vmhost, vm_['technology']), newnode) return _parse_proxmox_upid(node, vm_)
[ "def", "create_node", "(", "vm_", ",", "newid", ")", ":", "newnode", "=", "{", "}", "if", "'technology'", "not", "in", "vm_", ":", "vm_", "[", "'technology'", "]", "=", "'openvz'", "# default virt tech if none is given", "if", "vm_", "[", "'technology'", "]"...
Build and submit the requestdata to create a new node
[ "Build", "and", "submit", "the", "requestdata", "to", "create", "a", "new", "node" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/proxmox.py#L922-L1042
train
saltstack/salt
salt/cloud/clouds/proxmox.py
get_vmconfig
def get_vmconfig(vmid, node=None, node_type='openvz'): ''' Get VM configuration ''' if node is None: # We need to figure out which node this VM is on. for host_name, host_details in six.iteritems(avail_locations()): for item in query('get', 'nodes/{0}/{1}'.format(host_name, node_type)): if item['vmid'] == vmid: node = host_name # If we reached this point, we have all the information we need data = query('get', 'nodes/{0}/{1}/{2}/config'.format(node, node_type, vmid)) return data
python
def get_vmconfig(vmid, node=None, node_type='openvz'): ''' Get VM configuration ''' if node is None: # We need to figure out which node this VM is on. for host_name, host_details in six.iteritems(avail_locations()): for item in query('get', 'nodes/{0}/{1}'.format(host_name, node_type)): if item['vmid'] == vmid: node = host_name # If we reached this point, we have all the information we need data = query('get', 'nodes/{0}/{1}/{2}/config'.format(node, node_type, vmid)) return data
[ "def", "get_vmconfig", "(", "vmid", ",", "node", "=", "None", ",", "node_type", "=", "'openvz'", ")", ":", "if", "node", "is", "None", ":", "# We need to figure out which node this VM is on.", "for", "host_name", ",", "host_details", "in", "six", ".", "iteritems...
Get VM configuration
[ "Get", "VM", "configuration" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/proxmox.py#L1059-L1073
train
saltstack/salt
salt/cloud/clouds/proxmox.py
wait_for_state
def wait_for_state(vmid, state, timeout=300): ''' Wait until a specific state has been reached on a node ''' start_time = time.time() node = get_vm_status(vmid=vmid) if not node: log.error('wait_for_state: No VM retrieved based on given criteria.') raise SaltCloudExecutionFailure while True: if node['status'] == state: log.debug('Host %s is now in "%s" state!', node['name'], state) return True time.sleep(1) if time.time() - start_time > timeout: log.debug('Timeout reached while waiting for %s to become %s', node['name'], state) return False node = get_vm_status(vmid=vmid) log.debug('State for %s is: "%s" instead of "%s"', node['name'], node['status'], state)
python
def wait_for_state(vmid, state, timeout=300): ''' Wait until a specific state has been reached on a node ''' start_time = time.time() node = get_vm_status(vmid=vmid) if not node: log.error('wait_for_state: No VM retrieved based on given criteria.') raise SaltCloudExecutionFailure while True: if node['status'] == state: log.debug('Host %s is now in "%s" state!', node['name'], state) return True time.sleep(1) if time.time() - start_time > timeout: log.debug('Timeout reached while waiting for %s to become %s', node['name'], state) return False node = get_vm_status(vmid=vmid) log.debug('State for %s is: "%s" instead of "%s"', node['name'], node['status'], state)
[ "def", "wait_for_state", "(", "vmid", ",", "state", ",", "timeout", "=", "300", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "node", "=", "get_vm_status", "(", "vmid", "=", "vmid", ")", "if", "not", "node", ":", "log", ".", "error", ...
Wait until a specific state has been reached on a node
[ "Wait", "until", "a", "specific", "state", "has", "been", "reached", "on", "a", "node" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/proxmox.py#L1098-L1119
train
saltstack/salt
salt/cloud/clouds/proxmox.py
wait_for_task
def wait_for_task(upid, timeout=300): ''' Wait until a the task has been finished successfully ''' start_time = time.time() info = _lookup_proxmox_task(upid) if not info: log.error('wait_for_task: No task information ' 'retrieved based on given criteria.') raise SaltCloudExecutionFailure while True: if 'status' in info and info['status'] == 'OK': log.debug('Task has been finished!') return True time.sleep(3) # Little more patience, we're not in a hurry if time.time() - start_time > timeout: log.debug('Timeout reached while waiting for task to be finished') return False info = _lookup_proxmox_task(upid)
python
def wait_for_task(upid, timeout=300): ''' Wait until a the task has been finished successfully ''' start_time = time.time() info = _lookup_proxmox_task(upid) if not info: log.error('wait_for_task: No task information ' 'retrieved based on given criteria.') raise SaltCloudExecutionFailure while True: if 'status' in info and info['status'] == 'OK': log.debug('Task has been finished!') return True time.sleep(3) # Little more patience, we're not in a hurry if time.time() - start_time > timeout: log.debug('Timeout reached while waiting for task to be finished') return False info = _lookup_proxmox_task(upid)
[ "def", "wait_for_task", "(", "upid", ",", "timeout", "=", "300", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "info", "=", "_lookup_proxmox_task", "(", "upid", ")", "if", "not", "info", ":", "log", ".", "error", "(", "'wait_for_task: No ta...
Wait until a the task has been finished successfully
[ "Wait", "until", "a", "the", "task", "has", "been", "finished", "successfully" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/proxmox.py#L1122-L1141
train
saltstack/salt
salt/cloud/clouds/proxmox.py
destroy
def destroy(name, call=None): ''' Destroy a node. CLI Example: .. code-block:: bash salt-cloud --destroy mymachine ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) vmobj = _get_vm_by_name(name) if vmobj is not None: # stop the vm if get_vm_status(vmid=vmobj['vmid'])['status'] != 'stopped': stop(name, vmobj['vmid'], 'action') # wait until stopped if not wait_for_state(vmobj['vmid'], 'stopped'): return {'Error': 'Unable to stop {0}, command timed out'.format(name)} # required to wait a bit here, otherwise the VM is sometimes # still locked and destroy fails. time.sleep(3) query('delete', 'nodes/{0}/{1}'.format( vmobj['node'], vmobj['id'] )) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__) return {'Destroyed': '{0} was destroyed.'.format(name)}
python
def destroy(name, call=None): ''' Destroy a node. CLI Example: .. code-block:: bash salt-cloud --destroy mymachine ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) vmobj = _get_vm_by_name(name) if vmobj is not None: # stop the vm if get_vm_status(vmid=vmobj['vmid'])['status'] != 'stopped': stop(name, vmobj['vmid'], 'action') # wait until stopped if not wait_for_state(vmobj['vmid'], 'stopped'): return {'Error': 'Unable to stop {0}, command timed out'.format(name)} # required to wait a bit here, otherwise the VM is sometimes # still locked and destroy fails. time.sleep(3) query('delete', 'nodes/{0}/{1}'.format( vmobj['node'], vmobj['id'] )) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__) return {'Destroyed': '{0} was destroyed.'.format(name)}
[ "def", "destroy", "(", "name", ",", "call", "=", "None", ")", ":", "if", "call", "==", "'function'", ":", "raise", "SaltCloudSystemExit", "(", "'The destroy action must be called with -d, --destroy, '", "'-a or --action.'", ")", "__utils__", "[", "'cloud.fire_event'", ...
Destroy a node. CLI Example: .. code-block:: bash salt-cloud --destroy mymachine
[ "Destroy", "a", "node", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/proxmox.py#L1144-L1198
train
saltstack/salt
salt/cloud/clouds/proxmox.py
set_vm_status
def set_vm_status(status, name=None, vmid=None): ''' Convenience function for setting VM status ''' log.debug('Set status to %s for %s (%s)', status, name, vmid) if vmid is not None: log.debug('set_vm_status: via ID - VMID %s (%s): %s', vmid, name, status) vmobj = _get_vm_by_id(vmid) else: log.debug('set_vm_status: via name - VMID %s (%s): %s', vmid, name, status) vmobj = _get_vm_by_name(name) if not vmobj or 'node' not in vmobj or 'type' not in vmobj or 'vmid' not in vmobj: log.error('Unable to set status %s for %s (%s)', status, name, vmid) raise SaltCloudExecutionTimeout log.debug("VM_STATUS: Has desired info (%s). Setting status..", vmobj) data = query('post', 'nodes/{0}/{1}/{2}/status/{3}'.format( vmobj['node'], vmobj['type'], vmobj['vmid'], status)) result = _parse_proxmox_upid(data, vmobj) if result is not False and result is not None: log.debug('Set_vm_status action result: %s', result) return True return False
python
def set_vm_status(status, name=None, vmid=None): ''' Convenience function for setting VM status ''' log.debug('Set status to %s for %s (%s)', status, name, vmid) if vmid is not None: log.debug('set_vm_status: via ID - VMID %s (%s): %s', vmid, name, status) vmobj = _get_vm_by_id(vmid) else: log.debug('set_vm_status: via name - VMID %s (%s): %s', vmid, name, status) vmobj = _get_vm_by_name(name) if not vmobj or 'node' not in vmobj or 'type' not in vmobj or 'vmid' not in vmobj: log.error('Unable to set status %s for %s (%s)', status, name, vmid) raise SaltCloudExecutionTimeout log.debug("VM_STATUS: Has desired info (%s). Setting status..", vmobj) data = query('post', 'nodes/{0}/{1}/{2}/status/{3}'.format( vmobj['node'], vmobj['type'], vmobj['vmid'], status)) result = _parse_proxmox_upid(data, vmobj) if result is not False and result is not None: log.debug('Set_vm_status action result: %s', result) return True return False
[ "def", "set_vm_status", "(", "status", ",", "name", "=", "None", ",", "vmid", "=", "None", ")", ":", "log", ".", "debug", "(", "'Set status to %s for %s (%s)'", ",", "status", ",", "name", ",", "vmid", ")", "if", "vmid", "is", "not", "None", ":", "log"...
Convenience function for setting VM status
[ "Convenience", "function", "for", "setting", "VM", "status" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/proxmox.py#L1201-L1231
train
saltstack/salt
salt/cloud/clouds/proxmox.py
get_vm_status
def get_vm_status(vmid=None, name=None): ''' Get the status for a VM, either via the ID or the hostname ''' if vmid is not None: log.debug('get_vm_status: VMID %s', vmid) vmobj = _get_vm_by_id(vmid) elif name is not None: log.debug('get_vm_status: name %s', name) vmobj = _get_vm_by_name(name) else: log.debug("get_vm_status: No ID or NAME given") raise SaltCloudExecutionFailure log.debug('VM found: %s', vmobj) if vmobj is not None and 'node' in vmobj: log.debug("VM_STATUS: Has desired info. Retrieving.. (%s)", vmobj['name']) data = query('get', 'nodes/{0}/{1}/{2}/status/current'.format( vmobj['node'], vmobj['type'], vmobj['vmid'])) return data log.error('VM or requested status not found..') return False
python
def get_vm_status(vmid=None, name=None): ''' Get the status for a VM, either via the ID or the hostname ''' if vmid is not None: log.debug('get_vm_status: VMID %s', vmid) vmobj = _get_vm_by_id(vmid) elif name is not None: log.debug('get_vm_status: name %s', name) vmobj = _get_vm_by_name(name) else: log.debug("get_vm_status: No ID or NAME given") raise SaltCloudExecutionFailure log.debug('VM found: %s', vmobj) if vmobj is not None and 'node' in vmobj: log.debug("VM_STATUS: Has desired info. Retrieving.. (%s)", vmobj['name']) data = query('get', 'nodes/{0}/{1}/{2}/status/current'.format( vmobj['node'], vmobj['type'], vmobj['vmid'])) return data log.error('VM or requested status not found..') return False
[ "def", "get_vm_status", "(", "vmid", "=", "None", ",", "name", "=", "None", ")", ":", "if", "vmid", "is", "not", "None", ":", "log", ".", "debug", "(", "'get_vm_status: VMID %s'", ",", "vmid", ")", "vmobj", "=", "_get_vm_by_id", "(", "vmid", ")", "elif...
Get the status for a VM, either via the ID or the hostname
[ "Get", "the", "status", "for", "a", "VM", "either", "via", "the", "ID", "or", "the", "hostname" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/proxmox.py#L1234-L1258
train
saltstack/salt
salt/cloud/clouds/proxmox.py
start
def start(name, vmid=None, call=None): ''' Start a node. CLI Example: .. code-block:: bash salt-cloud -a start mymachine ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.debug('Start: %s (%s) = Start', name, vmid) if not set_vm_status('start', name, vmid=vmid): log.error('Unable to bring VM %s (%s) up..', name, vmid) raise SaltCloudExecutionFailure # xxx: TBD: Check here whether the status was actually changed to 'started' return {'Started': '{0} was started.'.format(name)}
python
def start(name, vmid=None, call=None): ''' Start a node. CLI Example: .. code-block:: bash salt-cloud -a start mymachine ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.debug('Start: %s (%s) = Start', name, vmid) if not set_vm_status('start', name, vmid=vmid): log.error('Unable to bring VM %s (%s) up..', name, vmid) raise SaltCloudExecutionFailure # xxx: TBD: Check here whether the status was actually changed to 'started' return {'Started': '{0} was started.'.format(name)}
[ "def", "start", "(", "name", ",", "vmid", "=", "None", ",", "call", "=", "None", ")", ":", "if", "call", "!=", "'action'", ":", "raise", "SaltCloudSystemExit", "(", "'The start action must be called with -a or --action.'", ")", "log", ".", "debug", "(", "'Star...
Start a node. CLI Example: .. code-block:: bash salt-cloud -a start mymachine
[ "Start", "a", "node", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/proxmox.py#L1261-L1283
train
saltstack/salt
salt/cloud/clouds/proxmox.py
stop
def stop(name, vmid=None, call=None): ''' Stop a node ("pulling the plug"). CLI Example: .. code-block:: bash salt-cloud -a stop mymachine ''' if call != 'action': raise SaltCloudSystemExit( 'The stop action must be called with -a or --action.' ) if not set_vm_status('stop', name, vmid=vmid): log.error('Unable to bring VM %s (%s) down..', name, vmid) raise SaltCloudExecutionFailure # xxx: TBD: Check here whether the status was actually changed to 'stopped' return {'Stopped': '{0} was stopped.'.format(name)}
python
def stop(name, vmid=None, call=None): ''' Stop a node ("pulling the plug"). CLI Example: .. code-block:: bash salt-cloud -a stop mymachine ''' if call != 'action': raise SaltCloudSystemExit( 'The stop action must be called with -a or --action.' ) if not set_vm_status('stop', name, vmid=vmid): log.error('Unable to bring VM %s (%s) down..', name, vmid) raise SaltCloudExecutionFailure # xxx: TBD: Check here whether the status was actually changed to 'stopped' return {'Stopped': '{0} was stopped.'.format(name)}
[ "def", "stop", "(", "name", ",", "vmid", "=", "None", ",", "call", "=", "None", ")", ":", "if", "call", "!=", "'action'", ":", "raise", "SaltCloudSystemExit", "(", "'The stop action must be called with -a or --action.'", ")", "if", "not", "set_vm_status", "(", ...
Stop a node ("pulling the plug"). CLI Example: .. code-block:: bash salt-cloud -a stop mymachine
[ "Stop", "a", "node", "(", "pulling", "the", "plug", ")", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/proxmox.py#L1286-L1307
train
saltstack/salt
salt/states/rsync.py
_get_summary
def _get_summary(rsync_out): ''' Get summary from the rsync successful output. ''' return "- " + "\n- ".join([elm for elm in rsync_out.split("\n\n")[-1].replace(" ", "\n").split("\n") if elm])
python
def _get_summary(rsync_out): ''' Get summary from the rsync successful output. ''' return "- " + "\n- ".join([elm for elm in rsync_out.split("\n\n")[-1].replace(" ", "\n").split("\n") if elm])
[ "def", "_get_summary", "(", "rsync_out", ")", ":", "return", "\"- \"", "+", "\"\\n- \"", ".", "join", "(", "[", "elm", "for", "elm", "in", "rsync_out", ".", "split", "(", "\"\\n\\n\"", ")", "[", "-", "1", "]", ".", "replace", "(", "\" \"", ",", "\"\...
Get summary from the rsync successful output.
[ "Get", "summary", "from", "the", "rsync", "successful", "output", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/rsync.py#L48-L53
train
saltstack/salt
salt/states/rsync.py
_get_changes
def _get_changes(rsync_out): ''' Get changes from the rsync successful output. ''' copied = list() deleted = list() for line in rsync_out.split("\n\n")[0].split("\n")[1:]: if line.startswith("deleting "): deleted.append(line.split(" ", 1)[-1]) else: copied.append(line) ret = { 'copied': os.linesep.join(sorted(copied)) or "N/A", 'deleted': os.linesep.join(sorted(deleted)) or "N/A", } # Return whether anything really changed ret['changed'] = not ((ret['copied'] == 'N/A') and (ret['deleted'] == 'N/A')) return ret
python
def _get_changes(rsync_out): ''' Get changes from the rsync successful output. ''' copied = list() deleted = list() for line in rsync_out.split("\n\n")[0].split("\n")[1:]: if line.startswith("deleting "): deleted.append(line.split(" ", 1)[-1]) else: copied.append(line) ret = { 'copied': os.linesep.join(sorted(copied)) or "N/A", 'deleted': os.linesep.join(sorted(deleted)) or "N/A", } # Return whether anything really changed ret['changed'] = not ((ret['copied'] == 'N/A') and (ret['deleted'] == 'N/A')) return ret
[ "def", "_get_changes", "(", "rsync_out", ")", ":", "copied", "=", "list", "(", ")", "deleted", "=", "list", "(", ")", "for", "line", "in", "rsync_out", ".", "split", "(", "\"\\n\\n\"", ")", "[", "0", "]", ".", "split", "(", "\"\\n\"", ")", "[", "1"...
Get changes from the rsync successful output.
[ "Get", "changes", "from", "the", "rsync", "successful", "output", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/rsync.py#L56-L77
train
saltstack/salt
salt/states/rsync.py
synchronized
def synchronized(name, source, delete=False, force=False, update=False, passwordfile=None, exclude=None, excludefrom=None, prepare=False, dryrun=False, additional_opts=None): ''' Guarantees that the source directory is always copied to the target. name Name of the target directory. source Source directory. prepare Create destination directory if it does not exists. delete Delete extraneous files from the destination dirs (True or False) force Force deletion of dirs even if not empty update Skip files that are newer on the receiver (True or False) passwordfile Read daemon-access password from the file (path) exclude Exclude files, that matches pattern. excludefrom Read exclude patterns from the file (path) dryrun Perform a trial run with no changes made. Is the same as doing test=True .. versionadded:: 2016.3.1 additional_opts Pass additional options to rsync, should be included as a list. .. versionadded:: 2018.3.0 ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} if not os.path.exists(name) and not force and not prepare: ret['result'] = False ret['comment'] = "Destination directory {dest} was not found.".format(dest=name) else: if not os.path.exists(name) and prepare: os.makedirs(name) if __opts__['test']: dryrun = True result = __salt__['rsync.rsync'](source, name, delete=delete, force=force, update=update, passwordfile=passwordfile, exclude=exclude, excludefrom=excludefrom, dryrun=dryrun, additional_opts=additional_opts) if __opts__['test'] or dryrun: ret['result'] = None ret['comment'] = _get_summary(result['stdout']) return ret # Failed if result.get('retcode'): ret['result'] = False ret['comment'] = result['stderr'] # Changed elif _get_changes(result['stdout'])['changed']: ret['comment'] = _get_summary(result['stdout']) ret['changes'] = _get_changes(result['stdout']) del ret['changes']['changed'] # Don't need to print the boolean # Clean else: ret['comment'] = _get_summary(result['stdout']) ret['changes'] = {} return ret
python
def synchronized(name, source, delete=False, force=False, update=False, passwordfile=None, exclude=None, excludefrom=None, prepare=False, dryrun=False, additional_opts=None): ''' Guarantees that the source directory is always copied to the target. name Name of the target directory. source Source directory. prepare Create destination directory if it does not exists. delete Delete extraneous files from the destination dirs (True or False) force Force deletion of dirs even if not empty update Skip files that are newer on the receiver (True or False) passwordfile Read daemon-access password from the file (path) exclude Exclude files, that matches pattern. excludefrom Read exclude patterns from the file (path) dryrun Perform a trial run with no changes made. Is the same as doing test=True .. versionadded:: 2016.3.1 additional_opts Pass additional options to rsync, should be included as a list. .. versionadded:: 2018.3.0 ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} if not os.path.exists(name) and not force and not prepare: ret['result'] = False ret['comment'] = "Destination directory {dest} was not found.".format(dest=name) else: if not os.path.exists(name) and prepare: os.makedirs(name) if __opts__['test']: dryrun = True result = __salt__['rsync.rsync'](source, name, delete=delete, force=force, update=update, passwordfile=passwordfile, exclude=exclude, excludefrom=excludefrom, dryrun=dryrun, additional_opts=additional_opts) if __opts__['test'] or dryrun: ret['result'] = None ret['comment'] = _get_summary(result['stdout']) return ret # Failed if result.get('retcode'): ret['result'] = False ret['comment'] = result['stderr'] # Changed elif _get_changes(result['stdout'])['changed']: ret['comment'] = _get_summary(result['stdout']) ret['changes'] = _get_changes(result['stdout']) del ret['changes']['changed'] # Don't need to print the boolean # Clean else: ret['comment'] = _get_summary(result['stdout']) ret['changes'] = {} return ret
[ "def", "synchronized", "(", "name", ",", "source", ",", "delete", "=", "False", ",", "force", "=", "False", ",", "update", "=", "False", ",", "passwordfile", "=", "None", ",", "exclude", "=", "None", ",", "excludefrom", "=", "None", ",", "prepare", "="...
Guarantees that the source directory is always copied to the target. name Name of the target directory. source Source directory. prepare Create destination directory if it does not exists. delete Delete extraneous files from the destination dirs (True or False) force Force deletion of dirs even if not empty update Skip files that are newer on the receiver (True or False) passwordfile Read daemon-access password from the file (path) exclude Exclude files, that matches pattern. excludefrom Read exclude patterns from the file (path) dryrun Perform a trial run with no changes made. Is the same as doing test=True .. versionadded:: 2016.3.1 additional_opts Pass additional options to rsync, should be included as a list. .. versionadded:: 2018.3.0
[ "Guarantees", "that", "the", "source", "directory", "is", "always", "copied", "to", "the", "target", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/rsync.py#L80-L170
train