text
stringlengths 52
3.87M
|
---|
def zmq_device(self):
'''
Multiprocessing target for the zmq queue device
'''
self.__setup_signals()
salt.utils.process.appendproctitle('MWorkerQueue')
self.context = zmq.Context(self.opts['worker_threads'])
# Prepare the zeromq sockets
self.uri = 'tcp://{interface}:{ret_port}'.format(**self.opts)
self.clients = self.context.socket(zmq.ROUTER)
if self.opts['ipv6'] is True and hasattr(zmq, 'IPV4ONLY'):
# IPv6 sockets work for both IPv6 and IPv4 addresses
self.clients.setsockopt(zmq.IPV4ONLY, 0)
self.clients.setsockopt(zmq.BACKLOG, self.opts.get('zmq_backlog', 1000))
self._start_zmq_monitor()
self.workers = self.context.socket(zmq.DEALER)
if self.opts.get('ipc_mode', '') == 'tcp':
self.w_uri = 'tcp://127.0.0.1:{0}'.format(
self.opts.get('tcp_master_workers', 4515)
)
else:
self.w_uri = 'ipc://{0}'.format(
os.path.join(self.opts['sock_dir'], 'workers.ipc')
)
log.info('Setting up the master communication server')
self.clients.bind(self.uri)
self.workers.bind(self.w_uri)
while True:
if self.clients.closed or self.workers.closed:
break
try:
zmq.device(zmq.QUEUE, self.clients, self.workers)
except zmq.ZMQError as exc:
if exc.errno == errno.EINTR:
continue
raise exc
except (KeyboardInterrupt, SystemExit):
break |
def close(self):
'''
Cleanly shutdown the router socket
'''
if self._closing:
return
log.info('MWorkerQueue under PID %s is closing', os.getpid())
self._closing = True
# pylint: disable=E0203
if getattr(self, '_monitor', None) is not None:
self._monitor.stop()
self._monitor = None
if getattr(self, '_w_monitor', None) is not None:
self._w_monitor.stop()
self._w_monitor = None
if hasattr(self, 'clients') and self.clients.closed is False:
self.clients.close()
if hasattr(self, 'workers') and self.workers.closed is False:
self.workers.close()
if hasattr(self, 'stream'):
self.stream.close()
if hasattr(self, '_socket') and self._socket.closed is False:
self._socket.close()
if hasattr(self, 'context') and self.context.closed is False:
self.context.term() |
def pre_fork(self, process_manager):
'''
Pre-fork we need to create the zmq router device
:param func process_manager: An instance of salt.utils.process.ProcessManager
'''
salt.transport.mixins.auth.AESReqServerMixin.pre_fork(self, process_manager)
process_manager.add_process(self.zmq_device) |
def _start_zmq_monitor(self):
'''
Starts ZMQ monitor for debugging purposes.
:return:
'''
# Socket monitor shall be used the only for debug
# purposes so using threading doesn't look too bad here
if HAS_ZMQ_MONITOR and self.opts['zmq_monitor']:
log.debug('Starting ZMQ monitor')
import threading
self._w_monitor = ZeroMQSocketMonitor(self._socket)
threading.Thread(target=self._w_monitor.start_poll).start()
log.debug('ZMQ monitor has been started started') |
def post_fork(self, payload_handler, io_loop):
'''
After forking we need to create all of the local sockets to listen to the
router
:param func payload_handler: A function to called to handle incoming payloads as
they are picked up off the wire
:param IOLoop io_loop: An instance of a Tornado IOLoop, to handle event scheduling
'''
self.payload_handler = payload_handler
self.io_loop = io_loop
self.context = zmq.Context(1)
self._socket = self.context.socket(zmq.REP)
self._start_zmq_monitor()
if self.opts.get('ipc_mode', '') == 'tcp':
self.w_uri = 'tcp://127.0.0.1:{0}'.format(
self.opts.get('tcp_master_workers', 4515)
)
else:
self.w_uri = 'ipc://{0}'.format(
os.path.join(self.opts['sock_dir'], 'workers.ipc')
)
log.info('Worker binding to socket %s', self.w_uri)
self._socket.connect(self.w_uri)
salt.transport.mixins.auth.AESReqServerMixin.post_fork(self, payload_handler, io_loop)
self.stream = zmq.eventloop.zmqstream.ZMQStream(self._socket, io_loop=self.io_loop)
self.stream.on_recv_stream(self.handle_message) |
def handle_message(self, stream, payload):
'''
Handle incoming messages from underlying TCP streams
:stream ZMQStream stream: A ZeroMQ stream.
See http://zeromq.github.io/pyzmq/api/generated/zmq.eventloop.zmqstream.html
:param dict payload: A payload to process
'''
try:
payload = self.serial.loads(payload[0])
payload = self._decode_payload(payload)
except Exception as exc:
exc_type = type(exc).__name__
if exc_type == 'AuthenticationError':
log.debug(
'Minion failed to auth to master. Since the payload is '
'encrypted, it is not known which minion failed to '
'authenticate. It is likely that this is a transient '
'failure due to the master rotating its public key.'
)
else:
log.error('Bad load from minion: %s: %s', exc_type, exc)
stream.send(self.serial.dumps('bad load'))
raise tornado.gen.Return()
# TODO helper functions to normalize payload?
if not isinstance(payload, dict) or not isinstance(payload.get('load'), dict):
log.error('payload and load must be a dict. Payload was: %s and load was %s', payload, payload.get('load'))
stream.send(self.serial.dumps('payload and load must be a dict'))
raise tornado.gen.Return()
try:
id_ = payload['load'].get('id', '')
if str('\0') in id_:
log.error('Payload contains an id with a null byte: %s', payload)
stream.send(self.serial.dumps('bad load: id contains a null byte'))
raise tornado.gen.Return()
except TypeError:
log.error('Payload contains non-string id: %s', payload)
stream.send(self.serial.dumps('bad load: id {0} is not a string'.format(id_)))
raise tornado.gen.Return()
# intercept the "_auth" commands, since the main daemon shouldn't know
# anything about our key auth
if payload['enc'] == 'clear' and payload.get('load', {}).get('cmd') == '_auth':
stream.send(self.serial.dumps(self._auth(payload['load'])))
raise tornado.gen.Return()
# TODO: test
try:
# Take the payload_handler function that was registered when we created the channel
# and call it, returning control to the caller until it completes
ret, req_opts = yield self.payload_handler(payload)
except Exception as e:
# always attempt to return an error to the minion
stream.send(self.serial.dumps('Some exception handling minion payload'))
log.error('Some exception handling a payload from minion', exc_info=True)
raise tornado.gen.Return()
req_fun = req_opts.get('fun', 'send')
if req_fun == 'send_clear':
stream.send(self.serial.dumps(ret))
elif req_fun == 'send':
stream.send(self.serial.dumps(self.crypticle.dumps(ret)))
elif req_fun == 'send_private':
stream.send(self.serial.dumps(self._encrypt_private(ret,
req_opts['key'],
req_opts['tgt'],
)))
else:
log.error('Unknown req_fun %s', req_fun)
# always attempt to return an error to the minion
stream.send(self.serial.dumps('Server-side exception handling payload'))
raise tornado.gen.Return() |
def _publish_daemon(self, log_queue=None):
'''
Bind to the interface specified in the configuration file
'''
salt.utils.process.appendproctitle(self.__class__.__name__)
if log_queue:
salt.log.setup.set_multiprocessing_logging_queue(log_queue)
salt.log.setup.setup_multiprocessing_logging(log_queue)
# Set up the context
context = zmq.Context(1)
# Prepare minion publish socket
pub_sock = context.socket(zmq.PUB)
_set_tcp_keepalive(pub_sock, self.opts)
# if 2.1 >= zmq < 3.0, we only have one HWM setting
try:
pub_sock.setsockopt(zmq.HWM, self.opts.get('pub_hwm', 1000))
# in zmq >= 3.0, there are separate send and receive HWM settings
except AttributeError:
# Set the High Water Marks. For more information on HWM, see:
# http://api.zeromq.org/4-1:zmq-setsockopt
pub_sock.setsockopt(zmq.SNDHWM, self.opts.get('pub_hwm', 1000))
pub_sock.setsockopt(zmq.RCVHWM, self.opts.get('pub_hwm', 1000))
if self.opts['ipv6'] is True and hasattr(zmq, 'IPV4ONLY'):
# IPv6 sockets work for both IPv6 and IPv4 addresses
pub_sock.setsockopt(zmq.IPV4ONLY, 0)
pub_sock.setsockopt(zmq.BACKLOG, self.opts.get('zmq_backlog', 1000))
pub_sock.setsockopt(zmq.LINGER, -1)
pub_uri = 'tcp://{interface}:{publish_port}'.format(**self.opts)
# Prepare minion pull socket
pull_sock = context.socket(zmq.PULL)
pull_sock.setsockopt(zmq.LINGER, -1)
if self.opts.get('ipc_mode', '') == 'tcp':
pull_uri = 'tcp://127.0.0.1:{0}'.format(
self.opts.get('tcp_master_publish_pull', 4514)
)
else:
pull_uri = 'ipc://{0}'.format(
os.path.join(self.opts['sock_dir'], 'publish_pull.ipc')
)
salt.utils.zeromq.check_ipc_path_max_len(pull_uri)
# Start the minion command publisher
log.info('Starting the Salt Publisher on %s', pub_uri)
pub_sock.bind(pub_uri)
# Securely create socket
log.info('Starting the Salt Puller on %s', pull_uri)
with salt.utils.files.set_umask(0o177):
pull_sock.bind(pull_uri)
try:
while True:
# Catch and handle EINTR from when this process is sent
# SIGUSR1 gracefully so we don't choke and die horribly
try:
log.debug('Publish daemon getting data from puller %s', pull_uri)
package = pull_sock.recv()
log.debug('Publish daemon received payload. size=%d', len(package))
unpacked_package = salt.payload.unpackage(package)
if six.PY3:
unpacked_package = salt.transport.frame.decode_embedded_strs(unpacked_package)
payload = unpacked_package['payload']
log.trace('Accepted unpacked package from puller')
if self.opts['zmq_filtering']:
# if you have a specific topic list, use that
if 'topic_lst' in unpacked_package:
for topic in unpacked_package['topic_lst']:
log.trace('Sending filtered data over publisher %s', pub_uri)
# zmq filters are substring match, hash the topic
# to avoid collisions
htopic = salt.utils.stringutils.to_bytes(hashlib.sha1(topic).hexdigest())
pub_sock.send(htopic, flags=zmq.SNDMORE)
pub_sock.send(payload)
log.trace('Filtered data has been sent')
# Syndic broadcast
if self.opts.get('order_masters'):
log.trace('Sending filtered data to syndic')
pub_sock.send(b'syndic', flags=zmq.SNDMORE)
pub_sock.send(payload)
log.trace('Filtered data has been sent to syndic')
# otherwise its a broadcast
else:
# TODO: constants file for "broadcast"
log.trace('Sending broadcasted data over publisher %s', pub_uri)
pub_sock.send(b'broadcast', flags=zmq.SNDMORE)
pub_sock.send(payload)
log.trace('Broadcasted data has been sent')
else:
log.trace('Sending ZMQ-unfiltered data over publisher %s', pub_uri)
pub_sock.send(payload)
log.trace('Unfiltered data has been sent')
except zmq.ZMQError as exc:
if exc.errno == errno.EINTR:
continue
raise exc
except KeyboardInterrupt:
log.trace('Publish daemon caught Keyboard interupt, tearing down')
# Cleanly close the sockets if we're shutting down
if pub_sock.closed is False:
pub_sock.close()
if pull_sock.closed is False:
pull_sock.close()
if context.closed is False:
context.term() |
def pub_connect(self):
'''
Create and connect this thread's zmq socket. If a publisher socket
already exists "pub_close" is called before creating and connecting a
new socket.
'''
if self.pub_sock:
self.pub_close()
ctx = zmq.Context.instance()
self._sock_data.sock = ctx.socket(zmq.PUSH)
self.pub_sock.setsockopt(zmq.LINGER, -1)
if self.opts.get('ipc_mode', '') == 'tcp':
pull_uri = 'tcp://127.0.0.1:{0}'.format(
self.opts.get('tcp_master_publish_pull', 4514)
)
else:
pull_uri = 'ipc://{0}'.format(
os.path.join(self.opts['sock_dir'], 'publish_pull.ipc')
)
log.debug("Connecting to pub server: %s", pull_uri)
self.pub_sock.connect(pull_uri)
return self._sock_data.sock |
def pub_close(self):
'''
Disconnect an existing publisher socket and remove it from the local
thread's cache.
'''
if hasattr(self._sock_data, 'sock'):
self._sock_data.sock.close()
delattr(self._sock_data, 'sock') |
def publish(self, load):
'''
Publish "load" to minions. This send the load to the publisher daemon
process with does the actual sending to minions.
:param dict load: A load to be sent across the wire to minions
'''
payload = {'enc': 'aes'}
crypticle = salt.crypt.Crypticle(self.opts, salt.master.SMaster.secrets['aes']['secret'].value)
payload['load'] = crypticle.dumps(load)
if self.opts['sign_pub_messages']:
master_pem_path = os.path.join(self.opts['pki_dir'], 'master.pem')
log.debug("Signing data packet")
payload['sig'] = salt.crypt.sign_message(master_pem_path, payload['load'])
int_payload = {'payload': self.serial.dumps(payload)}
# add some targeting stuff for lists only (for now)
if load['tgt_type'] == 'list':
int_payload['topic_lst'] = load['tgt']
# If zmq_filtering is enabled, target matching has to happen master side
match_targets = ["pcre", "glob", "list"]
if self.opts['zmq_filtering'] and load['tgt_type'] in match_targets:
# Fetch a list of minions that match
_res = self.ckminions.check_minions(load['tgt'],
tgt_type=load['tgt_type'])
match_ids = _res['minions']
log.debug("Publish Side Match: %s", match_ids)
# Send list of miions thru so zmq can target them
int_payload['topic_lst'] = match_ids
payload = self.serial.dumps(int_payload)
log.debug(
'Sending payload to publish daemon. jid=%s size=%d',
load.get('jid', None), len(payload),
)
if not self.pub_sock:
self.pub_connect()
self.pub_sock.send(payload)
log.debug('Sent payload to publish daemon.') |
def timeout_message(self, message):
'''
Handle a message timeout by removing it from the sending queue
and informing the caller
:raises: SaltReqTimeoutError
'''
future = self.send_future_map.pop(message, None)
# In a race condition the message might have been sent by the time
# we're timing it out. Make sure the future is not None
if future is not None:
del self.send_timeout_map[message]
if future.attempts < future.tries:
future.attempts += 1
log.debug('SaltReqTimeoutError, retrying. (%s/%s)', future.attempts, future.tries)
self.send(
message,
timeout=future.timeout,
tries=future.tries,
future=future,
)
else:
future.set_exception(SaltReqTimeoutError('Message timed out')) |
def send(self, message, timeout=None, tries=3, future=None, callback=None, raw=False):
'''
Return a future which will be completed when the message has a response
'''
if future is None:
future = tornado.concurrent.Future()
future.tries = tries
future.attempts = 0
future.timeout = timeout
# if a future wasn't passed in, we need to serialize the message
message = self.serial.dumps(message)
if callback is not None:
def handle_future(future):
response = future.result()
self.io_loop.add_callback(callback, response)
future.add_done_callback(handle_future)
# Add this future to the mapping
self.send_future_map[message] = future
if self.opts.get('detect_mode') is True:
timeout = 1
if timeout is not None:
send_timeout = self.io_loop.call_later(timeout, self.timeout_message, message)
self.send_timeout_map[message] = send_timeout
if not self.send_queue:
self.io_loop.spawn_callback(self._internal_send_recv)
self.send_queue.append(message)
return future |
def _get_instance(hosts=None, profile=None):
'''
Return the elasticsearch instance
'''
es = None
proxies = None
use_ssl = False
ca_certs = None
verify_certs = True
http_auth = None
timeout = 10
if profile is None:
profile = 'elasticsearch'
if isinstance(profile, six.string_types):
_profile = __salt__['config.option'](profile, None)
elif isinstance(profile, dict):
_profile = profile
if _profile:
hosts = _profile.get('host', hosts)
if not hosts:
hosts = _profile.get('hosts', hosts)
proxies = _profile.get('proxies', None)
use_ssl = _profile.get('use_ssl', False)
ca_certs = _profile.get('ca_certs', None)
verify_certs = _profile.get('verify_certs', True)
username = _profile.get('username', None)
password = _profile.get('password', None)
timeout = _profile.get('timeout', 10)
if username and password:
http_auth = (username, password)
if not hosts:
hosts = ['127.0.0.1:9200']
if isinstance(hosts, six.string_types):
hosts = [hosts]
try:
if proxies:
# Custom connection class to use requests module with proxies
class ProxyConnection(RequestsHttpConnection):
def __init__(self, *args, **kwargs):
proxies = kwargs.pop('proxies', {})
super(ProxyConnection, self).__init__(*args, **kwargs)
self.session.proxies = proxies
es = elasticsearch.Elasticsearch(
hosts,
connection_class=ProxyConnection,
proxies=proxies,
use_ssl=use_ssl,
ca_certs=ca_certs,
verify_certs=verify_certs,
http_auth=http_auth,
timeout=timeout,
)
else:
es = elasticsearch.Elasticsearch(
hosts,
use_ssl=use_ssl,
ca_certs=ca_certs,
verify_certs=verify_certs,
http_auth=http_auth,
timeout=timeout,
)
# Try the connection
es.info()
except elasticsearch.exceptions.TransportError as err:
raise CommandExecutionError(
'Could not connect to Elasticsearch host/ cluster {0} due to {1}'.format(hosts, err))
return es |
def ping(allow_failure=False, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Test connection to Elasticsearch instance. This method does not fail if not explicitly specified.
allow_failure
Throw exception if ping fails
CLI example::
salt myminion elasticsearch.ping allow_failure=True
salt myminion elasticsearch.ping profile=elasticsearch-extra
'''
try:
_get_instance(hosts, profile)
except CommandExecutionError as e:
if allow_failure:
raise e
return False
return True |
def info(hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Return Elasticsearch information.
CLI example::
salt myminion elasticsearch.info
salt myminion elasticsearch.info profile=elasticsearch-extra
'''
es = _get_instance(hosts, profile)
try:
return es.info()
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot retrieve server information, server returned code {0} with message {1}".format(e.status_code, e.error)) |
def node_info(nodes=None, flat_settings=False, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Return Elasticsearch node information.
nodes
List of cluster nodes (id or name) to display stats for. Use _local for connected node, empty for all
flat_settings
Flatten settings keys
CLI example::
salt myminion elasticsearch.node_info flat_settings=True
'''
es = _get_instance(hosts, profile)
try:
return es.nodes.info(node_id=nodes, flat_settings=flat_settings)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot retrieve node information, server returned code {0} with message {1}".format(e.status_code, e.error)) |
def cluster_health(index=None, level='cluster', local=False, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Return Elasticsearch cluster health.
index
Limit the information returned to a specific index
level
Specify the level of detail for returned information, default 'cluster', valid choices are: 'cluster', 'indices', 'shards'
local
Return local information, do not retrieve the state from master node
CLI example::
salt myminion elasticsearch.cluster_health
'''
es = _get_instance(hosts, profile)
try:
return es.cluster.health(index=index, level=level, local=local)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot retrieve health information, server returned code {0} with message {1}".format(e.status_code, e.error)) |
def cluster_stats(nodes=None, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Return Elasticsearch cluster stats.
nodes
List of cluster nodes (id or name) to display stats for. Use _local for connected node, empty for all
CLI example::
salt myminion elasticsearch.cluster_stats
'''
es = _get_instance(hosts, profile)
try:
return es.cluster.stats(node_id=nodes)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot retrieve cluster stats, server returned code {0} with message {1}".format(e.status_code, e.error)) |
def alias_create(indices, alias, hosts=None, body=None, profile=None, source=None):
'''
Create an alias for a specific index/indices
indices
Single or multiple indices separated by comma, use _all to perform the operation on all indices.
alias
Alias name
body
Optional definition such as routing or filter as defined in https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-aliases.html
source
URL of file specifying optional definition such as routing or filter. Cannot be used in combination with ``body``.
CLI example::
salt myminion elasticsearch.alias_create testindex_v1 testindex
'''
es = _get_instance(hosts, profile)
if source and body:
message = 'Either body or source should be specified but not both.'
raise SaltInvocationError(message)
if source:
body = __salt__['cp.get_file_str'](
source,
saltenv=__opts__.get('saltenv', 'base'))
try:
result = es.indices.put_alias(index=indices, name=alias, body=body)
return result.get('acknowledged', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot create alias {0} in index {1}, server returned code {2} with message {3}".format(alias, indices, e.status_code, e.error)) |
def alias_delete(indices, aliases, hosts=None, body=None, profile=None, source=None):
'''
Delete an alias of an index
indices
Single or multiple indices separated by comma, use _all to perform the operation on all indices.
aliases
Alias names separated by comma
CLI example::
salt myminion elasticsearch.alias_delete testindex_v1 testindex
'''
es = _get_instance(hosts, profile)
if source and body:
message = 'Either body or source should be specified but not both.'
raise SaltInvocationError(message)
if source:
body = __salt__['cp.get_file_str'](
source,
saltenv=__opts__.get('saltenv', 'base'))
try:
result = es.indices.delete_alias(index=indices, name=aliases)
return result.get('acknowledged', False)
except elasticsearch.exceptions.NotFoundError:
return True
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot delete alias {0} in index {1}, server returned code {2} with message {3}".format(aliases, indices, e.status_code, e.error)) |
def alias_exists(aliases, indices=None, hosts=None, profile=None):
'''
Return a boolean indicating whether given alias exists
indices
Single or multiple indices separated by comma, use _all to perform the operation on all indices.
aliases
Alias names separated by comma
CLI example::
salt myminion elasticsearch.alias_exists None testindex
'''
es = _get_instance(hosts, profile)
try:
return es.indices.exists_alias(name=aliases, index=indices)
except elasticsearch.exceptions.NotFoundError:
return False
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot get alias {0} in index {1}, server returned code {2} with message {3}".format(aliases, indices, e.status_code, e.error)) |
def alias_get(indices=None, aliases=None, hosts=None, profile=None):
'''
Check for the existence of an alias and if it exists, return it
indices
Single or multiple indices separated by comma, use _all to perform the operation on all indices.
aliases
Alias names separated by comma
CLI example::
salt myminion elasticsearch.alias_get testindex
'''
es = _get_instance(hosts, profile)
try:
return es.indices.get_alias(index=indices, name=aliases)
except elasticsearch.exceptions.NotFoundError:
return None
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot get alias {0} in index {1}, server returned code {2} with message {3}".format(aliases, indices, e.status_code, e.error)) |
def document_create(index, doc_type, body=None, id=None, hosts=None, profile=None, source=None):
'''
Create a document in a specified index
index
Index name where the document should reside
doc_type
Type of the document
body
Document to store
source
URL of file specifying document to store. Cannot be used in combination with ``body``.
id
Optional unique document identifier for specified doc_type (empty for random)
CLI example::
salt myminion elasticsearch.document_create testindex doctype1 '{}'
'''
es = _get_instance(hosts, profile)
if source and body:
message = 'Either body or source should be specified but not both.'
raise SaltInvocationError(message)
if source:
body = __salt__['cp.get_file_str'](
source,
saltenv=__opts__.get('saltenv', 'base'))
try:
return es.index(index=index, doc_type=doc_type, body=body, id=id)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot create document in index {0}, server returned code {1} with message {2}".format(index, e.status_code, e.error)) |
def document_delete(index, doc_type, id, hosts=None, profile=None):
'''
Delete a document from an index
index
Index name where the document resides
doc_type
Type of the document
id
Document identifier
CLI example::
salt myminion elasticsearch.document_delete testindex doctype1 AUx-384m0Bug_8U80wQZ
'''
es = _get_instance(hosts, profile)
try:
return es.delete(index=index, doc_type=doc_type, id=id)
except elasticsearch.exceptions.NotFoundError:
return None
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot delete document {0} in index {1}, server returned code {2} with message {3}".format(id, index, e.status_code, e.error)) |
def document_exists(index, id, doc_type='_all', hosts=None, profile=None):
'''
Return a boolean indicating whether given document exists
index
Index name where the document resides
id
Document identifier
doc_type
Type of the document, use _all to fetch the first document matching the ID across all types
CLI example::
salt myminion elasticsearch.document_exists testindex AUx-384m0Bug_8U80wQZ
'''
es = _get_instance(hosts, profile)
try:
return es.exists(index=index, id=id, doc_type=doc_type)
except elasticsearch.exceptions.NotFoundError:
return False
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot retrieve document {0} from index {1}, server returned code {2} with message {3}".format(id, index, e.status_code, e.error)) |
def index_create(index, body=None, hosts=None, profile=None, source=None):
'''
Create an index
index
Index name
body
Index definition, such as settings and mappings as defined in https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-create-index.html
source
URL to file specifying index definition. Cannot be used in combination with ``body``.
CLI example::
salt myminion elasticsearch.index_create testindex
salt myminion elasticsearch.index_create testindex2 '{"settings" : {"index" : {"number_of_shards" : 3, "number_of_replicas" : 2}}}'
'''
es = _get_instance(hosts, profile)
if source and body:
message = 'Either body or source should be specified but not both.'
raise SaltInvocationError(message)
if source:
body = __salt__['cp.get_file_str'](
source,
saltenv=__opts__.get('saltenv', 'base'))
try:
result = es.indices.create(index=index, body=body)
return result.get('acknowledged', False) and result.get("shards_acknowledged", True)
except elasticsearch.TransportError as e:
if "index_already_exists_exception" == e.error:
return True
raise CommandExecutionError("Cannot create index {0}, server returned code {1} with message {2}".format(index, e.status_code, e.error)) |
def index_delete(index, hosts=None, profile=None):
'''
Delete an index
index
Index name
CLI example::
salt myminion elasticsearch.index_delete testindex
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.delete(index=index)
return result.get('acknowledged', False)
except elasticsearch.exceptions.NotFoundError:
return True
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot delete index {0}, server returned code {1} with message {2}".format(index, e.status_code, e.error)) |
def index_exists(index, hosts=None, profile=None):
'''
Return a boolean indicating whether given index exists
index
Index name
CLI example::
salt myminion elasticsearch.index_exists testindex
'''
es = _get_instance(hosts, profile)
try:
return es.indices.exists(index=index)
except elasticsearch.exceptions.NotFoundError:
return False
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot retrieve index {0}, server returned code {1} with message {2}".format(index, e.status_code, e.error)) |
def index_get(index, hosts=None, profile=None):
'''
Check for the existence of an index and if it exists, return it
index
Index name
CLI example::
salt myminion elasticsearch.index_get testindex
'''
es = _get_instance(hosts, profile)
try:
return es.indices.get(index=index)
except elasticsearch.exceptions.NotFoundError:
return None
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot retrieve index {0}, server returned code {1} with message {2}".format(index, e.status_code, e.error)) |
def index_open(index, allow_no_indices=True, expand_wildcards='closed', ignore_unavailable=True, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Open specified index.
index
Index to be opened
allow_no_indices
Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes _all string or when no indices have been specified)
expand_wildcards
Whether to expand wildcard expression to concrete indices that are open, closed or both., default ‘closed’, valid choices are: ‘open’, ‘closed’, ‘none’, ‘all’
ignore_unavailable
Whether specified concrete indices should be ignored when unavailable (missing or closed)
CLI example::
salt myminion elasticsearch.index_open testindex
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.open(index=index, allow_no_indices=allow_no_indices, expand_wildcards=expand_wildcards, ignore_unavailable=ignore_unavailable)
return result.get('acknowledged', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot open index {0}, server returned code {1} with message {2}".format(index, e.status_code, e.error)) |
def mapping_create(index, doc_type, body=None, hosts=None, profile=None, source=None):
'''
Create a mapping in a given index
index
Index for the mapping
doc_type
Name of the document type
body
Mapping definition as specified in https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-put-mapping.html
source
URL to file specifying mapping definition. Cannot be used in combination with ``body``.
CLI example::
salt myminion elasticsearch.mapping_create testindex user '{ "user" : { "properties" : { "message" : {"type" : "string", "store" : true } } } }'
'''
es = _get_instance(hosts, profile)
if source and body:
message = 'Either body or source should be specified but not both.'
raise SaltInvocationError(message)
if source:
body = __salt__['cp.get_file_str'](
source,
saltenv=__opts__.get('saltenv', 'base'))
try:
result = es.indices.put_mapping(index=index, doc_type=doc_type, body=body)
return result.get('acknowledged', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot create mapping {0}, server returned code {1} with message {2}".format(index, e.status_code, e.error)) |
def mapping_delete(index, doc_type, hosts=None, profile=None):
'''
Delete a mapping (type) along with its data. As of Elasticsearch 5.0 this is no longer available.
index
Index for the mapping
doc_type
Name of the document type
CLI example::
salt myminion elasticsearch.mapping_delete testindex user
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.delete_mapping(index=index, doc_type=doc_type)
return result.get('acknowledged', False)
except elasticsearch.exceptions.NotFoundError:
return True
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot delete mapping {0}, server returned code {1} with message {2}".format(index, e.status_code, e.error))
except AttributeError:
raise CommandExecutionError("Method is not applicable for Elasticsearch 5.0+") |
def mapping_get(index, doc_type, hosts=None, profile=None):
'''
Retrieve mapping definition of index or index/type
index
Index for the mapping
doc_type
Name of the document type
CLI example::
salt myminion elasticsearch.mapping_get testindex user
'''
es = _get_instance(hosts, profile)
try:
return es.indices.get_mapping(index=index, doc_type=doc_type)
except elasticsearch.exceptions.NotFoundError:
return None
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot retrieve mapping {0}, server returned code {1} with message {2}".format(index, e.status_code, e.error)) |
def index_template_create(name, body=None, hosts=None, profile=None, source=None):
'''
Create an index template
name
Index template name
body
Template definition as specified in http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-templates.html
source
URL to file specifying template definition. Cannot be used in combination with ``body``.
CLI example::
salt myminion elasticsearch.index_template_create testindex_templ '{ "template": "logstash-*", "order": 1, "settings": { "number_of_shards": 1 } }'
'''
es = _get_instance(hosts, profile)
if source and body:
message = 'Either body or source should be specified but not both.'
raise SaltInvocationError(message)
if source:
body = __salt__['cp.get_file_str'](
source,
saltenv=__opts__.get('saltenv', 'base'))
try:
result = es.indices.put_template(name=name, body=body)
return result.get('acknowledged', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot create template {0}, server returned code {1} with message {2}".format(name, e.status_code, e.error)) |
def index_template_delete(name, hosts=None, profile=None):
'''
Delete an index template (type) along with its data
name
Index template name
CLI example::
salt myminion elasticsearch.index_template_delete testindex_templ user
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.delete_template(name=name)
return result.get('acknowledged', False)
except elasticsearch.exceptions.NotFoundError:
return True
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot delete template {0}, server returned code {1} with message {2}".format(name, e.status_code, e.error)) |
def index_template_exists(name, hosts=None, profile=None):
'''
Return a boolean indicating whether given index template exists
name
Index template name
CLI example::
salt myminion elasticsearch.index_template_exists testindex_templ
'''
es = _get_instance(hosts, profile)
try:
return es.indices.exists_template(name=name)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot retrieve template {0}, server returned code {1} with message {2}".format(name, e.status_code, e.error)) |
def index_template_get(name, hosts=None, profile=None):
'''
Retrieve template definition of index or index/type
name
Index template name
CLI example::
salt myminion elasticsearch.index_template_get testindex_templ
'''
es = _get_instance(hosts, profile)
try:
return es.indices.get_template(name=name)
except elasticsearch.exceptions.NotFoundError:
return None
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot retrieve template {0}, server returned code {1} with message {2}".format(name, e.status_code, e.error)) |
def pipeline_get(id, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Retrieve Ingest pipeline definition. Available since Elasticsearch 5.0.
id
Pipeline id
CLI example::
salt myminion elasticsearch.pipeline_get mypipeline
'''
es = _get_instance(hosts, profile)
try:
return es.ingest.get_pipeline(id=id)
except elasticsearch.NotFoundError:
return None
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot create pipeline {0}, server returned code {1} with message {2}".format(id, e.status_code, e.error))
except AttributeError:
raise CommandExecutionError("Method is applicable only for Elasticsearch 5.0+") |
def pipeline_delete(id, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Delete Ingest pipeline. Available since Elasticsearch 5.0.
id
Pipeline id
CLI example::
salt myminion elasticsearch.pipeline_delete mypipeline
'''
es = _get_instance(hosts, profile)
try:
ret = es.ingest.delete_pipeline(id=id)
return ret.get('acknowledged', False)
except elasticsearch.NotFoundError:
return True
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot delete pipeline {0}, server returned code {1} with message {2}".format(id, e.status_code, e.error))
except AttributeError:
raise CommandExecutionError("Method is applicable only for Elasticsearch 5.0+") |
def pipeline_create(id, body, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Create Ingest pipeline by supplied definition. Available since Elasticsearch 5.0.
id
Pipeline id
body
Pipeline definition as specified in https://www.elastic.co/guide/en/elasticsearch/reference/master/pipeline.html
CLI example::
salt myminion elasticsearch.pipeline_create mypipeline '{"description": "my custom pipeline", "processors": [{"set" : {"field": "collector_timestamp_millis", "value": "{{_ingest.timestamp}}"}}]}'
'''
es = _get_instance(hosts, profile)
try:
out = es.ingest.put_pipeline(id=id, body=body)
return out.get('acknowledged', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot create pipeline {0}, server returned code {1} with message {2}".format(id, e.status_code, e.error))
except AttributeError:
raise CommandExecutionError("Method is applicable only for Elasticsearch 5.0+") |
def pipeline_simulate(id, body, verbose=False, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Simulate existing Ingest pipeline on provided data. Available since Elasticsearch 5.0.
id
Pipeline id
body
Pipeline definition as specified in https://www.elastic.co/guide/en/elasticsearch/reference/master/pipeline.html
verbose
Specify if the output should be more verbose
CLI example::
salt myminion elasticsearch.pipeline_simulate mypipeline '{"docs":[{"_index":"index","_type":"type","_id":"id","_source":{"foo":"bar"}},{"_index":"index","_type":"type","_id":"id","_source":{"foo":"rab"}}]}' verbose=True
'''
es = _get_instance(hosts, profile)
try:
return es.ingest.simulate(id=id, body=body, verbose=verbose)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot simulate pipeline {0}, server returned code {1} with message {2}".format(id, e.status_code, e.error))
except AttributeError:
raise CommandExecutionError("Method is applicable only for Elasticsearch 5.0+") |
def search_template_get(id, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Obtain existing search template definition.
id
Template ID
CLI example::
salt myminion elasticsearch.search_template_get mytemplate
'''
es = _get_instance(hosts, profile)
try:
return es.get_template(id=id)
except elasticsearch.NotFoundError:
return None
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot obtain search template {0}, server returned code {1} with message {2}".format(id, e.status_code, e.error)) |
def search_template_create(id, body, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Create search template by supplied definition
id
Template ID
body
Search template definition
CLI example::
salt myminion elasticsearch.search_template_create mytemplate '{"template":{"query":{"match":{"title":"{{query_string}}"}}}}'
'''
es = _get_instance(hosts, profile)
try:
result = es.put_template(id=id, body=body)
return result.get('acknowledged', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot create search template {0}, server returned code {1} with message {2}".format(id, e.status_code, e.error)) |
def search_template_delete(id, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Delete existing search template definition.
id
Template ID
CLI example::
salt myminion elasticsearch.search_template_delete mytemplate
'''
es = _get_instance(hosts, profile)
try:
result = es.delete_template(id=id)
return result.get('acknowledged', False)
except elasticsearch.NotFoundError:
return True
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot delete search template {0}, server returned code {1} with message {2}".format(id, e.status_code, e.error)) |
def repository_get(name, local=False, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Get existing repository details.
name
Repository name
local
Retrieve only local information, default is false
CLI example::
salt myminion elasticsearch.repository_get testrepo
'''
es = _get_instance(hosts, profile)
try:
return es.snapshot.get_repository(repository=name, local=local)
except elasticsearch.NotFoundError:
return None
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot obtain repository {0}, server returned code {1} with message {2}".format(name, e.status_code, e.error)) |
def repository_create(name, body, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Create repository for storing snapshots. Note that shared repository paths have to be specified in path.repo Elasticsearch configuration option.
name
Repository name
body
Repository definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
CLI example::
salt myminion elasticsearch.repository_create testrepo '{"type":"fs","settings":{"location":"/tmp/test","compress":true}}'
'''
es = _get_instance(hosts, profile)
try:
result = es.snapshot.create_repository(repository=name, body=body)
return result.get('acknowledged', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot create repository {0}, server returned code {1} with message {2}".format(name, e.status_code, e.error)) |
def repository_delete(name, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Delete existing repository.
name
Repository name
CLI example::
salt myminion elasticsearch.repository_delete testrepo
'''
es = _get_instance(hosts, profile)
try:
result = es.snapshot.delete_repository(repository=name)
return result.get('acknowledged', False)
except elasticsearch.NotFoundError:
return True
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot delete repository {0}, server returned code {1} with message {2}".format(name, e.status_code, e.error)) |
def repository_verify(name, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Obtain list of cluster nodes which successfully verified this repository.
name
Repository name
CLI example::
salt myminion elasticsearch.repository_verify testrepo
'''
es = _get_instance(hosts, profile)
try:
return es.snapshot.verify_repository(repository=name)
except elasticsearch.NotFoundError:
return None
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot verify repository {0}, server returned code {1} with message {2}".format(name, e.status_code, e.error)) |
def snapshot_status(repository=None, snapshot=None, ignore_unavailable=False, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Obtain status of all currently running snapshots.
repository
Particular repository to look for snapshots
snapshot
Snapshot name
ignore_unavailable
Ignore unavailable snapshots
CLI example::
salt myminion elasticsearch.snapshot_status ignore_unavailable=True
'''
es = _get_instance(hosts, profile)
try:
return es.snapshot.status(repository=repository, snapshot=snapshot, ignore_unavailable=ignore_unavailable)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot obtain snapshot status, server returned code {0} with message {1}".format(e.status_code, e.error)) |
def snapshot_get(repository, snapshot, ignore_unavailable=False, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Obtain snapshot residing in specified repository.
repository
Repository name
snapshot
Snapshot name, use _all to obtain all snapshots in specified repository
ignore_unavailable
Ignore unavailable snapshots
CLI example::
salt myminion elasticsearch.snapshot_get testrepo testsnapshot
'''
es = _get_instance(hosts, profile)
try:
return es.snapshot.get(repository=repository, snapshot=snapshot, ignore_unavailable=ignore_unavailable)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot obtain details of snapshot {0} in repository {1}, server returned code {2} with message {3}".format(snapshot, repository, e.status_code, e.error)) |
def snapshot_create(repository, snapshot, body=None, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Create snapshot in specified repository by supplied definition.
repository
Repository name
snapshot
Snapshot name
body
Snapshot definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
CLI example::
salt myminion elasticsearch.snapshot_create testrepo testsnapshot '{"indices":"index_1,index_2","ignore_unavailable":true,"include_global_state":false}'
'''
es = _get_instance(hosts, profile)
try:
response = es.snapshot.create(repository=repository, snapshot=snapshot, body=body)
return response.get('accepted', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot create snapshot {0} in repository {1}, server returned code {2} with message {3}".format(snapshot, repository, e.status_code, e.error)) |
def snapshot_delete(repository, snapshot, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Delete snapshot from specified repository.
repository
Repository name
snapshot
Snapshot name
CLI example::
salt myminion elasticsearch.snapshot_delete testrepo testsnapshot
'''
es = _get_instance(hosts, profile)
try:
result = es.snapshot.delete(repository=repository, snapshot=snapshot)
return result.get('acknowledged', False)
except elasticsearch.NotFoundError:
return True
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot delete snapshot {0} from repository {1}, server returned code {2} with message {3}".format(snapshot, repository, e.status_code, e.error)) |
def installed(name, channel=None):
'''
Ensure that the named snap package is installed
name
The snap package
channel
Optional. The channel to install the package from.
'''
ret = {'name': name,
'changes': {},
'pchanges': {},
'result': None,
'comment': ''}
old = __salt__['snap.versions_installed'](name)
if not old:
if __opts__['test']:
ret['comment'] = 'Package "{0}" would have been installed'.format(name)
ret['pchanges']['new'] = name
ret['pchanges']['old'] = None
ret['result'] = None
return ret
install = __salt__['snap.install'](name, channel=channel)
if install['result']:
ret['comment'] = 'Package "{0}" was installed'.format(name)
ret['changes']['new'] = name
ret['changes']['old'] = None
ret['result'] = True
return ret
ret['comment'] = 'Package "{0}" failed to install'.format(name)
ret['comment'] += '\noutput:\n' + install['output']
ret['result'] = False
return ret
# Currently snap always returns only one line?
old_channel = old[0]['tracking']
if old_channel != channel and channel is not None:
if __opts__['test']:
ret['comment'] = 'Package "{0}" would have been switched to channel {1}'.format(name, channel)
ret['pchanges']['old_channel'] = old_channel
ret['pchanges']['new_channel'] = channel
ret['result'] = None
return ret
refresh = __salt__['snap.install'](name, channel=channel, refresh=True)
if refresh['result']:
ret['comment'] = 'Package "{0}" was switched to channel {1}'.format(name, channel)
ret['pchanges']['old_channel'] = old_channel
ret['pchanges']['new_channel'] = channel
ret['result'] = True
return ret
ret['comment'] = 'Failed to switch Package "{0}" to channel {1}'.format(name, channel)
ret['comment'] += '\noutput:\n' + install['output']
ret['result'] = False
return ret
ret['comment'] = 'Package "{0}" is already installed'.format(name)
if __opts__['test']:
ret['result'] = None
return ret
ret['result'] = True
return ret |
def removed(name):
'''
Ensure that the named snap package is not installed
name
The snap package
'''
ret = {'name': name,
'changes': {},
'pchanges': {},
'result': None,
'comment': ''}
old = __salt__['snap.versions_installed'](name)
if not old:
ret['comment'] = 'Package {0} is not installed'.format(name)
ret['result'] = True
return ret
if __opts__['test']:
ret['comment'] = 'Package {0} would have been removed'.format(name)
ret['result'] = None
ret['pchanges']['old'] = old[0]['version']
ret['pchanges']['new'] = None
return ret
remove = __salt__['snap.remove'](name)
ret['comment'] = 'Package {0} removed'.format(name)
ret['result'] = True
ret['changes']['old'] = old[0]['version']
ret['changes']['new'] = None
return ret |
def _get_queue(config):
'''
Check the context for the notifier and construct it if not present
'''
if 'watchdog.observer' not in __context__:
queue = collections.deque()
observer = Observer()
for path in config.get('directories', {}):
path_params = config.get('directories').get(path)
masks = path_params.get('mask', DEFAULT_MASK)
event_handler = Handler(queue, masks)
observer.schedule(event_handler, path)
observer.start()
__context__['watchdog.observer'] = observer
__context__['watchdog.queue'] = queue
return __context__['watchdog.queue'] |
def validate(config):
'''
Validate the beacon configuration
'''
try:
_validate(config)
return True, 'Valid beacon configuration'
except ValidationError as error:
return False, str(error) |
def beacon(config):
'''
Watch the configured directories
Example Config
.. code-block:: yaml
beacons:
watchdog:
- directories:
/path/to/dir:
mask:
- create
- modify
- delete
- move
The mask list can contain the following events (the default mask is create,
modify delete, and move):
* create - File or directory is created in watched directory
* modify - The watched directory is modified
* delete - File or directory is deleted from watched directory
* move - File or directory is moved or renamed in the watched directory
'''
_config = {}
list(map(_config.update, config))
queue = _get_queue(_config)
ret = []
while queue:
ret.append(to_salt_event(queue.popleft()))
return ret |
def bounce_cluster(name):
'''
Bounce all Traffic Server nodes in the cluster. Bouncing Traffic Server
shuts down and immediately restarts Traffic Server, node-by-node.
.. code-block:: yaml
bounce_ats_cluster:
trafficserver.bounce_cluster
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
if __opts__['test']:
ret['comment'] = 'Bouncing cluster'
return ret
__salt__['trafficserver.bounce_cluster']()
ret['result'] = True
ret['comment'] = 'Bounced cluster'
return ret |
def bounce_local(name, drain=False):
'''
Bounce Traffic Server on the local node. Bouncing Traffic Server shuts down
and immediately restarts the Traffic Server node.
This option modifies the behavior of traffic_line -b and traffic_line -L
such that traffic_server is not shut down until the number of active client
connections drops to the number given by the
proxy.config.restart.active_client_threshold configuration variable.
.. code-block:: yaml
bounce_ats_local:
trafficserver.bounce_local
bounce_ats_local:
trafficserver.bounce_local
- drain: True
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
if __opts__['test']:
ret['comment'] = 'Bouncing local node'
return ret
if drain:
__salt__['trafficserver.bounce_local'](drain=True)
ret['result'] = True
ret['comment'] = 'Bounced local node with drain option'
return ret
else:
__salt__['trafficserver.bounce_local']()
ret['result'] = True
ret['comment'] = 'Bounced local node'
return ret |
def clear_cluster(name):
'''
Clears accumulated statistics on all nodes in the cluster.
.. code-block:: yaml
clear_ats_cluster:
trafficserver.clear_cluster
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
if __opts__['test']:
ret['comment'] = 'Clearing cluster statistics'
return ret
__salt__['trafficserver.clear_cluster']()
ret['result'] = True
ret['comment'] = 'Cleared cluster statistics'
return ret |
def clear_node(name):
'''
Clears accumulated statistics on the local node.
.. code-block:: yaml
clear_ats_node:
trafficserver.clear_node
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
if __opts__['test']:
ret['comment'] = 'Clearing local node statistics'
return ret
__salt__['trafficserver.clear_node']()
ret['result'] = True
ret['comment'] = 'Cleared local node statistics'
return ret |
def restart_cluster(name):
'''
Restart the traffic_manager process and the traffic_server process on all
the nodes in a cluster.
.. code-block:: bash
restart_ats_cluster:
trafficserver.restart_cluster
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
if __opts__['test']:
ret['comment'] = 'Restarting cluster'
return ret
__salt__['trafficserver.restart_cluster']()
ret['result'] = True
ret['comment'] = 'Restarted cluster'
return ret |
def restart_local(name, drain=False):
'''
Restart the traffic_manager and traffic_server processes on the local node.
This option modifies the behavior of traffic_line -b and traffic_line -L
such that traffic_server is not shut down until the number of active client
connections drops to the number given by the
proxy.config.restart.active_client_threshold configuration variable.
.. code-block:: yaml
restart_ats_local:
trafficserver.restart_local
restart_ats_local_drain:
trafficserver.restart_local
- drain: True
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
if __opts__['test']:
ret['comment'] = 'Restarting local node'
return ret
if drain:
__salt__['trafficserver.restart_local'](drain=True)
ret['result'] = True
ret['comment'] = 'Restarted local node with drain option'
return ret
else:
__salt__['trafficserver.restart_local']()
ret['result'] = True
ret['comment'] = 'Restarted local node'
return ret |
def config(name, value):
'''
Set Traffic Server configuration variable values.
.. code-block:: yaml
proxy.config.proxy_name:
trafficserver.config:
- value: cdn.site.domain.tld
OR
traffic_server_setting:
trafficserver.config:
- name: proxy.config.proxy_name
- value: cdn.site.domain.tld
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
if __opts__['test']:
ret['comment'] = 'Configuring {0} to {1}'.format(
name,
value,
)
return ret
__salt__['trafficserver.set_config'](name, value)
ret['result'] = True
ret['comment'] = 'Configured {0} to {1}'.format(name, value)
return ret |
def shutdown(name):
'''
Shut down Traffic Server on the local node.
.. code-block:: yaml
shutdown_ats:
trafficserver.shutdown
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
if __opts__['test']:
ret['comment'] = 'Shutting down local node'
return ret
__salt__['trafficserver.shutdown']()
ret['result'] = True
ret['comment'] = 'Shutdown local node'
return ret |
def startup(name):
'''
Start Traffic Server on the local node.
.. code-block:: yaml
startup_ats:
trafficserver.startup
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
if __opts__['test']:
ret['comment'] = 'Starting up local node'
return ret
__salt__['trafficserver.startup']()
ret['result'] = True
ret['comment'] = 'Starting up local node'
return ret |
def refresh(name):
'''
Initiate a Traffic Server configuration file reread. Use this command to
update the running configuration after any configuration file modification.
The timestamp of the last reconfiguration event (in seconds since epoch) is
published in the proxy.node.config.reconfigure_time metric.
.. code-block:: yaml
refresh_ats:
trafficserver.refresh
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
if __opts__['test']:
ret['comment'] = 'Refreshing local node configuration'
return ret
__salt__['trafficserver.refresh']()
ret['result'] = True
ret['comment'] = 'Refreshed local node configuration'
return ret |
def zero_cluster(name):
'''
Reset performance statistics to zero across the cluster.
.. code-block:: yaml
zero_ats_cluster:
trafficserver.zero_cluster
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
if __opts__['test']:
ret['comment'] = 'Zeroing cluster statistics'
return ret
__salt__['trafficserver.zero_cluster']()
ret['result'] = True
ret['comment'] = 'Zeroed cluster statistics'
return ret |
def zero_node(name):
'''
Reset performance statistics to zero on the local node.
.. code-block:: yaml
zero_ats_node:
trafficserver.zero_node
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
if __opts__['test']:
ret['comment'] = 'Zeroing local node statistics'
return ret
__salt__['trafficserver.zero_node']()
ret['result'] = True
ret['comment'] = 'Zeroed local node statistics'
return ret |
def offline(name, path):
'''
Mark a cache storage device as offline. The storage is identified by a path
which must match exactly a path specified in storage.config. This removes
the storage from the cache and redirects requests that would have used this
storage to other storage. This has exactly the same effect as a disk
failure for that storage. This does not persist across restarts of the
traffic_server process.
.. code-block:: yaml
offline_ats_path:
trafficserver.offline:
- path: /path/to/cache
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
if __opts__['test']:
ret['comment'] = 'Setting {0} to offline'.format(path)
return ret
__salt__['trafficserver.offline'](path)
ret['result'] = True
ret['comment'] = 'Set {0} as offline'.format(path)
return ret |
def present(name,
type,
url,
access='proxy',
user='',
password='',
database='',
basic_auth=False,
basic_auth_user='',
basic_auth_password='',
is_default=False,
json_data=None,
profile='grafana'):
'''
Ensure that a data source is present.
name
Name of the data source.
type
Which type of data source it is ('graphite', 'influxdb' etc.).
url
The URL to the data source API.
user
Optional - user to authenticate with the data source
password
Optional - password to authenticate with the data source
basic_auth
Optional - set to True to use HTTP basic auth to authenticate with the
data source.
basic_auth_user
Optional - HTTP basic auth username.
basic_auth_password
Optional - HTTP basic auth password.
is_default
Default: False
'''
if isinstance(profile, string_types):
profile = __salt__['config.option'](profile)
ret = {'name': name, 'result': None, 'comment': None, 'changes': {}}
datasource = _get_datasource(profile, name)
data = _get_json_data(name, type, url, access, user, password, database,
basic_auth, basic_auth_user, basic_auth_password, is_default, json_data)
if datasource:
requests.put(
_get_url(profile, datasource['id']),
data,
headers=_get_headers(profile),
timeout=profile.get('grafana_timeout', 3),
)
ret['result'] = True
ret['changes'] = _diff(datasource, data)
if ret['changes']['new'] or ret['changes']['old']:
ret['comment'] = 'Data source {0} updated'.format(name)
else:
ret['changes'] = {}
ret['comment'] = 'Data source {0} already up-to-date'.format(name)
else:
requests.post(
'{0}/api/datasources'.format(profile['grafana_url']),
data,
headers=_get_headers(profile),
timeout=profile.get('grafana_timeout', 3),
)
ret['result'] = True
ret['comment'] = 'New data source {0} added'.format(name)
ret['changes'] = data
return ret |
def absent(name, profile='grafana'):
'''
Ensure that a data source is present.
name
Name of the data source to remove.
'''
if isinstance(profile, string_types):
profile = __salt__['config.option'](profile)
ret = {'result': None, 'comment': None, 'changes': {}}
datasource = _get_datasource(profile, name)
if not datasource:
ret['result'] = True
ret['comment'] = 'Data source {0} already absent'.format(name)
return ret
requests.delete(
_get_url(profile, datasource['id']),
headers=_get_headers(profile),
timeout=profile.get('grafana_timeout', 3),
)
ret['result'] = True
ret['comment'] = 'Data source {0} was deleted'.format(name)
return ret |
def compare_changes(obj, **kwargs):
'''
Compare two dicts returning only keys that exist in the first dict and are
different in the second one
'''
changes = {}
for key, value in obj.items():
if key in kwargs:
if value != kwargs[key]:
changes[key] = kwargs[key]
return changes |
def network_create(auth=None, **kwargs):
'''
Create a network
name
Name of the network being created
shared : False
If ``True``, set the network as shared
admin_state_up : True
If ``True``, Set the network administrative state to "up"
external : False
Control whether or not this network is externally accessible
provider
An optional Python dictionary of network provider options
project_id
The project ID on which this network will be created
CLI Example:
.. code-block:: bash
salt '*' neutronng.network_create name=network2 \
shared=True admin_state_up=True external=True
salt '*' neutronng.network_create name=network3 \
provider='{"network_type": "vlan",\
"segmentation_id": "4010",\
"physical_network": "provider"}' \
project_id=1dcac318a83b4610b7a7f7ba01465548
'''
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(keep_name=True, **kwargs)
return cloud.create_network(**kwargs) |
def network_delete(auth=None, **kwargs):
'''
Delete a network
name_or_id
Name or ID of the network being deleted
CLI Example:
.. code-block:: bash
salt '*' neutronng.network_delete name_or_id=network1
salt '*' neutronng.network_delete name_or_id=1dcac318a83b4610b7a7f7ba01465548
'''
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return cloud.delete_network(**kwargs) |
def list_networks(auth=None, **kwargs):
'''
List networks
filters
A Python dictionary of filter conditions to push down
CLI Example:
.. code-block:: bash
salt '*' neutronng.list_networks
salt '*' neutronng.list_networks \
filters='{"tenant_id": "1dcac318a83b4610b7a7f7ba01465548"}'
'''
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return cloud.list_networks(**kwargs) |
def network_get(auth=None, **kwargs):
'''
Get a single network
filters
A Python dictionary of filter conditions to push down
CLI Example:
.. code-block:: bash
salt '*' neutronng.network_get name=XLB4
'''
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return cloud.get_network(**kwargs) |
def subnet_create(auth=None, **kwargs):
'''
Create a subnet
network_name_or_id
The unique name or ID of the attached network. If a non-unique name is
supplied, an exception is raised.
cidr
The CIDR
ip_version
The IP version, which is 4 or 6.
enable_dhcp : False
Set to ``True`` if DHCP is enabled and ``False`` if disabled
subnet_name
The name of the subnet
tenant_id
The ID of the tenant who owns the network. Only administrative users
can specify a tenant ID other than their own.
allocation_pools
A list of dictionaries of the start and end addresses for the
allocation pools.
gateway_ip
The gateway IP address. When you specify both ``allocation_pools`` and
``gateway_ip``, you must ensure that the gateway IP does not overlap
with the specified allocation pools.
disable_gateway_ip : False
Set to ``True`` if gateway IP address is disabled and ``False`` if
enabled. It is not allowed with ``gateway_ip``.
dns_nameservers
A list of DNS name servers for the subnet
host_routes
A list of host route dictionaries for the subnet
ipv6_ra_mode
IPv6 Router Advertisement mode. Valid values are ``dhcpv6-stateful``,
``dhcpv6-stateless``, or ``slaac``.
ipv6_address_mode
IPv6 address mode. Valid values are ``dhcpv6-stateful``,
``dhcpv6-stateless``, or ``slaac``.
use_default_subnetpool
If ``True``, use the default subnetpool for ``ip_version`` to obtain a
CIDR. It is required to pass ``None`` to the ``cidr`` argument when
enabling this option.
CLI Example:
.. code-block:: bash
salt '*' neutronng.subnet_create network_name_or_id=network1
subnet_name=subnet1
salt '*' neutronng.subnet_create subnet_name=subnet2\
network_name_or_id=network2 enable_dhcp=True \
allocation_pools='[{"start": "192.168.199.2",\
"end": "192.168.199.254"}]'\
gateway_ip='192.168.199.1' cidr=192.168.199.0/24
salt '*' neutronng.subnet_create network_name_or_id=network1 \
subnet_name=subnet1 dns_nameservers='["8.8.8.8", "8.8.8.7"]'
'''
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return cloud.create_subnet(**kwargs) |
def subnet_update(auth=None, **kwargs):
'''
Update a subnet
name_or_id
Name or ID of the subnet to update
subnet_name
The new name of the subnet
enable_dhcp
Set to ``True`` if DHCP is enabled and ``False`` if disabled
gateway_ip
The gateway IP address. When you specify both allocation_pools and
gateway_ip, you must ensure that the gateway IP does not overlap with
the specified allocation pools.
disable_gateway_ip : False
Set to ``True`` if gateway IP address is disabled and False if enabled.
It is not allowed with ``gateway_ip``.
allocation_pools
A list of dictionaries of the start and end addresses for the
allocation pools.
dns_nameservers
A list of DNS name servers for the subnet
host_routes
A list of host route dictionaries for the subnet
.. code-block:: bash
salt '*' neutronng.subnet_update name=subnet1 subnet_name=subnet2
salt '*' neutronng.subnet_update name=subnet1 dns_nameservers='["8.8.8.8", "8.8.8.7"]'
'''
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return cloud.update_subnet(**kwargs) |
def subnet_delete(auth=None, **kwargs):
'''
Delete a subnet
name
Name or ID of the subnet to update
CLI Example:
.. code-block:: bash
salt '*' neutronng.subnet_delete name=subnet1
salt '*' neutronng.subnet_delete \
name=1dcac318a83b4610b7a7f7ba01465548
'''
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return cloud.delete_subnet(**kwargs) |
def list_subnets(auth=None, **kwargs):
'''
List subnets
filters
A Python dictionary of filter conditions to push down
CLI Example:
.. code-block:: bash
salt '*' neutronng.list_subnets
salt '*' neutronng.list_subnets \
filters='{"tenant_id": "1dcac318a83b4610b7a7f7ba01465548"}'
'''
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return cloud.list_subnets(**kwargs) |
def subnet_get(auth=None, **kwargs):
'''
Get a single subnet
filters
A Python dictionary of filter conditions to push down
CLI Example:
.. code-block:: bash
salt '*' neutronng.subnet_get name=subnet1
'''
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return cloud.get_subnet(**kwargs) |
def security_group_create(auth=None, **kwargs):
'''
Create a security group. Use security_group_get to create default.
project_id
The project ID on which this security group will be created
CLI Example:
.. code-block:: bash
salt '*' neutronng.security_group_create name=secgroup1 \
description="Very secure security group"
salt '*' neutronng.security_group_create name=secgroup1 \
description="Very secure security group" \
project_id=1dcac318a83b4610b7a7f7ba01465548
'''
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(keep_name=True, **kwargs)
return cloud.create_security_group(**kwargs) |
def security_group_update(secgroup=None, auth=None, **kwargs):
'''
Update a security group
secgroup
Name, ID or Raw Object of the security group to update
name
New name for the security group
description
New description for the security group
CLI Example:
.. code-block:: bash
salt '*' neutronng.security_group_update secgroup=secgroup1 \
description="Very secure security group"
salt '*' neutronng.security_group_update secgroup=secgroup1 \
description="Very secure security group" \
project_id=1dcac318a83b4610b7a7f7ba01465548
'''
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(keep_name=True, **kwargs)
return cloud.update_security_group(secgroup, **kwargs) |
def security_group_delete(auth=None, **kwargs):
'''
Delete a security group
name_or_id
The name or unique ID of the security group
CLI Example:
.. code-block:: bash
salt '*' neutronng.security_group_delete name_or_id=secgroup1
'''
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return cloud.delete_security_group(**kwargs) |
def security_group_get(auth=None, **kwargs):
'''
Get a single security group. This will create a default security group
if one does not exist yet for a particular project id.
filters
A Python dictionary of filter conditions to push down
CLI Example:
.. code-block:: bash
salt '*' neutronng.security_group_get \
name=1dcac318a83b4610b7a7f7ba01465548
salt '*' neutronng.security_group_get \
name=default\
filters='{"tenant_id":"2e778bb64ca64a199eb526b5958d8710"}'
'''
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return cloud.get_security_group(**kwargs) |
def security_group_rule_create(auth=None, **kwargs):
'''
Create a rule in a security group
secgroup_name_or_id
The security group name or ID to associate with this security group
rule. If a non-unique group name is given, an exception is raised.
port_range_min
The minimum port number in the range that is matched by the security
group rule. If the protocol is TCP or UDP, this value must be less than
or equal to the port_range_max attribute value. If nova is used by the
cloud provider for security groups, then a value of None will be
transformed to -1.
port_range_max
The maximum port number in the range that is matched by the security
group rule. The port_range_min attribute constrains the port_range_max
attribute. If nova is used by the cloud provider for security groups,
then a value of None will be transformed to -1.
protocol
The protocol that is matched by the security group rule. Valid values
are ``None``, ``tcp``, ``udp``, and ``icmp``.
remote_ip_prefix
The remote IP prefix to be associated with this security group rule.
This attribute matches the specified IP prefix as the source IP address
of the IP packet.
remote_group_id
The remote group ID to be associated with this security group rule
direction
Either ``ingress`` or ``egress``; the direction in which the security
group rule is applied. For a compute instance, an ingress security
group rule is applied to incoming (ingress) traffic for that instance.
An egress rule is applied to traffic leaving the instance
ethertype
Must be IPv4 or IPv6, and addresses represented in CIDR must match the
ingress or egress rules
project_id
Specify the project ID this security group will be created on
(admin-only)
CLI Example:
.. code-block:: bash
salt '*' neutronng.security_group_rule_create\
secgroup_name_or_id=secgroup1
salt '*' neutronng.security_group_rule_create\
secgroup_name_or_id=secgroup2 port_range_min=8080\
port_range_max=8080 direction='egress'
salt '*' neutronng.security_group_rule_create\
secgroup_name_or_id=c0e1d1ce-7296-405e-919d-1c08217be529\
protocol=icmp project_id=1dcac318a83b4610b7a7f7ba01465548
'''
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return cloud.create_security_group_rule(**kwargs) |
def security_group_rule_delete(auth=None, **kwargs):
'''
Delete a security group
name_or_id
The unique ID of the security group rule
CLI Example:
.. code-block:: bash
salt '*' neutronng.security_group_rule_delete name_or_id=1dcac318a83b4610b7a7f7ba01465548
'''
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return cloud.delete_security_group_rule(**kwargs) |
def avail_locations(call=None):
'''
Return a dict of all available VM locations on the cloud provider with
relevant data
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
params = {'Action': 'DescribeRegions'}
items = query(params=params)
ret = {}
for region in items['Regions']['Region']:
ret[region['RegionId']] = {}
for item in region:
ret[region['RegionId']][item] = six.text_type(region[item])
return ret |
def avail_images(kwargs=None, call=None):
'''
Return a list of the images that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not isinstance(kwargs, dict):
kwargs = {}
provider = get_configured_provider()
location = provider.get('location', DEFAULT_LOCATION)
if 'location' in kwargs:
location = kwargs['location']
params = {
'Action': 'DescribeImages',
'RegionId': location,
'PageSize': '100',
}
items = query(params=params)
ret = {}
for image in items['Images']['Image']:
ret[image['ImageId']] = {}
for item in image:
ret[image['ImageId']][item] = six.text_type(image[item])
return ret |
def avail_sizes(call=None):
'''
Return a list of the image sizes that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
params = {'Action': 'DescribeInstanceTypes'}
items = query(params=params)
ret = {}
for image in items['InstanceTypes']['InstanceType']:
ret[image['InstanceTypeId']] = {}
for item in image:
ret[image['InstanceTypeId']][item] = six.text_type(image[item])
return ret |
def list_availability_zones(call=None):
'''
List all availability zones in the current region
'''
ret = {}
params = {'Action': 'DescribeZones',
'RegionId': get_location()}
items = query(params)
for zone in items['Zones']['Zone']:
ret[zone['ZoneId']] = {}
for item in zone:
ret[zone['ZoneId']][item] = six.text_type(zone[item])
return ret |
def list_nodes_min(call=None):
'''
Return a list of the VMs that are on the provider. Only a list of VM names,
and their state, is returned. This is the minimum amount of information
needed to check for existing VMs.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_min function must be called with -f or --function.'
)
ret = {}
location = get_location()
params = {
'Action': 'DescribeInstanceStatus',
'RegionId': location,
}
nodes = query(params)
log.debug(
'Total %s instance found in Region %s',
nodes['TotalCount'], location
)
if 'Code' in nodes or nodes['TotalCount'] == 0:
return ret
for node in nodes['InstanceStatuses']['InstanceStatus']:
ret[node['InstanceId']] = {}
for item in node:
ret[node['InstanceId']][item] = node[item]
return ret |
def list_nodes(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
nodes = list_nodes_full()
ret = {}
for instanceId in nodes:
node = nodes[instanceId]
ret[node['name']] = {
'id': node['id'],
'name': node['name'],
'public_ips': node['public_ips'],
'private_ips': node['private_ips'],
'size': node['size'],
'state': six.text_type(node['state']),
}
return ret |
def list_nodes_full(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f '
'or --function.'
)
ret = {}
location = get_location()
params = {
'Action': 'DescribeInstanceStatus',
'RegionId': location,
'PageSize': '50'
}
result = query(params=params)
log.debug(
'Total %s instance found in Region %s',
result['TotalCount'], location
)
if 'Code' in result or result['TotalCount'] == 0:
return ret
# aliyun max 100 top instance in api
result_instancestatus = result['InstanceStatuses']['InstanceStatus']
if result['TotalCount'] > 50:
params['PageNumber'] = '2'
result = query(params=params)
result_instancestatus.update(result['InstanceStatuses']['InstanceStatus'])
for node in result_instancestatus:
instanceId = node.get('InstanceId', '')
params = {
'Action': 'DescribeInstanceAttribute',
'InstanceId': instanceId
}
items = query(params=params)
if 'Code' in items:
log.warning('Query instance:%s attribute failed', instanceId)
continue
name = items['InstanceName']
ret[name] = {
'id': items['InstanceId'],
'name': name,
'image': items['ImageId'],
'size': 'TODO',
'state': items['Status']
}
for item in items:
value = items[item]
if value is not None:
value = six.text_type(value)
if item == "PublicIpAddress":
ret[name]['public_ips'] = items[item]['IpAddress']
if item == "InnerIpAddress" and 'private_ips' not in ret[name]:
ret[name]['private_ips'] = items[item]['IpAddress']
if item == 'VpcAttributes':
vpc_ips = items[item]['PrivateIpAddress']['IpAddress']
if vpc_ips:
ret[name]['private_ips'] = vpc_ips
ret[name][item] = value
provider = __active_provider_name__ or 'aliyun'
if ':' in provider:
comps = provider.split(':')
provider = comps[0]
__opts__['update_cachedir'] = True
__utils__['cloud.cache_node_list'](ret, provider, __opts__)
return ret |
def list_securitygroup(call=None):
'''
Return a list of security group
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
params = {
'Action': 'DescribeSecurityGroups',
'RegionId': get_location(),
'PageSize': '50',
}
result = query(params)
if 'Code' in result:
return {}
ret = {}
for sg in result['SecurityGroups']['SecurityGroup']:
ret[sg['SecurityGroupId']] = {}
for item in sg:
ret[sg['SecurityGroupId']][item] = sg[item]
return ret |
def get_image(vm_):
'''
Return the image object to use
'''
images = avail_images()
vm_image = six.text_type(config.get_cloud_config_value(
'image', vm_, __opts__, search_global=False
))
if not vm_image:
raise SaltCloudNotFound('No image specified for this VM.')
if vm_image and six.text_type(vm_image) in images:
return images[vm_image]['ImageId']
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
) |
def get_securitygroup(vm_):
'''
Return the security group
'''
sgs = list_securitygroup()
securitygroup = config.get_cloud_config_value(
'securitygroup', vm_, __opts__, search_global=False
)
if not securitygroup:
raise SaltCloudNotFound('No securitygroup ID specified for this VM.')
if securitygroup and six.text_type(securitygroup) in sgs:
return sgs[securitygroup]['SecurityGroupId']
raise SaltCloudNotFound(
'The specified security group, \'{0}\', could not be found.'.format(
securitygroup)
) |
def get_size(vm_):
'''
Return the VM's size. Used by create_node().
'''
sizes = avail_sizes()
vm_size = six.text_type(config.get_cloud_config_value(
'size', vm_, __opts__, search_global=False
))
if not vm_size:
raise SaltCloudNotFound('No size specified for this VM.')
if vm_size and six.text_type(vm_size) in sizes:
return sizes[vm_size]['InstanceTypeId']
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
) |
def __get_location(vm_):
'''
Return the VM's location
'''
locations = avail_locations()
vm_location = six.text_type(config.get_cloud_config_value(
'location', vm_, __opts__, search_global=False
))
if not vm_location:
raise SaltCloudNotFound('No location specified for this VM.')
if vm_location and six.text_type(vm_location) in locations:
return locations[vm_location]['RegionId']
raise SaltCloudNotFound(
'The specified location, \'{0}\', could not be found.'.format(
vm_location
)
) |
End of preview. Expand
in Dataset Viewer.
README.md exists but content is empty.
Use the Edit dataset card button to edit it.
- Downloads last month
- 35