repository_name
stringclasses 316
values | func_path_in_repository
stringlengths 6
223
| func_name
stringlengths 1
134
| language
stringclasses 1
value | func_code_string
stringlengths 57
65.5k
| func_documentation_string
stringlengths 1
46.3k
| split_name
stringclasses 1
value | func_code_url
stringlengths 91
315
| called_functions
sequencelengths 1
156
⌀ | enclosing_scope
stringlengths 2
1.48M
|
---|---|---|---|---|---|---|---|---|---|
saltstack/salt | salt/transport/zeromq.py | ZeroMQReqServerChannel.zmq_device | python | 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 | Multiprocessing target for the zmq queue device | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/zeromq.py#L582-L622 | [
"def appendproctitle(name):\n '''\n Append \"name\" to the current process title\n '''\n if HAS_SETPROCTITLE:\n setproctitle.setproctitle(setproctitle.getproctitle() + ' ' + name)\n",
"def _start_zmq_monitor(self):\n '''\n Starts ZMQ monitor for debugging purposes.\n :return:\n '''\n # Socket monitor shall be used the only for debug\n # purposes so using threading doesn't look too bad here\n\n if HAS_ZMQ_MONITOR and self.opts['zmq_monitor']:\n log.debug('Starting ZMQ monitor')\n import threading\n self._w_monitor = ZeroMQSocketMonitor(self._socket)\n threading.Thread(target=self._w_monitor.start_poll).start()\n log.debug('ZMQ monitor has been started started')\n",
"def __setup_signals(self):\n signal.signal(signal.SIGINT, self._handle_signals)\n signal.signal(signal.SIGTERM, self._handle_signals)\n"
] | class ZeroMQReqServerChannel(salt.transport.mixins.auth.AESReqServerMixin,
salt.transport.server.ReqServerChannel):
def __init__(self, opts):
salt.transport.server.ReqServerChannel.__init__(self, opts)
self._closing = False
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()
# pylint: enable=E0203
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)
@tornado.gen.coroutine
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 __setup_signals(self):
signal.signal(signal.SIGINT, self._handle_signals)
signal.signal(signal.SIGTERM, self._handle_signals)
def _handle_signals(self, signum, sigframe):
msg = '{0} received a '.format(self.__class__.__name__)
if signum == signal.SIGINT:
msg += 'SIGINT'
elif signum == signal.SIGTERM:
msg += 'SIGTERM'
msg += '. Exiting'
log.debug(msg)
self.close()
sys.exit(salt.defaults.exitcodes.EX_OK)
|
saltstack/salt | salt/transport/zeromq.py | ZeroMQReqServerChannel.close | python | 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() | Cleanly shutdown the router socket | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/zeromq.py#L624-L648 | null | class ZeroMQReqServerChannel(salt.transport.mixins.auth.AESReqServerMixin,
salt.transport.server.ReqServerChannel):
def __init__(self, opts):
salt.transport.server.ReqServerChannel.__init__(self, opts)
self._closing = False
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
# pylint: enable=E0203
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)
@tornado.gen.coroutine
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 __setup_signals(self):
signal.signal(signal.SIGINT, self._handle_signals)
signal.signal(signal.SIGTERM, self._handle_signals)
def _handle_signals(self, signum, sigframe):
msg = '{0} received a '.format(self.__class__.__name__)
if signum == signal.SIGINT:
msg += 'SIGINT'
elif signum == signal.SIGTERM:
msg += 'SIGTERM'
msg += '. Exiting'
log.debug(msg)
self.close()
sys.exit(salt.defaults.exitcodes.EX_OK)
|
saltstack/salt | salt/transport/zeromq.py | ZeroMQReqServerChannel.pre_fork | python | 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) | Pre-fork we need to create the zmq router device
:param func process_manager: An instance of salt.utils.process.ProcessManager | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/zeromq.py#L651-L658 | [
"def pre_fork(self, _):\n '''\n Pre-fork we need to create the zmq router device\n '''\n if 'aes' not in salt.master.SMaster.secrets:\n # TODO: This is still needed only for the unit tests\n # 'tcp_test.py' and 'zeromq_test.py'. Fix that. In normal\n # cases, 'aes' is already set in the secrets.\n salt.master.SMaster.secrets['aes'] = {\n 'secret': multiprocessing.Array(\n ctypes.c_char,\n salt.utils.stringutils.to_bytes(salt.crypt.Crypticle.generate_key_string())\n ),\n 'reload': salt.crypt.Crypticle.generate_key_string\n }\n",
"def add_process(self, tgt, args=None, kwargs=None, name=None):\n '''\n Create a processes and args + kwargs\n This will deterimine if it is a Process class, otherwise it assumes\n it is a function\n '''\n if args is None:\n args = []\n\n if kwargs is None:\n kwargs = {}\n\n if salt.utils.platform.is_windows():\n # Need to ensure that 'log_queue' and 'log_queue_level' is\n # correctly transferred to processes that inherit from\n # 'MultiprocessingProcess'.\n if type(MultiprocessingProcess) is type(tgt) and (\n issubclass(tgt, MultiprocessingProcess)):\n need_log_queue = True\n else:\n need_log_queue = False\n\n if need_log_queue:\n if 'log_queue' not in kwargs:\n if hasattr(self, 'log_queue'):\n kwargs['log_queue'] = self.log_queue\n else:\n kwargs['log_queue'] = (\n salt.log.setup.get_multiprocessing_logging_queue()\n )\n if 'log_queue_level' not in kwargs:\n if hasattr(self, 'log_queue_level'):\n kwargs['log_queue_level'] = self.log_queue_level\n else:\n kwargs['log_queue_level'] = (\n salt.log.setup.get_multiprocessing_logging_level()\n )\n\n # create a nicer name for the debug log\n if name is None:\n if isinstance(tgt, types.FunctionType):\n name = '{0}.{1}'.format(\n tgt.__module__,\n tgt.__name__,\n )\n else:\n name = '{0}{1}.{2}'.format(\n tgt.__module__,\n '.{0}'.format(tgt.__class__) if six.text_type(tgt.__class__) != \"<type 'type'>\" else '',\n tgt.__name__,\n )\n\n if type(multiprocessing.Process) is type(tgt) and issubclass(tgt, multiprocessing.Process):\n process = tgt(*args, **kwargs)\n else:\n process = multiprocessing.Process(target=tgt, args=args, kwargs=kwargs, name=name)\n\n if isinstance(process, SignalHandlingMultiprocessingProcess):\n with default_signals(signal.SIGINT, signal.SIGTERM):\n process.start()\n else:\n process.start()\n log.debug(\"Started '%s' with pid %s\", name, process.pid)\n self._process_map[process.pid] = {'tgt': tgt,\n 'args': args,\n 'kwargs': kwargs,\n 'Process': process}\n return process\n"
] | class ZeroMQReqServerChannel(salt.transport.mixins.auth.AESReqServerMixin,
salt.transport.server.ReqServerChannel):
def __init__(self, opts):
salt.transport.server.ReqServerChannel.__init__(self, opts)
self._closing = False
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()
# pylint: enable=E0203
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)
@tornado.gen.coroutine
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 __setup_signals(self):
signal.signal(signal.SIGINT, self._handle_signals)
signal.signal(signal.SIGTERM, self._handle_signals)
def _handle_signals(self, signum, sigframe):
msg = '{0} received a '.format(self.__class__.__name__)
if signum == signal.SIGINT:
msg += 'SIGINT'
elif signum == signal.SIGTERM:
msg += 'SIGTERM'
msg += '. Exiting'
log.debug(msg)
self.close()
sys.exit(salt.defaults.exitcodes.EX_OK)
|
saltstack/salt | salt/transport/zeromq.py | ZeroMQReqServerChannel._start_zmq_monitor | python | 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') | Starts ZMQ monitor for debugging purposes.
:return: | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/zeromq.py#L660-L673 | null | class ZeroMQReqServerChannel(salt.transport.mixins.auth.AESReqServerMixin,
salt.transport.server.ReqServerChannel):
def __init__(self, opts):
salt.transport.server.ReqServerChannel.__init__(self, opts)
self._closing = False
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()
# pylint: enable=E0203
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 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)
@tornado.gen.coroutine
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 __setup_signals(self):
signal.signal(signal.SIGINT, self._handle_signals)
signal.signal(signal.SIGTERM, self._handle_signals)
def _handle_signals(self, signum, sigframe):
msg = '{0} received a '.format(self.__class__.__name__)
if signum == signal.SIGINT:
msg += 'SIGINT'
elif signum == signal.SIGTERM:
msg += 'SIGTERM'
msg += '. Exiting'
log.debug(msg)
self.close()
sys.exit(salt.defaults.exitcodes.EX_OK)
|
saltstack/salt | salt/transport/zeromq.py | ZeroMQReqServerChannel.post_fork | python | 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) | 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 | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/zeromq.py#L675-L705 | [
"def _start_zmq_monitor(self):\n '''\n Starts ZMQ monitor for debugging purposes.\n :return:\n '''\n # Socket monitor shall be used the only for debug\n # purposes so using threading doesn't look too bad here\n\n if HAS_ZMQ_MONITOR and self.opts['zmq_monitor']:\n log.debug('Starting ZMQ monitor')\n import threading\n self._w_monitor = ZeroMQSocketMonitor(self._socket)\n threading.Thread(target=self._w_monitor.start_poll).start()\n log.debug('ZMQ monitor has been started started')\n",
"def post_fork(self, _, __):\n self.serial = salt.payload.Serial(self.opts)\n self.crypticle = salt.crypt.Crypticle(self.opts, salt.master.SMaster.secrets['aes']['secret'].value)\n\n # other things needed for _auth\n # Create the event manager\n self.event = salt.utils.event.get_master_event(self.opts, self.opts['sock_dir'], listen=False)\n self.auto_key = salt.daemons.masterapi.AutoKey(self.opts)\n\n # only create a con_cache-client if the con_cache is active\n if self.opts['con_cache']:\n self.cache_cli = CacheCli(self.opts)\n else:\n self.cache_cli = False\n # Make an minion checker object\n self.ckminions = salt.utils.minions.CkMinions(self.opts)\n\n self.master_key = salt.crypt.MasterKeys(self.opts)\n"
] | class ZeroMQReqServerChannel(salt.transport.mixins.auth.AESReqServerMixin,
salt.transport.server.ReqServerChannel):
def __init__(self, opts):
salt.transport.server.ReqServerChannel.__init__(self, opts)
self._closing = False
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()
# pylint: enable=E0203
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')
@tornado.gen.coroutine
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 __setup_signals(self):
signal.signal(signal.SIGINT, self._handle_signals)
signal.signal(signal.SIGTERM, self._handle_signals)
def _handle_signals(self, signum, sigframe):
msg = '{0} received a '.format(self.__class__.__name__)
if signum == signal.SIGINT:
msg += 'SIGINT'
elif signum == signal.SIGTERM:
msg += 'SIGTERM'
msg += '. Exiting'
log.debug(msg)
self.close()
sys.exit(salt.defaults.exitcodes.EX_OK)
|
saltstack/salt | salt/transport/zeromq.py | ZeroMQReqServerChannel.handle_message | python | 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() | 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 | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/zeromq.py#L708-L782 | [
"def _decode_payload(self, payload):\n # we need to decrypt it\n if payload['enc'] == 'aes':\n try:\n payload['load'] = self.crypticle.loads(payload['load'])\n except salt.crypt.AuthenticationError:\n if not self._update_aes():\n raise\n payload['load'] = self.crypticle.loads(payload['load'])\n return payload\n"
] | class ZeroMQReqServerChannel(salt.transport.mixins.auth.AESReqServerMixin,
salt.transport.server.ReqServerChannel):
def __init__(self, opts):
salt.transport.server.ReqServerChannel.__init__(self, opts)
self._closing = False
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()
# pylint: enable=E0203
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)
@tornado.gen.coroutine
def __setup_signals(self):
signal.signal(signal.SIGINT, self._handle_signals)
signal.signal(signal.SIGTERM, self._handle_signals)
def _handle_signals(self, signum, sigframe):
msg = '{0} received a '.format(self.__class__.__name__)
if signum == signal.SIGINT:
msg += 'SIGINT'
elif signum == signal.SIGTERM:
msg += 'SIGTERM'
msg += '. Exiting'
log.debug(msg)
self.close()
sys.exit(salt.defaults.exitcodes.EX_OK)
|
saltstack/salt | salt/transport/zeromq.py | ZeroMQPubServerChannel._publish_daemon | python | 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() | Bind to the interface specified in the configuration file | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/zeromq.py#L847-L955 | null | class ZeroMQPubServerChannel(salt.transport.server.PubServerChannel):
'''
Encapsulate synchronous operations for a publisher channel
'''
_sock_data = threading.local()
def __init__(self, opts):
self.opts = opts
self.serial = salt.payload.Serial(self.opts) # TODO: in init?
self.ckminions = salt.utils.minions.CkMinions(self.opts)
def connect(self):
return tornado.gen.sleep(5)
def pre_fork(self, process_manager, kwargs=None):
'''
Do anything necessary pre-fork. Since this is on the master side this will
primarily be used to create IPC channels and create our daemon process to
do the actual publishing
:param func process_manager: A ProcessManager, from salt.utils.process.ProcessManager
'''
process_manager.add_process(self._publish_daemon, kwargs=kwargs)
@property
def pub_sock(self):
'''
This thread's zmq publisher socket. This socket is stored on the class
so that multiple instantiations in the same thread will re-use a single
zmq socket.
'''
try:
return self._sock_data.sock
except AttributeError:
pass
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.')
|
saltstack/salt | salt/transport/zeromq.py | ZeroMQPubServerChannel.pub_connect | python | 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 | 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. | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/zeromq.py#L979-L1000 | [
"def pub_close(self):\n '''\n Disconnect an existing publisher socket and remove it from the local\n thread's cache.\n '''\n if hasattr(self._sock_data, 'sock'):\n self._sock_data.sock.close()\n delattr(self._sock_data, 'sock')\n"
] | class ZeroMQPubServerChannel(salt.transport.server.PubServerChannel):
'''
Encapsulate synchronous operations for a publisher channel
'''
_sock_data = threading.local()
def __init__(self, opts):
self.opts = opts
self.serial = salt.payload.Serial(self.opts) # TODO: in init?
self.ckminions = salt.utils.minions.CkMinions(self.opts)
def connect(self):
return tornado.gen.sleep(5)
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 pre_fork(self, process_manager, kwargs=None):
'''
Do anything necessary pre-fork. Since this is on the master side this will
primarily be used to create IPC channels and create our daemon process to
do the actual publishing
:param func process_manager: A ProcessManager, from salt.utils.process.ProcessManager
'''
process_manager.add_process(self._publish_daemon, kwargs=kwargs)
@property
def pub_sock(self):
'''
This thread's zmq publisher socket. This socket is stored on the class
so that multiple instantiations in the same thread will re-use a single
zmq socket.
'''
try:
return self._sock_data.sock
except AttributeError:
pass
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.')
|
saltstack/salt | salt/transport/zeromq.py | ZeroMQPubServerChannel.pub_close | python | 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') | Disconnect an existing publisher socket and remove it from the local
thread's cache. | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/zeromq.py#L1002-L1009 | null | class ZeroMQPubServerChannel(salt.transport.server.PubServerChannel):
'''
Encapsulate synchronous operations for a publisher channel
'''
_sock_data = threading.local()
def __init__(self, opts):
self.opts = opts
self.serial = salt.payload.Serial(self.opts) # TODO: in init?
self.ckminions = salt.utils.minions.CkMinions(self.opts)
def connect(self):
return tornado.gen.sleep(5)
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 pre_fork(self, process_manager, kwargs=None):
'''
Do anything necessary pre-fork. Since this is on the master side this will
primarily be used to create IPC channels and create our daemon process to
do the actual publishing
:param func process_manager: A ProcessManager, from salt.utils.process.ProcessManager
'''
process_manager.add_process(self._publish_daemon, kwargs=kwargs)
@property
def pub_sock(self):
'''
This thread's zmq publisher socket. This socket is stored on the class
so that multiple instantiations in the same thread will re-use a single
zmq socket.
'''
try:
return self._sock_data.sock
except AttributeError:
pass
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 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.')
|
saltstack/salt | salt/transport/zeromq.py | ZeroMQPubServerChannel.publish | python | 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.') | 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 | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/zeromq.py#L1011-L1050 | [
"def sign_message(privkey_path, message, passphrase=None):\n '''\n Use Crypto.Signature.PKCS1_v1_5 to sign a message. Returns the signature.\n '''\n key = get_rsa_key(privkey_path, passphrase)\n log.debug('salt.crypt.sign_message: Signing message.')\n if HAS_M2:\n md = EVP.MessageDigest('sha1')\n md.update(salt.utils.stringutils.to_bytes(message))\n digest = md.final()\n return key.sign(digest)\n else:\n signer = PKCS1_v1_5.new(key)\n return signer.sign(SHA.new(salt.utils.stringutils.to_bytes(message)))\n",
"def pub_connect(self):\n '''\n Create and connect this thread's zmq socket. If a publisher socket\n already exists \"pub_close\" is called before creating and connecting a\n new socket.\n '''\n if self.pub_sock:\n self.pub_close()\n ctx = zmq.Context.instance()\n self._sock_data.sock = ctx.socket(zmq.PUSH)\n self.pub_sock.setsockopt(zmq.LINGER, -1)\n if self.opts.get('ipc_mode', '') == 'tcp':\n pull_uri = 'tcp://127.0.0.1:{0}'.format(\n self.opts.get('tcp_master_publish_pull', 4514)\n )\n else:\n pull_uri = 'ipc://{0}'.format(\n os.path.join(self.opts['sock_dir'], 'publish_pull.ipc')\n )\n log.debug(\"Connecting to pub server: %s\", pull_uri)\n self.pub_sock.connect(pull_uri)\n return self._sock_data.sock\n",
"def dumps(self, obj):\n '''\n Serialize and encrypt a python object\n '''\n return self.encrypt(self.PICKLE_PAD + self.serial.dumps(obj))\n",
"def check_minions(self,\n expr,\n tgt_type='glob',\n delimiter=DEFAULT_TARGET_DELIM,\n greedy=True):\n '''\n Check the passed regex against the available minions' public keys\n stored for authentication. This should return a set of ids which\n match the regex, this will then be used to parse the returns to\n make sure everyone has checked back in.\n '''\n\n try:\n if expr is None:\n expr = ''\n check_func = getattr(self, '_check_{0}_minions'.format(tgt_type), None)\n if tgt_type in ('grain',\n 'grain_pcre',\n 'pillar',\n 'pillar_pcre',\n 'pillar_exact',\n 'compound',\n 'compound_pillar_exact'):\n _res = check_func(expr, delimiter, greedy)\n else:\n _res = check_func(expr, greedy)\n _res['ssh_minions'] = False\n if self.opts.get('enable_ssh_minions', False) is True and isinstance('tgt', six.string_types):\n roster = salt.roster.Roster(self.opts, self.opts.get('roster', 'flat'))\n ssh_minions = roster.targets(expr, tgt_type)\n if ssh_minions:\n _res['minions'].extend(ssh_minions)\n _res['ssh_minions'] = True\n except Exception:\n log.exception(\n 'Failed matching available minions with %s pattern: %s',\n tgt_type, expr)\n _res = {'minions': [], 'missing': []}\n return _res\n",
"def dumps(self, msg, use_bin_type=False):\n '''\n Run the correct dumps serialization format\n\n :param use_bin_type: Useful for Python 3 support. Tells msgpack to\n differentiate between 'str' and 'bytes' types\n by encoding them differently.\n Since this changes the wire protocol, this\n option should not be used outside of IPC.\n '''\n def ext_type_encoder(obj):\n if isinstance(obj, six.integer_types):\n # msgpack can't handle the very long Python longs for jids\n # Convert any very long longs to strings\n return six.text_type(obj)\n elif isinstance(obj, (datetime.datetime, datetime.date)):\n # msgpack doesn't support datetime.datetime and datetime.date datatypes.\n # So here we have converted these types to custom datatype\n # This is msgpack Extended types numbered 78\n return msgpack.ExtType(78, salt.utils.stringutils.to_bytes(\n obj.strftime('%Y%m%dT%H:%M:%S.%f')))\n # The same for immutable types\n elif isinstance(obj, immutabletypes.ImmutableDict):\n return dict(obj)\n elif isinstance(obj, immutabletypes.ImmutableList):\n return list(obj)\n elif isinstance(obj, (set, immutabletypes.ImmutableSet)):\n # msgpack can't handle set so translate it to tuple\n return tuple(obj)\n elif isinstance(obj, CaseInsensitiveDict):\n return dict(obj)\n # Nothing known exceptions found. Let msgpack raise it's own.\n return obj\n\n try:\n if msgpack.version >= (0, 4, 0):\n # msgpack only supports 'use_bin_type' starting in 0.4.0.\n # Due to this, if we don't need it, don't pass it at all so\n # that under Python 2 we can still work with older versions\n # of msgpack.\n return salt.utils.msgpack.dumps(msg, default=ext_type_encoder,\n use_bin_type=use_bin_type,\n _msgpack_module=msgpack)\n else:\n return salt.utils.msgpack.dumps(msg, default=ext_type_encoder,\n _msgpack_module=msgpack)\n except (OverflowError, msgpack.exceptions.PackValueError):\n # msgpack<=0.4.6 don't call ext encoder on very long integers raising the error instead.\n # Convert any very long longs to strings and call dumps again.\n def verylong_encoder(obj, context):\n # Make sure we catch recursion here.\n objid = id(obj)\n if objid in context:\n return '<Recursion on {} with id={}>'.format(type(obj).__name__, id(obj))\n context.add(objid)\n\n if isinstance(obj, dict):\n for key, value in six.iteritems(obj.copy()):\n obj[key] = verylong_encoder(value, context)\n return dict(obj)\n elif isinstance(obj, (list, tuple)):\n obj = list(obj)\n for idx, entry in enumerate(obj):\n obj[idx] = verylong_encoder(entry, context)\n return obj\n # A value of an Integer object is limited from -(2^63) upto (2^64)-1 by MessagePack\n # spec. Here we care only of JIDs that are positive integers.\n if isinstance(obj, six.integer_types) and obj >= pow(2, 64):\n return six.text_type(obj)\n else:\n return obj\n\n msg = verylong_encoder(msg, set())\n if msgpack.version >= (0, 4, 0):\n return salt.utils.msgpack.dumps(msg, default=ext_type_encoder,\n use_bin_type=use_bin_type,\n _msgpack_module=msgpack)\n else:\n return salt.utils.msgpack.dumps(msg, default=ext_type_encoder,\n _msgpack_module=msgpack)\n"
] | class ZeroMQPubServerChannel(salt.transport.server.PubServerChannel):
'''
Encapsulate synchronous operations for a publisher channel
'''
_sock_data = threading.local()
def __init__(self, opts):
self.opts = opts
self.serial = salt.payload.Serial(self.opts) # TODO: in init?
self.ckminions = salt.utils.minions.CkMinions(self.opts)
def connect(self):
return tornado.gen.sleep(5)
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 pre_fork(self, process_manager, kwargs=None):
'''
Do anything necessary pre-fork. Since this is on the master side this will
primarily be used to create IPC channels and create our daemon process to
do the actual publishing
:param func process_manager: A ProcessManager, from salt.utils.process.ProcessManager
'''
process_manager.add_process(self._publish_daemon, kwargs=kwargs)
@property
def pub_sock(self):
'''
This thread's zmq publisher socket. This socket is stored on the class
so that multiple instantiations in the same thread will re-use a single
zmq socket.
'''
try:
return self._sock_data.sock
except AttributeError:
pass
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')
|
saltstack/salt | salt/transport/zeromq.py | AsyncReqMessageClient.timeout_message | python | 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')) | Handle a message timeout by removing it from the sending queue
and informing the caller
:raises: SaltReqTimeoutError | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/zeromq.py#L1230-L1253 | [
"def send(self, message, timeout=None, tries=3, future=None, callback=None, raw=False):\n '''\n Return a future which will be completed when the message has a response\n '''\n if future is None:\n future = tornado.concurrent.Future()\n future.tries = tries\n future.attempts = 0\n future.timeout = timeout\n # if a future wasn't passed in, we need to serialize the message\n message = self.serial.dumps(message)\n if callback is not None:\n def handle_future(future):\n response = future.result()\n self.io_loop.add_callback(callback, response)\n future.add_done_callback(handle_future)\n # Add this future to the mapping\n self.send_future_map[message] = future\n\n if self.opts.get('detect_mode') is True:\n timeout = 1\n\n if timeout is not None:\n send_timeout = self.io_loop.call_later(timeout, self.timeout_message, message)\n self.send_timeout_map[message] = send_timeout\n\n if not self.send_queue:\n self.io_loop.spawn_callback(self._internal_send_recv)\n\n self.send_queue.append(message)\n\n return future\n"
] | class AsyncReqMessageClient(object):
'''
This class wraps the underlying zeromq REQ socket and gives a future-based
interface to sending and recieving messages. This works around the primary
limitation of serialized send/recv on the underlying socket by queueing the
message sends in this class. In the future if we decide to attempt to multiplex
we can manage a pool of REQ/REP sockets-- but for now we'll just do them in serial
'''
def __init__(self, opts, addr, linger=0, io_loop=None):
'''
Create an asynchronous message client
:param dict opts: The salt opts dictionary
:param str addr: The interface IP address to bind to
:param int linger: The number of seconds to linger on a ZMQ socket. See
http://api.zeromq.org/2-1:zmq-setsockopt [ZMQ_LINGER]
:param IOLoop io_loop: A Tornado IOLoop event scheduler [tornado.ioloop.IOLoop]
'''
self.opts = opts
self.addr = addr
self.linger = linger
if io_loop is None:
install_zmq()
ZMQDefaultLoop.current()
else:
self.io_loop = io_loop
self.serial = salt.payload.Serial(self.opts)
self.context = zmq.Context()
# wire up sockets
self._init_socket()
self.send_queue = []
# mapping of message -> future
self.send_future_map = {}
self.send_timeout_map = {} # message -> timeout
self._closing = False
# TODO: timeout all in-flight sessions, or error
def close(self):
if self._closing:
return
self._closing = True
if hasattr(self, 'stream') and self.stream is not None:
if ZMQ_VERSION_INFO < (14, 3, 0):
# stream.close() doesn't work properly on pyzmq < 14.3.0
if self.stream.socket:
self.stream.socket.close()
self.stream.io_loop.remove_handler(self.stream.socket)
# set this to None, more hacks for messed up pyzmq
self.stream.socket = None
self.socket.close()
else:
self.stream.close()
self.socket = None
self.stream = None
if self.context.closed is False:
self.context.term()
def destroy(self):
# Bacwards compat
salt.utils.versions.warn_until(
'Sodium',
'Calling {0}.destroy() is deprecated. Please call {0}.close() instead.'.format(
self.__class__.__name__
),
stacklevel=3
)
self.close()
def __del__(self):
self.close()
def _init_socket(self):
if hasattr(self, 'stream'):
self.stream.close() # pylint: disable=E0203
self.socket.close() # pylint: disable=E0203
del self.stream
del self.socket
self.socket = self.context.socket(zmq.REQ)
# socket options
if hasattr(zmq, 'RECONNECT_IVL_MAX'):
self.socket.setsockopt(
zmq.RECONNECT_IVL_MAX, 5000
)
_set_tcp_keepalive(self.socket, self.opts)
if self.addr.startswith('tcp://['):
# Hint PF type if bracket enclosed IPv6 address
if hasattr(zmq, 'IPV6'):
self.socket.setsockopt(zmq.IPV6, 1)
elif hasattr(zmq, 'IPV4ONLY'):
self.socket.setsockopt(zmq.IPV4ONLY, 0)
self.socket.linger = self.linger
log.debug('Trying to connect to: %s', self.addr)
self.socket.connect(self.addr)
self.stream = zmq.eventloop.zmqstream.ZMQStream(self.socket, io_loop=self.io_loop)
@tornado.gen.coroutine
def _internal_send_recv(self):
while self.send_queue:
message = self.send_queue[0]
future = self.send_future_map.get(message, None)
if future is None:
# Timedout
del self.send_queue[0]
continue
# send
def mark_future(msg):
if not future.done():
data = self.serial.loads(msg[0])
future.set_result(data)
self.stream.on_recv(mark_future)
self.stream.send(message)
try:
ret = yield future
except Exception as err: # pylint: disable=W0702
log.debug('Re-init ZMQ socket: %s', err)
self._init_socket() # re-init the zmq socket (no other way in zmq)
del self.send_queue[0]
continue
del self.send_queue[0]
self.send_future_map.pop(message, None)
self.remove_message_timeout(message)
def remove_message_timeout(self, message):
if message not in self.send_timeout_map:
return
timeout = self.send_timeout_map.pop(message, None)
if timeout is not None:
# Hasn't been already timedout
self.io_loop.remove_timeout(timeout)
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
|
saltstack/salt | salt/transport/zeromq.py | AsyncReqMessageClient.send | python | 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 | Return a future which will be completed when the message has a response | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/zeromq.py#L1255-L1286 | null | class AsyncReqMessageClient(object):
'''
This class wraps the underlying zeromq REQ socket and gives a future-based
interface to sending and recieving messages. This works around the primary
limitation of serialized send/recv on the underlying socket by queueing the
message sends in this class. In the future if we decide to attempt to multiplex
we can manage a pool of REQ/REP sockets-- but for now we'll just do them in serial
'''
def __init__(self, opts, addr, linger=0, io_loop=None):
'''
Create an asynchronous message client
:param dict opts: The salt opts dictionary
:param str addr: The interface IP address to bind to
:param int linger: The number of seconds to linger on a ZMQ socket. See
http://api.zeromq.org/2-1:zmq-setsockopt [ZMQ_LINGER]
:param IOLoop io_loop: A Tornado IOLoop event scheduler [tornado.ioloop.IOLoop]
'''
self.opts = opts
self.addr = addr
self.linger = linger
if io_loop is None:
install_zmq()
ZMQDefaultLoop.current()
else:
self.io_loop = io_loop
self.serial = salt.payload.Serial(self.opts)
self.context = zmq.Context()
# wire up sockets
self._init_socket()
self.send_queue = []
# mapping of message -> future
self.send_future_map = {}
self.send_timeout_map = {} # message -> timeout
self._closing = False
# TODO: timeout all in-flight sessions, or error
def close(self):
if self._closing:
return
self._closing = True
if hasattr(self, 'stream') and self.stream is not None:
if ZMQ_VERSION_INFO < (14, 3, 0):
# stream.close() doesn't work properly on pyzmq < 14.3.0
if self.stream.socket:
self.stream.socket.close()
self.stream.io_loop.remove_handler(self.stream.socket)
# set this to None, more hacks for messed up pyzmq
self.stream.socket = None
self.socket.close()
else:
self.stream.close()
self.socket = None
self.stream = None
if self.context.closed is False:
self.context.term()
def destroy(self):
# Bacwards compat
salt.utils.versions.warn_until(
'Sodium',
'Calling {0}.destroy() is deprecated. Please call {0}.close() instead.'.format(
self.__class__.__name__
),
stacklevel=3
)
self.close()
def __del__(self):
self.close()
def _init_socket(self):
if hasattr(self, 'stream'):
self.stream.close() # pylint: disable=E0203
self.socket.close() # pylint: disable=E0203
del self.stream
del self.socket
self.socket = self.context.socket(zmq.REQ)
# socket options
if hasattr(zmq, 'RECONNECT_IVL_MAX'):
self.socket.setsockopt(
zmq.RECONNECT_IVL_MAX, 5000
)
_set_tcp_keepalive(self.socket, self.opts)
if self.addr.startswith('tcp://['):
# Hint PF type if bracket enclosed IPv6 address
if hasattr(zmq, 'IPV6'):
self.socket.setsockopt(zmq.IPV6, 1)
elif hasattr(zmq, 'IPV4ONLY'):
self.socket.setsockopt(zmq.IPV4ONLY, 0)
self.socket.linger = self.linger
log.debug('Trying to connect to: %s', self.addr)
self.socket.connect(self.addr)
self.stream = zmq.eventloop.zmqstream.ZMQStream(self.socket, io_loop=self.io_loop)
@tornado.gen.coroutine
def _internal_send_recv(self):
while self.send_queue:
message = self.send_queue[0]
future = self.send_future_map.get(message, None)
if future is None:
# Timedout
del self.send_queue[0]
continue
# send
def mark_future(msg):
if not future.done():
data = self.serial.loads(msg[0])
future.set_result(data)
self.stream.on_recv(mark_future)
self.stream.send(message)
try:
ret = yield future
except Exception as err: # pylint: disable=W0702
log.debug('Re-init ZMQ socket: %s', err)
self._init_socket() # re-init the zmq socket (no other way in zmq)
del self.send_queue[0]
continue
del self.send_queue[0]
self.send_future_map.pop(message, None)
self.remove_message_timeout(message)
def remove_message_timeout(self, message):
if message not in self.send_timeout_map:
return
timeout = self.send_timeout_map.pop(message, None)
if timeout is not None:
# Hasn't been already timedout
self.io_loop.remove_timeout(timeout)
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'))
|
saltstack/salt | salt/modules/elasticsearch.py | _get_instance | python | 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 | Return the elasticsearch instance | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L81-L153 | null | # -*- coding: utf-8 -*-
'''
Elasticsearch - A distributed RESTful search and analytics server
Module to provide Elasticsearch compatibility to Salt
(compatible with Elasticsearch version 1.5.2+)
.. versionadded:: 2015.8.0
:depends: `elasticsearch-py <http://elasticsearch-py.readthedocs.org/en/latest/>`_
:configuration: This module accepts connection configuration details either as
parameters or as configuration settings in /etc/salt/minion on the relevant
minions:
.. code-block:: yaml
elasticsearch:
host: '10.10.10.100:9200'
elasticsearch-cluster:
hosts:
- '10.10.10.100:9200'
- '10.10.10.101:9200'
- '10.10.10.102:9200'
elasticsearch-extra:
hosts:
- '10.10.10.100:9200'
use_ssl: True
verify_certs: True
ca_certs: /path/to/custom_ca_bundle.pem
number_of_shards: 1
number_of_replicas: 0
functions_blacklist:
- 'saltutil.find_job'
- 'pillar.items'
- 'grains.items'
proxies:
- http: http://proxy:3128
- https: http://proxy:1080
When specifying proxies the requests backend will be used and the 'proxies'
data structure is passed as-is to that module.
This data can also be passed into pillar. Options passed into opts will
overwrite options passed into pillar.
Some functionality might be limited by elasticsearch-py and Elasticsearch server versions.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
# Import third party libs
try:
import elasticsearch
from elasticsearch import RequestsHttpConnection
logging.getLogger('elasticsearch').setLevel(logging.CRITICAL)
HAS_ELASTICSEARCH = True
except ImportError:
HAS_ELASTICSEARCH = False
def __virtual__():
'''
Only load if elasticsearch libraries exist.
'''
if not HAS_ELASTICSEARCH:
return (False, 'Cannot load module elasticsearch: elasticsearch libraries not found')
return True
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 document_get(index, id, doc_type='_all', hosts=None, profile=None):
'''
Check for the existence of a document and if it exists, return it
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_get testindex AUx-384m0Bug_8U80wQZ
'''
es = _get_instance(hosts, profile)
try:
return es.get(index=index, id=id, doc_type=doc_type)
except elasticsearch.exceptions.NotFoundError:
return None
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 index_close(index, allow_no_indices=True, expand_wildcards='open', ignore_unavailable=True, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Close specified index.
index
Index to be closed
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 ‘open’, 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_close testindex
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.close(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 close 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_restore(repository, snapshot, body=None, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Restore existing snapshot in specified repository by supplied definition.
repository
Repository name
snapshot
Snapshot name
body
Restore definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
CLI example::
salt myminion elasticsearch.snapshot_restore testrepo testsnapshot '{"indices":"index_1,index_2","ignore_unavailable":true,"include_global_state":true}'
'''
es = _get_instance(hosts, profile)
try:
response = es.snapshot.restore(repository=repository, snapshot=snapshot, body=body)
return response.get('accepted', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot restore 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))
|
saltstack/salt | salt/modules/elasticsearch.py | ping | python | 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 | .. 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 | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L156-L176 | [
"def _get_instance(hosts=None, profile=None):\n '''\n Return the elasticsearch instance\n '''\n es = None\n proxies = None\n use_ssl = False\n ca_certs = None\n verify_certs = True\n http_auth = None\n timeout = 10\n\n if profile is None:\n profile = 'elasticsearch'\n\n if isinstance(profile, six.string_types):\n _profile = __salt__['config.option'](profile, None)\n elif isinstance(profile, dict):\n _profile = profile\n if _profile:\n hosts = _profile.get('host', hosts)\n if not hosts:\n hosts = _profile.get('hosts', hosts)\n proxies = _profile.get('proxies', None)\n use_ssl = _profile.get('use_ssl', False)\n ca_certs = _profile.get('ca_certs', None)\n verify_certs = _profile.get('verify_certs', True)\n username = _profile.get('username', None)\n password = _profile.get('password', None)\n timeout = _profile.get('timeout', 10)\n\n if username and password:\n http_auth = (username, password)\n\n if not hosts:\n hosts = ['127.0.0.1:9200']\n if isinstance(hosts, six.string_types):\n hosts = [hosts]\n try:\n if proxies:\n # Custom connection class to use requests module with proxies\n class ProxyConnection(RequestsHttpConnection):\n def __init__(self, *args, **kwargs):\n proxies = kwargs.pop('proxies', {})\n super(ProxyConnection, self).__init__(*args, **kwargs)\n self.session.proxies = proxies\n\n es = elasticsearch.Elasticsearch(\n hosts,\n connection_class=ProxyConnection,\n proxies=proxies,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n else:\n es = elasticsearch.Elasticsearch(\n hosts,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n\n # Try the connection\n es.info()\n except elasticsearch.exceptions.TransportError as err:\n raise CommandExecutionError(\n 'Could not connect to Elasticsearch host/ cluster {0} due to {1}'.format(hosts, err))\n return es\n"
] | # -*- coding: utf-8 -*-
'''
Elasticsearch - A distributed RESTful search and analytics server
Module to provide Elasticsearch compatibility to Salt
(compatible with Elasticsearch version 1.5.2+)
.. versionadded:: 2015.8.0
:depends: `elasticsearch-py <http://elasticsearch-py.readthedocs.org/en/latest/>`_
:configuration: This module accepts connection configuration details either as
parameters or as configuration settings in /etc/salt/minion on the relevant
minions:
.. code-block:: yaml
elasticsearch:
host: '10.10.10.100:9200'
elasticsearch-cluster:
hosts:
- '10.10.10.100:9200'
- '10.10.10.101:9200'
- '10.10.10.102:9200'
elasticsearch-extra:
hosts:
- '10.10.10.100:9200'
use_ssl: True
verify_certs: True
ca_certs: /path/to/custom_ca_bundle.pem
number_of_shards: 1
number_of_replicas: 0
functions_blacklist:
- 'saltutil.find_job'
- 'pillar.items'
- 'grains.items'
proxies:
- http: http://proxy:3128
- https: http://proxy:1080
When specifying proxies the requests backend will be used and the 'proxies'
data structure is passed as-is to that module.
This data can also be passed into pillar. Options passed into opts will
overwrite options passed into pillar.
Some functionality might be limited by elasticsearch-py and Elasticsearch server versions.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
# Import third party libs
try:
import elasticsearch
from elasticsearch import RequestsHttpConnection
logging.getLogger('elasticsearch').setLevel(logging.CRITICAL)
HAS_ELASTICSEARCH = True
except ImportError:
HAS_ELASTICSEARCH = False
def __virtual__():
'''
Only load if elasticsearch libraries exist.
'''
if not HAS_ELASTICSEARCH:
return (False, 'Cannot load module elasticsearch: elasticsearch libraries not found')
return True
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 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 document_get(index, id, doc_type='_all', hosts=None, profile=None):
'''
Check for the existence of a document and if it exists, return it
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_get testindex AUx-384m0Bug_8U80wQZ
'''
es = _get_instance(hosts, profile)
try:
return es.get(index=index, id=id, doc_type=doc_type)
except elasticsearch.exceptions.NotFoundError:
return None
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 index_close(index, allow_no_indices=True, expand_wildcards='open', ignore_unavailable=True, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Close specified index.
index
Index to be closed
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 ‘open’, 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_close testindex
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.close(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 close 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_restore(repository, snapshot, body=None, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Restore existing snapshot in specified repository by supplied definition.
repository
Repository name
snapshot
Snapshot name
body
Restore definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
CLI example::
salt myminion elasticsearch.snapshot_restore testrepo testsnapshot '{"indices":"index_1,index_2","ignore_unavailable":true,"include_global_state":true}'
'''
es = _get_instance(hosts, profile)
try:
response = es.snapshot.restore(repository=repository, snapshot=snapshot, body=body)
return response.get('accepted', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot restore 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))
|
saltstack/salt | salt/modules/elasticsearch.py | info | python | 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)) | .. versionadded:: 2017.7.0
Return Elasticsearch information.
CLI example::
salt myminion elasticsearch.info
salt myminion elasticsearch.info profile=elasticsearch-extra | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L179-L195 | [
"def _get_instance(hosts=None, profile=None):\n '''\n Return the elasticsearch instance\n '''\n es = None\n proxies = None\n use_ssl = False\n ca_certs = None\n verify_certs = True\n http_auth = None\n timeout = 10\n\n if profile is None:\n profile = 'elasticsearch'\n\n if isinstance(profile, six.string_types):\n _profile = __salt__['config.option'](profile, None)\n elif isinstance(profile, dict):\n _profile = profile\n if _profile:\n hosts = _profile.get('host', hosts)\n if not hosts:\n hosts = _profile.get('hosts', hosts)\n proxies = _profile.get('proxies', None)\n use_ssl = _profile.get('use_ssl', False)\n ca_certs = _profile.get('ca_certs', None)\n verify_certs = _profile.get('verify_certs', True)\n username = _profile.get('username', None)\n password = _profile.get('password', None)\n timeout = _profile.get('timeout', 10)\n\n if username and password:\n http_auth = (username, password)\n\n if not hosts:\n hosts = ['127.0.0.1:9200']\n if isinstance(hosts, six.string_types):\n hosts = [hosts]\n try:\n if proxies:\n # Custom connection class to use requests module with proxies\n class ProxyConnection(RequestsHttpConnection):\n def __init__(self, *args, **kwargs):\n proxies = kwargs.pop('proxies', {})\n super(ProxyConnection, self).__init__(*args, **kwargs)\n self.session.proxies = proxies\n\n es = elasticsearch.Elasticsearch(\n hosts,\n connection_class=ProxyConnection,\n proxies=proxies,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n else:\n es = elasticsearch.Elasticsearch(\n hosts,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n\n # Try the connection\n es.info()\n except elasticsearch.exceptions.TransportError as err:\n raise CommandExecutionError(\n 'Could not connect to Elasticsearch host/ cluster {0} due to {1}'.format(hosts, err))\n return es\n"
] | # -*- coding: utf-8 -*-
'''
Elasticsearch - A distributed RESTful search and analytics server
Module to provide Elasticsearch compatibility to Salt
(compatible with Elasticsearch version 1.5.2+)
.. versionadded:: 2015.8.0
:depends: `elasticsearch-py <http://elasticsearch-py.readthedocs.org/en/latest/>`_
:configuration: This module accepts connection configuration details either as
parameters or as configuration settings in /etc/salt/minion on the relevant
minions:
.. code-block:: yaml
elasticsearch:
host: '10.10.10.100:9200'
elasticsearch-cluster:
hosts:
- '10.10.10.100:9200'
- '10.10.10.101:9200'
- '10.10.10.102:9200'
elasticsearch-extra:
hosts:
- '10.10.10.100:9200'
use_ssl: True
verify_certs: True
ca_certs: /path/to/custom_ca_bundle.pem
number_of_shards: 1
number_of_replicas: 0
functions_blacklist:
- 'saltutil.find_job'
- 'pillar.items'
- 'grains.items'
proxies:
- http: http://proxy:3128
- https: http://proxy:1080
When specifying proxies the requests backend will be used and the 'proxies'
data structure is passed as-is to that module.
This data can also be passed into pillar. Options passed into opts will
overwrite options passed into pillar.
Some functionality might be limited by elasticsearch-py and Elasticsearch server versions.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
# Import third party libs
try:
import elasticsearch
from elasticsearch import RequestsHttpConnection
logging.getLogger('elasticsearch').setLevel(logging.CRITICAL)
HAS_ELASTICSEARCH = True
except ImportError:
HAS_ELASTICSEARCH = False
def __virtual__():
'''
Only load if elasticsearch libraries exist.
'''
if not HAS_ELASTICSEARCH:
return (False, 'Cannot load module elasticsearch: elasticsearch libraries not found')
return True
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 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 document_get(index, id, doc_type='_all', hosts=None, profile=None):
'''
Check for the existence of a document and if it exists, return it
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_get testindex AUx-384m0Bug_8U80wQZ
'''
es = _get_instance(hosts, profile)
try:
return es.get(index=index, id=id, doc_type=doc_type)
except elasticsearch.exceptions.NotFoundError:
return None
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 index_close(index, allow_no_indices=True, expand_wildcards='open', ignore_unavailable=True, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Close specified index.
index
Index to be closed
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 ‘open’, 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_close testindex
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.close(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 close 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_restore(repository, snapshot, body=None, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Restore existing snapshot in specified repository by supplied definition.
repository
Repository name
snapshot
Snapshot name
body
Restore definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
CLI example::
salt myminion elasticsearch.snapshot_restore testrepo testsnapshot '{"indices":"index_1,index_2","ignore_unavailable":true,"include_global_state":true}'
'''
es = _get_instance(hosts, profile)
try:
response = es.snapshot.restore(repository=repository, snapshot=snapshot, body=body)
return response.get('accepted', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot restore 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))
|
saltstack/salt | salt/modules/elasticsearch.py | node_info | python | 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)) | .. 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 | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L198-L218 | [
"def _get_instance(hosts=None, profile=None):\n '''\n Return the elasticsearch instance\n '''\n es = None\n proxies = None\n use_ssl = False\n ca_certs = None\n verify_certs = True\n http_auth = None\n timeout = 10\n\n if profile is None:\n profile = 'elasticsearch'\n\n if isinstance(profile, six.string_types):\n _profile = __salt__['config.option'](profile, None)\n elif isinstance(profile, dict):\n _profile = profile\n if _profile:\n hosts = _profile.get('host', hosts)\n if not hosts:\n hosts = _profile.get('hosts', hosts)\n proxies = _profile.get('proxies', None)\n use_ssl = _profile.get('use_ssl', False)\n ca_certs = _profile.get('ca_certs', None)\n verify_certs = _profile.get('verify_certs', True)\n username = _profile.get('username', None)\n password = _profile.get('password', None)\n timeout = _profile.get('timeout', 10)\n\n if username and password:\n http_auth = (username, password)\n\n if not hosts:\n hosts = ['127.0.0.1:9200']\n if isinstance(hosts, six.string_types):\n hosts = [hosts]\n try:\n if proxies:\n # Custom connection class to use requests module with proxies\n class ProxyConnection(RequestsHttpConnection):\n def __init__(self, *args, **kwargs):\n proxies = kwargs.pop('proxies', {})\n super(ProxyConnection, self).__init__(*args, **kwargs)\n self.session.proxies = proxies\n\n es = elasticsearch.Elasticsearch(\n hosts,\n connection_class=ProxyConnection,\n proxies=proxies,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n else:\n es = elasticsearch.Elasticsearch(\n hosts,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n\n # Try the connection\n es.info()\n except elasticsearch.exceptions.TransportError as err:\n raise CommandExecutionError(\n 'Could not connect to Elasticsearch host/ cluster {0} due to {1}'.format(hosts, err))\n return es\n"
] | # -*- coding: utf-8 -*-
'''
Elasticsearch - A distributed RESTful search and analytics server
Module to provide Elasticsearch compatibility to Salt
(compatible with Elasticsearch version 1.5.2+)
.. versionadded:: 2015.8.0
:depends: `elasticsearch-py <http://elasticsearch-py.readthedocs.org/en/latest/>`_
:configuration: This module accepts connection configuration details either as
parameters or as configuration settings in /etc/salt/minion on the relevant
minions:
.. code-block:: yaml
elasticsearch:
host: '10.10.10.100:9200'
elasticsearch-cluster:
hosts:
- '10.10.10.100:9200'
- '10.10.10.101:9200'
- '10.10.10.102:9200'
elasticsearch-extra:
hosts:
- '10.10.10.100:9200'
use_ssl: True
verify_certs: True
ca_certs: /path/to/custom_ca_bundle.pem
number_of_shards: 1
number_of_replicas: 0
functions_blacklist:
- 'saltutil.find_job'
- 'pillar.items'
- 'grains.items'
proxies:
- http: http://proxy:3128
- https: http://proxy:1080
When specifying proxies the requests backend will be used and the 'proxies'
data structure is passed as-is to that module.
This data can also be passed into pillar. Options passed into opts will
overwrite options passed into pillar.
Some functionality might be limited by elasticsearch-py and Elasticsearch server versions.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
# Import third party libs
try:
import elasticsearch
from elasticsearch import RequestsHttpConnection
logging.getLogger('elasticsearch').setLevel(logging.CRITICAL)
HAS_ELASTICSEARCH = True
except ImportError:
HAS_ELASTICSEARCH = False
def __virtual__():
'''
Only load if elasticsearch libraries exist.
'''
if not HAS_ELASTICSEARCH:
return (False, 'Cannot load module elasticsearch: elasticsearch libraries not found')
return True
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 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 document_get(index, id, doc_type='_all', hosts=None, profile=None):
'''
Check for the existence of a document and if it exists, return it
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_get testindex AUx-384m0Bug_8U80wQZ
'''
es = _get_instance(hosts, profile)
try:
return es.get(index=index, id=id, doc_type=doc_type)
except elasticsearch.exceptions.NotFoundError:
return None
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 index_close(index, allow_no_indices=True, expand_wildcards='open', ignore_unavailable=True, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Close specified index.
index
Index to be closed
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 ‘open’, 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_close testindex
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.close(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 close 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_restore(repository, snapshot, body=None, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Restore existing snapshot in specified repository by supplied definition.
repository
Repository name
snapshot
Snapshot name
body
Restore definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
CLI example::
salt myminion elasticsearch.snapshot_restore testrepo testsnapshot '{"indices":"index_1,index_2","ignore_unavailable":true,"include_global_state":true}'
'''
es = _get_instance(hosts, profile)
try:
response = es.snapshot.restore(repository=repository, snapshot=snapshot, body=body)
return response.get('accepted', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot restore 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))
|
saltstack/salt | salt/modules/elasticsearch.py | cluster_health | python | 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)) | .. 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 | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L221-L243 | [
"def _get_instance(hosts=None, profile=None):\n '''\n Return the elasticsearch instance\n '''\n es = None\n proxies = None\n use_ssl = False\n ca_certs = None\n verify_certs = True\n http_auth = None\n timeout = 10\n\n if profile is None:\n profile = 'elasticsearch'\n\n if isinstance(profile, six.string_types):\n _profile = __salt__['config.option'](profile, None)\n elif isinstance(profile, dict):\n _profile = profile\n if _profile:\n hosts = _profile.get('host', hosts)\n if not hosts:\n hosts = _profile.get('hosts', hosts)\n proxies = _profile.get('proxies', None)\n use_ssl = _profile.get('use_ssl', False)\n ca_certs = _profile.get('ca_certs', None)\n verify_certs = _profile.get('verify_certs', True)\n username = _profile.get('username', None)\n password = _profile.get('password', None)\n timeout = _profile.get('timeout', 10)\n\n if username and password:\n http_auth = (username, password)\n\n if not hosts:\n hosts = ['127.0.0.1:9200']\n if isinstance(hosts, six.string_types):\n hosts = [hosts]\n try:\n if proxies:\n # Custom connection class to use requests module with proxies\n class ProxyConnection(RequestsHttpConnection):\n def __init__(self, *args, **kwargs):\n proxies = kwargs.pop('proxies', {})\n super(ProxyConnection, self).__init__(*args, **kwargs)\n self.session.proxies = proxies\n\n es = elasticsearch.Elasticsearch(\n hosts,\n connection_class=ProxyConnection,\n proxies=proxies,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n else:\n es = elasticsearch.Elasticsearch(\n hosts,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n\n # Try the connection\n es.info()\n except elasticsearch.exceptions.TransportError as err:\n raise CommandExecutionError(\n 'Could not connect to Elasticsearch host/ cluster {0} due to {1}'.format(hosts, err))\n return es\n"
] | # -*- coding: utf-8 -*-
'''
Elasticsearch - A distributed RESTful search and analytics server
Module to provide Elasticsearch compatibility to Salt
(compatible with Elasticsearch version 1.5.2+)
.. versionadded:: 2015.8.0
:depends: `elasticsearch-py <http://elasticsearch-py.readthedocs.org/en/latest/>`_
:configuration: This module accepts connection configuration details either as
parameters or as configuration settings in /etc/salt/minion on the relevant
minions:
.. code-block:: yaml
elasticsearch:
host: '10.10.10.100:9200'
elasticsearch-cluster:
hosts:
- '10.10.10.100:9200'
- '10.10.10.101:9200'
- '10.10.10.102:9200'
elasticsearch-extra:
hosts:
- '10.10.10.100:9200'
use_ssl: True
verify_certs: True
ca_certs: /path/to/custom_ca_bundle.pem
number_of_shards: 1
number_of_replicas: 0
functions_blacklist:
- 'saltutil.find_job'
- 'pillar.items'
- 'grains.items'
proxies:
- http: http://proxy:3128
- https: http://proxy:1080
When specifying proxies the requests backend will be used and the 'proxies'
data structure is passed as-is to that module.
This data can also be passed into pillar. Options passed into opts will
overwrite options passed into pillar.
Some functionality might be limited by elasticsearch-py and Elasticsearch server versions.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
# Import third party libs
try:
import elasticsearch
from elasticsearch import RequestsHttpConnection
logging.getLogger('elasticsearch').setLevel(logging.CRITICAL)
HAS_ELASTICSEARCH = True
except ImportError:
HAS_ELASTICSEARCH = False
def __virtual__():
'''
Only load if elasticsearch libraries exist.
'''
if not HAS_ELASTICSEARCH:
return (False, 'Cannot load module elasticsearch: elasticsearch libraries not found')
return True
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_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 document_get(index, id, doc_type='_all', hosts=None, profile=None):
'''
Check for the existence of a document and if it exists, return it
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_get testindex AUx-384m0Bug_8U80wQZ
'''
es = _get_instance(hosts, profile)
try:
return es.get(index=index, id=id, doc_type=doc_type)
except elasticsearch.exceptions.NotFoundError:
return None
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 index_close(index, allow_no_indices=True, expand_wildcards='open', ignore_unavailable=True, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Close specified index.
index
Index to be closed
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 ‘open’, 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_close testindex
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.close(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 close 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_restore(repository, snapshot, body=None, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Restore existing snapshot in specified repository by supplied definition.
repository
Repository name
snapshot
Snapshot name
body
Restore definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
CLI example::
salt myminion elasticsearch.snapshot_restore testrepo testsnapshot '{"indices":"index_1,index_2","ignore_unavailable":true,"include_global_state":true}'
'''
es = _get_instance(hosts, profile)
try:
response = es.snapshot.restore(repository=repository, snapshot=snapshot, body=body)
return response.get('accepted', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot restore 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))
|
saltstack/salt | salt/modules/elasticsearch.py | cluster_stats | python | 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)) | .. 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 | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L246-L264 | [
"def _get_instance(hosts=None, profile=None):\n '''\n Return the elasticsearch instance\n '''\n es = None\n proxies = None\n use_ssl = False\n ca_certs = None\n verify_certs = True\n http_auth = None\n timeout = 10\n\n if profile is None:\n profile = 'elasticsearch'\n\n if isinstance(profile, six.string_types):\n _profile = __salt__['config.option'](profile, None)\n elif isinstance(profile, dict):\n _profile = profile\n if _profile:\n hosts = _profile.get('host', hosts)\n if not hosts:\n hosts = _profile.get('hosts', hosts)\n proxies = _profile.get('proxies', None)\n use_ssl = _profile.get('use_ssl', False)\n ca_certs = _profile.get('ca_certs', None)\n verify_certs = _profile.get('verify_certs', True)\n username = _profile.get('username', None)\n password = _profile.get('password', None)\n timeout = _profile.get('timeout', 10)\n\n if username and password:\n http_auth = (username, password)\n\n if not hosts:\n hosts = ['127.0.0.1:9200']\n if isinstance(hosts, six.string_types):\n hosts = [hosts]\n try:\n if proxies:\n # Custom connection class to use requests module with proxies\n class ProxyConnection(RequestsHttpConnection):\n def __init__(self, *args, **kwargs):\n proxies = kwargs.pop('proxies', {})\n super(ProxyConnection, self).__init__(*args, **kwargs)\n self.session.proxies = proxies\n\n es = elasticsearch.Elasticsearch(\n hosts,\n connection_class=ProxyConnection,\n proxies=proxies,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n else:\n es = elasticsearch.Elasticsearch(\n hosts,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n\n # Try the connection\n es.info()\n except elasticsearch.exceptions.TransportError as err:\n raise CommandExecutionError(\n 'Could not connect to Elasticsearch host/ cluster {0} due to {1}'.format(hosts, err))\n return es\n"
] | # -*- coding: utf-8 -*-
'''
Elasticsearch - A distributed RESTful search and analytics server
Module to provide Elasticsearch compatibility to Salt
(compatible with Elasticsearch version 1.5.2+)
.. versionadded:: 2015.8.0
:depends: `elasticsearch-py <http://elasticsearch-py.readthedocs.org/en/latest/>`_
:configuration: This module accepts connection configuration details either as
parameters or as configuration settings in /etc/salt/minion on the relevant
minions:
.. code-block:: yaml
elasticsearch:
host: '10.10.10.100:9200'
elasticsearch-cluster:
hosts:
- '10.10.10.100:9200'
- '10.10.10.101:9200'
- '10.10.10.102:9200'
elasticsearch-extra:
hosts:
- '10.10.10.100:9200'
use_ssl: True
verify_certs: True
ca_certs: /path/to/custom_ca_bundle.pem
number_of_shards: 1
number_of_replicas: 0
functions_blacklist:
- 'saltutil.find_job'
- 'pillar.items'
- 'grains.items'
proxies:
- http: http://proxy:3128
- https: http://proxy:1080
When specifying proxies the requests backend will be used and the 'proxies'
data structure is passed as-is to that module.
This data can also be passed into pillar. Options passed into opts will
overwrite options passed into pillar.
Some functionality might be limited by elasticsearch-py and Elasticsearch server versions.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
# Import third party libs
try:
import elasticsearch
from elasticsearch import RequestsHttpConnection
logging.getLogger('elasticsearch').setLevel(logging.CRITICAL)
HAS_ELASTICSEARCH = True
except ImportError:
HAS_ELASTICSEARCH = False
def __virtual__():
'''
Only load if elasticsearch libraries exist.
'''
if not HAS_ELASTICSEARCH:
return (False, 'Cannot load module elasticsearch: elasticsearch libraries not found')
return True
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 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 document_get(index, id, doc_type='_all', hosts=None, profile=None):
'''
Check for the existence of a document and if it exists, return it
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_get testindex AUx-384m0Bug_8U80wQZ
'''
es = _get_instance(hosts, profile)
try:
return es.get(index=index, id=id, doc_type=doc_type)
except elasticsearch.exceptions.NotFoundError:
return None
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 index_close(index, allow_no_indices=True, expand_wildcards='open', ignore_unavailable=True, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Close specified index.
index
Index to be closed
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 ‘open’, 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_close testindex
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.close(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 close 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_restore(repository, snapshot, body=None, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Restore existing snapshot in specified repository by supplied definition.
repository
Repository name
snapshot
Snapshot name
body
Restore definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
CLI example::
salt myminion elasticsearch.snapshot_restore testrepo testsnapshot '{"indices":"index_1,index_2","ignore_unavailable":true,"include_global_state":true}'
'''
es = _get_instance(hosts, profile)
try:
response = es.snapshot.restore(repository=repository, snapshot=snapshot, body=body)
return response.get('accepted', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot restore 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))
|
saltstack/salt | salt/modules/elasticsearch.py | alias_create | python | 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)) | 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 | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L267-L296 | [
"def _get_instance(hosts=None, profile=None):\n '''\n Return the elasticsearch instance\n '''\n es = None\n proxies = None\n use_ssl = False\n ca_certs = None\n verify_certs = True\n http_auth = None\n timeout = 10\n\n if profile is None:\n profile = 'elasticsearch'\n\n if isinstance(profile, six.string_types):\n _profile = __salt__['config.option'](profile, None)\n elif isinstance(profile, dict):\n _profile = profile\n if _profile:\n hosts = _profile.get('host', hosts)\n if not hosts:\n hosts = _profile.get('hosts', hosts)\n proxies = _profile.get('proxies', None)\n use_ssl = _profile.get('use_ssl', False)\n ca_certs = _profile.get('ca_certs', None)\n verify_certs = _profile.get('verify_certs', True)\n username = _profile.get('username', None)\n password = _profile.get('password', None)\n timeout = _profile.get('timeout', 10)\n\n if username and password:\n http_auth = (username, password)\n\n if not hosts:\n hosts = ['127.0.0.1:9200']\n if isinstance(hosts, six.string_types):\n hosts = [hosts]\n try:\n if proxies:\n # Custom connection class to use requests module with proxies\n class ProxyConnection(RequestsHttpConnection):\n def __init__(self, *args, **kwargs):\n proxies = kwargs.pop('proxies', {})\n super(ProxyConnection, self).__init__(*args, **kwargs)\n self.session.proxies = proxies\n\n es = elasticsearch.Elasticsearch(\n hosts,\n connection_class=ProxyConnection,\n proxies=proxies,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n else:\n es = elasticsearch.Elasticsearch(\n hosts,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n\n # Try the connection\n es.info()\n except elasticsearch.exceptions.TransportError as err:\n raise CommandExecutionError(\n 'Could not connect to Elasticsearch host/ cluster {0} due to {1}'.format(hosts, err))\n return es\n"
] | # -*- coding: utf-8 -*-
'''
Elasticsearch - A distributed RESTful search and analytics server
Module to provide Elasticsearch compatibility to Salt
(compatible with Elasticsearch version 1.5.2+)
.. versionadded:: 2015.8.0
:depends: `elasticsearch-py <http://elasticsearch-py.readthedocs.org/en/latest/>`_
:configuration: This module accepts connection configuration details either as
parameters or as configuration settings in /etc/salt/minion on the relevant
minions:
.. code-block:: yaml
elasticsearch:
host: '10.10.10.100:9200'
elasticsearch-cluster:
hosts:
- '10.10.10.100:9200'
- '10.10.10.101:9200'
- '10.10.10.102:9200'
elasticsearch-extra:
hosts:
- '10.10.10.100:9200'
use_ssl: True
verify_certs: True
ca_certs: /path/to/custom_ca_bundle.pem
number_of_shards: 1
number_of_replicas: 0
functions_blacklist:
- 'saltutil.find_job'
- 'pillar.items'
- 'grains.items'
proxies:
- http: http://proxy:3128
- https: http://proxy:1080
When specifying proxies the requests backend will be used and the 'proxies'
data structure is passed as-is to that module.
This data can also be passed into pillar. Options passed into opts will
overwrite options passed into pillar.
Some functionality might be limited by elasticsearch-py and Elasticsearch server versions.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
# Import third party libs
try:
import elasticsearch
from elasticsearch import RequestsHttpConnection
logging.getLogger('elasticsearch').setLevel(logging.CRITICAL)
HAS_ELASTICSEARCH = True
except ImportError:
HAS_ELASTICSEARCH = False
def __virtual__():
'''
Only load if elasticsearch libraries exist.
'''
if not HAS_ELASTICSEARCH:
return (False, 'Cannot load module elasticsearch: elasticsearch libraries not found')
return True
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_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 document_get(index, id, doc_type='_all', hosts=None, profile=None):
'''
Check for the existence of a document and if it exists, return it
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_get testindex AUx-384m0Bug_8U80wQZ
'''
es = _get_instance(hosts, profile)
try:
return es.get(index=index, id=id, doc_type=doc_type)
except elasticsearch.exceptions.NotFoundError:
return None
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 index_close(index, allow_no_indices=True, expand_wildcards='open', ignore_unavailable=True, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Close specified index.
index
Index to be closed
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 ‘open’, 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_close testindex
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.close(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 close 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_restore(repository, snapshot, body=None, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Restore existing snapshot in specified repository by supplied definition.
repository
Repository name
snapshot
Snapshot name
body
Restore definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
CLI example::
salt myminion elasticsearch.snapshot_restore testrepo testsnapshot '{"indices":"index_1,index_2","ignore_unavailable":true,"include_global_state":true}'
'''
es = _get_instance(hosts, profile)
try:
response = es.snapshot.restore(repository=repository, snapshot=snapshot, body=body)
return response.get('accepted', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot restore 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))
|
saltstack/salt | salt/modules/elasticsearch.py | alias_delete | python | 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)) | 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 | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L299-L327 | [
"def _get_instance(hosts=None, profile=None):\n '''\n Return the elasticsearch instance\n '''\n es = None\n proxies = None\n use_ssl = False\n ca_certs = None\n verify_certs = True\n http_auth = None\n timeout = 10\n\n if profile is None:\n profile = 'elasticsearch'\n\n if isinstance(profile, six.string_types):\n _profile = __salt__['config.option'](profile, None)\n elif isinstance(profile, dict):\n _profile = profile\n if _profile:\n hosts = _profile.get('host', hosts)\n if not hosts:\n hosts = _profile.get('hosts', hosts)\n proxies = _profile.get('proxies', None)\n use_ssl = _profile.get('use_ssl', False)\n ca_certs = _profile.get('ca_certs', None)\n verify_certs = _profile.get('verify_certs', True)\n username = _profile.get('username', None)\n password = _profile.get('password', None)\n timeout = _profile.get('timeout', 10)\n\n if username and password:\n http_auth = (username, password)\n\n if not hosts:\n hosts = ['127.0.0.1:9200']\n if isinstance(hosts, six.string_types):\n hosts = [hosts]\n try:\n if proxies:\n # Custom connection class to use requests module with proxies\n class ProxyConnection(RequestsHttpConnection):\n def __init__(self, *args, **kwargs):\n proxies = kwargs.pop('proxies', {})\n super(ProxyConnection, self).__init__(*args, **kwargs)\n self.session.proxies = proxies\n\n es = elasticsearch.Elasticsearch(\n hosts,\n connection_class=ProxyConnection,\n proxies=proxies,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n else:\n es = elasticsearch.Elasticsearch(\n hosts,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n\n # Try the connection\n es.info()\n except elasticsearch.exceptions.TransportError as err:\n raise CommandExecutionError(\n 'Could not connect to Elasticsearch host/ cluster {0} due to {1}'.format(hosts, err))\n return es\n"
] | # -*- coding: utf-8 -*-
'''
Elasticsearch - A distributed RESTful search and analytics server
Module to provide Elasticsearch compatibility to Salt
(compatible with Elasticsearch version 1.5.2+)
.. versionadded:: 2015.8.0
:depends: `elasticsearch-py <http://elasticsearch-py.readthedocs.org/en/latest/>`_
:configuration: This module accepts connection configuration details either as
parameters or as configuration settings in /etc/salt/minion on the relevant
minions:
.. code-block:: yaml
elasticsearch:
host: '10.10.10.100:9200'
elasticsearch-cluster:
hosts:
- '10.10.10.100:9200'
- '10.10.10.101:9200'
- '10.10.10.102:9200'
elasticsearch-extra:
hosts:
- '10.10.10.100:9200'
use_ssl: True
verify_certs: True
ca_certs: /path/to/custom_ca_bundle.pem
number_of_shards: 1
number_of_replicas: 0
functions_blacklist:
- 'saltutil.find_job'
- 'pillar.items'
- 'grains.items'
proxies:
- http: http://proxy:3128
- https: http://proxy:1080
When specifying proxies the requests backend will be used and the 'proxies'
data structure is passed as-is to that module.
This data can also be passed into pillar. Options passed into opts will
overwrite options passed into pillar.
Some functionality might be limited by elasticsearch-py and Elasticsearch server versions.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
# Import third party libs
try:
import elasticsearch
from elasticsearch import RequestsHttpConnection
logging.getLogger('elasticsearch').setLevel(logging.CRITICAL)
HAS_ELASTICSEARCH = True
except ImportError:
HAS_ELASTICSEARCH = False
def __virtual__():
'''
Only load if elasticsearch libraries exist.
'''
if not HAS_ELASTICSEARCH:
return (False, 'Cannot load module elasticsearch: elasticsearch libraries not found')
return True
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_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 document_get(index, id, doc_type='_all', hosts=None, profile=None):
'''
Check for the existence of a document and if it exists, return it
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_get testindex AUx-384m0Bug_8U80wQZ
'''
es = _get_instance(hosts, profile)
try:
return es.get(index=index, id=id, doc_type=doc_type)
except elasticsearch.exceptions.NotFoundError:
return None
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 index_close(index, allow_no_indices=True, expand_wildcards='open', ignore_unavailable=True, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Close specified index.
index
Index to be closed
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 ‘open’, 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_close testindex
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.close(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 close 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_restore(repository, snapshot, body=None, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Restore existing snapshot in specified repository by supplied definition.
repository
Repository name
snapshot
Snapshot name
body
Restore definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
CLI example::
salt myminion elasticsearch.snapshot_restore testrepo testsnapshot '{"indices":"index_1,index_2","ignore_unavailable":true,"include_global_state":true}'
'''
es = _get_instance(hosts, profile)
try:
response = es.snapshot.restore(repository=repository, snapshot=snapshot, body=body)
return response.get('accepted', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot restore 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))
|
saltstack/salt | salt/modules/elasticsearch.py | alias_exists | python | 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)) | 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 | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L330-L349 | [
"def _get_instance(hosts=None, profile=None):\n '''\n Return the elasticsearch instance\n '''\n es = None\n proxies = None\n use_ssl = False\n ca_certs = None\n verify_certs = True\n http_auth = None\n timeout = 10\n\n if profile is None:\n profile = 'elasticsearch'\n\n if isinstance(profile, six.string_types):\n _profile = __salt__['config.option'](profile, None)\n elif isinstance(profile, dict):\n _profile = profile\n if _profile:\n hosts = _profile.get('host', hosts)\n if not hosts:\n hosts = _profile.get('hosts', hosts)\n proxies = _profile.get('proxies', None)\n use_ssl = _profile.get('use_ssl', False)\n ca_certs = _profile.get('ca_certs', None)\n verify_certs = _profile.get('verify_certs', True)\n username = _profile.get('username', None)\n password = _profile.get('password', None)\n timeout = _profile.get('timeout', 10)\n\n if username and password:\n http_auth = (username, password)\n\n if not hosts:\n hosts = ['127.0.0.1:9200']\n if isinstance(hosts, six.string_types):\n hosts = [hosts]\n try:\n if proxies:\n # Custom connection class to use requests module with proxies\n class ProxyConnection(RequestsHttpConnection):\n def __init__(self, *args, **kwargs):\n proxies = kwargs.pop('proxies', {})\n super(ProxyConnection, self).__init__(*args, **kwargs)\n self.session.proxies = proxies\n\n es = elasticsearch.Elasticsearch(\n hosts,\n connection_class=ProxyConnection,\n proxies=proxies,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n else:\n es = elasticsearch.Elasticsearch(\n hosts,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n\n # Try the connection\n es.info()\n except elasticsearch.exceptions.TransportError as err:\n raise CommandExecutionError(\n 'Could not connect to Elasticsearch host/ cluster {0} due to {1}'.format(hosts, err))\n return es\n"
] | # -*- coding: utf-8 -*-
'''
Elasticsearch - A distributed RESTful search and analytics server
Module to provide Elasticsearch compatibility to Salt
(compatible with Elasticsearch version 1.5.2+)
.. versionadded:: 2015.8.0
:depends: `elasticsearch-py <http://elasticsearch-py.readthedocs.org/en/latest/>`_
:configuration: This module accepts connection configuration details either as
parameters or as configuration settings in /etc/salt/minion on the relevant
minions:
.. code-block:: yaml
elasticsearch:
host: '10.10.10.100:9200'
elasticsearch-cluster:
hosts:
- '10.10.10.100:9200'
- '10.10.10.101:9200'
- '10.10.10.102:9200'
elasticsearch-extra:
hosts:
- '10.10.10.100:9200'
use_ssl: True
verify_certs: True
ca_certs: /path/to/custom_ca_bundle.pem
number_of_shards: 1
number_of_replicas: 0
functions_blacklist:
- 'saltutil.find_job'
- 'pillar.items'
- 'grains.items'
proxies:
- http: http://proxy:3128
- https: http://proxy:1080
When specifying proxies the requests backend will be used and the 'proxies'
data structure is passed as-is to that module.
This data can also be passed into pillar. Options passed into opts will
overwrite options passed into pillar.
Some functionality might be limited by elasticsearch-py and Elasticsearch server versions.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
# Import third party libs
try:
import elasticsearch
from elasticsearch import RequestsHttpConnection
logging.getLogger('elasticsearch').setLevel(logging.CRITICAL)
HAS_ELASTICSEARCH = True
except ImportError:
HAS_ELASTICSEARCH = False
def __virtual__():
'''
Only load if elasticsearch libraries exist.
'''
if not HAS_ELASTICSEARCH:
return (False, 'Cannot load module elasticsearch: elasticsearch libraries not found')
return True
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_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 document_get(index, id, doc_type='_all', hosts=None, profile=None):
'''
Check for the existence of a document and if it exists, return it
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_get testindex AUx-384m0Bug_8U80wQZ
'''
es = _get_instance(hosts, profile)
try:
return es.get(index=index, id=id, doc_type=doc_type)
except elasticsearch.exceptions.NotFoundError:
return None
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 index_close(index, allow_no_indices=True, expand_wildcards='open', ignore_unavailable=True, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Close specified index.
index
Index to be closed
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 ‘open’, 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_close testindex
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.close(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 close 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_restore(repository, snapshot, body=None, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Restore existing snapshot in specified repository by supplied definition.
repository
Repository name
snapshot
Snapshot name
body
Restore definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
CLI example::
salt myminion elasticsearch.snapshot_restore testrepo testsnapshot '{"indices":"index_1,index_2","ignore_unavailable":true,"include_global_state":true}'
'''
es = _get_instance(hosts, profile)
try:
response = es.snapshot.restore(repository=repository, snapshot=snapshot, body=body)
return response.get('accepted', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot restore 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))
|
saltstack/salt | salt/modules/elasticsearch.py | alias_get | python | 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)) | 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 | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L352-L372 | [
"def _get_instance(hosts=None, profile=None):\n '''\n Return the elasticsearch instance\n '''\n es = None\n proxies = None\n use_ssl = False\n ca_certs = None\n verify_certs = True\n http_auth = None\n timeout = 10\n\n if profile is None:\n profile = 'elasticsearch'\n\n if isinstance(profile, six.string_types):\n _profile = __salt__['config.option'](profile, None)\n elif isinstance(profile, dict):\n _profile = profile\n if _profile:\n hosts = _profile.get('host', hosts)\n if not hosts:\n hosts = _profile.get('hosts', hosts)\n proxies = _profile.get('proxies', None)\n use_ssl = _profile.get('use_ssl', False)\n ca_certs = _profile.get('ca_certs', None)\n verify_certs = _profile.get('verify_certs', True)\n username = _profile.get('username', None)\n password = _profile.get('password', None)\n timeout = _profile.get('timeout', 10)\n\n if username and password:\n http_auth = (username, password)\n\n if not hosts:\n hosts = ['127.0.0.1:9200']\n if isinstance(hosts, six.string_types):\n hosts = [hosts]\n try:\n if proxies:\n # Custom connection class to use requests module with proxies\n class ProxyConnection(RequestsHttpConnection):\n def __init__(self, *args, **kwargs):\n proxies = kwargs.pop('proxies', {})\n super(ProxyConnection, self).__init__(*args, **kwargs)\n self.session.proxies = proxies\n\n es = elasticsearch.Elasticsearch(\n hosts,\n connection_class=ProxyConnection,\n proxies=proxies,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n else:\n es = elasticsearch.Elasticsearch(\n hosts,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n\n # Try the connection\n es.info()\n except elasticsearch.exceptions.TransportError as err:\n raise CommandExecutionError(\n 'Could not connect to Elasticsearch host/ cluster {0} due to {1}'.format(hosts, err))\n return es\n"
] | # -*- coding: utf-8 -*-
'''
Elasticsearch - A distributed RESTful search and analytics server
Module to provide Elasticsearch compatibility to Salt
(compatible with Elasticsearch version 1.5.2+)
.. versionadded:: 2015.8.0
:depends: `elasticsearch-py <http://elasticsearch-py.readthedocs.org/en/latest/>`_
:configuration: This module accepts connection configuration details either as
parameters or as configuration settings in /etc/salt/minion on the relevant
minions:
.. code-block:: yaml
elasticsearch:
host: '10.10.10.100:9200'
elasticsearch-cluster:
hosts:
- '10.10.10.100:9200'
- '10.10.10.101:9200'
- '10.10.10.102:9200'
elasticsearch-extra:
hosts:
- '10.10.10.100:9200'
use_ssl: True
verify_certs: True
ca_certs: /path/to/custom_ca_bundle.pem
number_of_shards: 1
number_of_replicas: 0
functions_blacklist:
- 'saltutil.find_job'
- 'pillar.items'
- 'grains.items'
proxies:
- http: http://proxy:3128
- https: http://proxy:1080
When specifying proxies the requests backend will be used and the 'proxies'
data structure is passed as-is to that module.
This data can also be passed into pillar. Options passed into opts will
overwrite options passed into pillar.
Some functionality might be limited by elasticsearch-py and Elasticsearch server versions.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
# Import third party libs
try:
import elasticsearch
from elasticsearch import RequestsHttpConnection
logging.getLogger('elasticsearch').setLevel(logging.CRITICAL)
HAS_ELASTICSEARCH = True
except ImportError:
HAS_ELASTICSEARCH = False
def __virtual__():
'''
Only load if elasticsearch libraries exist.
'''
if not HAS_ELASTICSEARCH:
return (False, 'Cannot load module elasticsearch: elasticsearch libraries not found')
return True
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 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 document_get(index, id, doc_type='_all', hosts=None, profile=None):
'''
Check for the existence of a document and if it exists, return it
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_get testindex AUx-384m0Bug_8U80wQZ
'''
es = _get_instance(hosts, profile)
try:
return es.get(index=index, id=id, doc_type=doc_type)
except elasticsearch.exceptions.NotFoundError:
return None
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 index_close(index, allow_no_indices=True, expand_wildcards='open', ignore_unavailable=True, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Close specified index.
index
Index to be closed
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 ‘open’, 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_close testindex
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.close(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 close 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_restore(repository, snapshot, body=None, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Restore existing snapshot in specified repository by supplied definition.
repository
Repository name
snapshot
Snapshot name
body
Restore definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
CLI example::
salt myminion elasticsearch.snapshot_restore testrepo testsnapshot '{"indices":"index_1,index_2","ignore_unavailable":true,"include_global_state":true}'
'''
es = _get_instance(hosts, profile)
try:
response = es.snapshot.restore(repository=repository, snapshot=snapshot, body=body)
return response.get('accepted', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot restore 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))
|
saltstack/salt | salt/modules/elasticsearch.py | document_create | python | 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)) | 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 '{}' | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L375-L405 | [
"def _get_instance(hosts=None, profile=None):\n '''\n Return the elasticsearch instance\n '''\n es = None\n proxies = None\n use_ssl = False\n ca_certs = None\n verify_certs = True\n http_auth = None\n timeout = 10\n\n if profile is None:\n profile = 'elasticsearch'\n\n if isinstance(profile, six.string_types):\n _profile = __salt__['config.option'](profile, None)\n elif isinstance(profile, dict):\n _profile = profile\n if _profile:\n hosts = _profile.get('host', hosts)\n if not hosts:\n hosts = _profile.get('hosts', hosts)\n proxies = _profile.get('proxies', None)\n use_ssl = _profile.get('use_ssl', False)\n ca_certs = _profile.get('ca_certs', None)\n verify_certs = _profile.get('verify_certs', True)\n username = _profile.get('username', None)\n password = _profile.get('password', None)\n timeout = _profile.get('timeout', 10)\n\n if username and password:\n http_auth = (username, password)\n\n if not hosts:\n hosts = ['127.0.0.1:9200']\n if isinstance(hosts, six.string_types):\n hosts = [hosts]\n try:\n if proxies:\n # Custom connection class to use requests module with proxies\n class ProxyConnection(RequestsHttpConnection):\n def __init__(self, *args, **kwargs):\n proxies = kwargs.pop('proxies', {})\n super(ProxyConnection, self).__init__(*args, **kwargs)\n self.session.proxies = proxies\n\n es = elasticsearch.Elasticsearch(\n hosts,\n connection_class=ProxyConnection,\n proxies=proxies,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n else:\n es = elasticsearch.Elasticsearch(\n hosts,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n\n # Try the connection\n es.info()\n except elasticsearch.exceptions.TransportError as err:\n raise CommandExecutionError(\n 'Could not connect to Elasticsearch host/ cluster {0} due to {1}'.format(hosts, err))\n return es\n"
] | # -*- coding: utf-8 -*-
'''
Elasticsearch - A distributed RESTful search and analytics server
Module to provide Elasticsearch compatibility to Salt
(compatible with Elasticsearch version 1.5.2+)
.. versionadded:: 2015.8.0
:depends: `elasticsearch-py <http://elasticsearch-py.readthedocs.org/en/latest/>`_
:configuration: This module accepts connection configuration details either as
parameters or as configuration settings in /etc/salt/minion on the relevant
minions:
.. code-block:: yaml
elasticsearch:
host: '10.10.10.100:9200'
elasticsearch-cluster:
hosts:
- '10.10.10.100:9200'
- '10.10.10.101:9200'
- '10.10.10.102:9200'
elasticsearch-extra:
hosts:
- '10.10.10.100:9200'
use_ssl: True
verify_certs: True
ca_certs: /path/to/custom_ca_bundle.pem
number_of_shards: 1
number_of_replicas: 0
functions_blacklist:
- 'saltutil.find_job'
- 'pillar.items'
- 'grains.items'
proxies:
- http: http://proxy:3128
- https: http://proxy:1080
When specifying proxies the requests backend will be used and the 'proxies'
data structure is passed as-is to that module.
This data can also be passed into pillar. Options passed into opts will
overwrite options passed into pillar.
Some functionality might be limited by elasticsearch-py and Elasticsearch server versions.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
# Import third party libs
try:
import elasticsearch
from elasticsearch import RequestsHttpConnection
logging.getLogger('elasticsearch').setLevel(logging.CRITICAL)
HAS_ELASTICSEARCH = True
except ImportError:
HAS_ELASTICSEARCH = False
def __virtual__():
'''
Only load if elasticsearch libraries exist.
'''
if not HAS_ELASTICSEARCH:
return (False, 'Cannot load module elasticsearch: elasticsearch libraries not found')
return True
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_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 document_get(index, id, doc_type='_all', hosts=None, profile=None):
'''
Check for the existence of a document and if it exists, return it
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_get testindex AUx-384m0Bug_8U80wQZ
'''
es = _get_instance(hosts, profile)
try:
return es.get(index=index, id=id, doc_type=doc_type)
except elasticsearch.exceptions.NotFoundError:
return None
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 index_close(index, allow_no_indices=True, expand_wildcards='open', ignore_unavailable=True, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Close specified index.
index
Index to be closed
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 ‘open’, 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_close testindex
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.close(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 close 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_restore(repository, snapshot, body=None, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Restore existing snapshot in specified repository by supplied definition.
repository
Repository name
snapshot
Snapshot name
body
Restore definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
CLI example::
salt myminion elasticsearch.snapshot_restore testrepo testsnapshot '{"indices":"index_1,index_2","ignore_unavailable":true,"include_global_state":true}'
'''
es = _get_instance(hosts, profile)
try:
response = es.snapshot.restore(repository=repository, snapshot=snapshot, body=body)
return response.get('accepted', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot restore 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))
|
saltstack/salt | salt/modules/elasticsearch.py | document_delete | python | 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)) | 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 | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L408-L430 | [
"def _get_instance(hosts=None, profile=None):\n '''\n Return the elasticsearch instance\n '''\n es = None\n proxies = None\n use_ssl = False\n ca_certs = None\n verify_certs = True\n http_auth = None\n timeout = 10\n\n if profile is None:\n profile = 'elasticsearch'\n\n if isinstance(profile, six.string_types):\n _profile = __salt__['config.option'](profile, None)\n elif isinstance(profile, dict):\n _profile = profile\n if _profile:\n hosts = _profile.get('host', hosts)\n if not hosts:\n hosts = _profile.get('hosts', hosts)\n proxies = _profile.get('proxies', None)\n use_ssl = _profile.get('use_ssl', False)\n ca_certs = _profile.get('ca_certs', None)\n verify_certs = _profile.get('verify_certs', True)\n username = _profile.get('username', None)\n password = _profile.get('password', None)\n timeout = _profile.get('timeout', 10)\n\n if username and password:\n http_auth = (username, password)\n\n if not hosts:\n hosts = ['127.0.0.1:9200']\n if isinstance(hosts, six.string_types):\n hosts = [hosts]\n try:\n if proxies:\n # Custom connection class to use requests module with proxies\n class ProxyConnection(RequestsHttpConnection):\n def __init__(self, *args, **kwargs):\n proxies = kwargs.pop('proxies', {})\n super(ProxyConnection, self).__init__(*args, **kwargs)\n self.session.proxies = proxies\n\n es = elasticsearch.Elasticsearch(\n hosts,\n connection_class=ProxyConnection,\n proxies=proxies,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n else:\n es = elasticsearch.Elasticsearch(\n hosts,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n\n # Try the connection\n es.info()\n except elasticsearch.exceptions.TransportError as err:\n raise CommandExecutionError(\n 'Could not connect to Elasticsearch host/ cluster {0} due to {1}'.format(hosts, err))\n return es\n"
] | # -*- coding: utf-8 -*-
'''
Elasticsearch - A distributed RESTful search and analytics server
Module to provide Elasticsearch compatibility to Salt
(compatible with Elasticsearch version 1.5.2+)
.. versionadded:: 2015.8.0
:depends: `elasticsearch-py <http://elasticsearch-py.readthedocs.org/en/latest/>`_
:configuration: This module accepts connection configuration details either as
parameters or as configuration settings in /etc/salt/minion on the relevant
minions:
.. code-block:: yaml
elasticsearch:
host: '10.10.10.100:9200'
elasticsearch-cluster:
hosts:
- '10.10.10.100:9200'
- '10.10.10.101:9200'
- '10.10.10.102:9200'
elasticsearch-extra:
hosts:
- '10.10.10.100:9200'
use_ssl: True
verify_certs: True
ca_certs: /path/to/custom_ca_bundle.pem
number_of_shards: 1
number_of_replicas: 0
functions_blacklist:
- 'saltutil.find_job'
- 'pillar.items'
- 'grains.items'
proxies:
- http: http://proxy:3128
- https: http://proxy:1080
When specifying proxies the requests backend will be used and the 'proxies'
data structure is passed as-is to that module.
This data can also be passed into pillar. Options passed into opts will
overwrite options passed into pillar.
Some functionality might be limited by elasticsearch-py and Elasticsearch server versions.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
# Import third party libs
try:
import elasticsearch
from elasticsearch import RequestsHttpConnection
logging.getLogger('elasticsearch').setLevel(logging.CRITICAL)
HAS_ELASTICSEARCH = True
except ImportError:
HAS_ELASTICSEARCH = False
def __virtual__():
'''
Only load if elasticsearch libraries exist.
'''
if not HAS_ELASTICSEARCH:
return (False, 'Cannot load module elasticsearch: elasticsearch libraries not found')
return True
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_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 document_get(index, id, doc_type='_all', hosts=None, profile=None):
'''
Check for the existence of a document and if it exists, return it
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_get testindex AUx-384m0Bug_8U80wQZ
'''
es = _get_instance(hosts, profile)
try:
return es.get(index=index, id=id, doc_type=doc_type)
except elasticsearch.exceptions.NotFoundError:
return None
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 index_close(index, allow_no_indices=True, expand_wildcards='open', ignore_unavailable=True, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Close specified index.
index
Index to be closed
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 ‘open’, 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_close testindex
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.close(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 close 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_restore(repository, snapshot, body=None, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Restore existing snapshot in specified repository by supplied definition.
repository
Repository name
snapshot
Snapshot name
body
Restore definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
CLI example::
salt myminion elasticsearch.snapshot_restore testrepo testsnapshot '{"indices":"index_1,index_2","ignore_unavailable":true,"include_global_state":true}'
'''
es = _get_instance(hosts, profile)
try:
response = es.snapshot.restore(repository=repository, snapshot=snapshot, body=body)
return response.get('accepted', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot restore 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))
|
saltstack/salt | salt/modules/elasticsearch.py | document_exists | python | 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)) | 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 | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L433-L455 | [
"def _get_instance(hosts=None, profile=None):\n '''\n Return the elasticsearch instance\n '''\n es = None\n proxies = None\n use_ssl = False\n ca_certs = None\n verify_certs = True\n http_auth = None\n timeout = 10\n\n if profile is None:\n profile = 'elasticsearch'\n\n if isinstance(profile, six.string_types):\n _profile = __salt__['config.option'](profile, None)\n elif isinstance(profile, dict):\n _profile = profile\n if _profile:\n hosts = _profile.get('host', hosts)\n if not hosts:\n hosts = _profile.get('hosts', hosts)\n proxies = _profile.get('proxies', None)\n use_ssl = _profile.get('use_ssl', False)\n ca_certs = _profile.get('ca_certs', None)\n verify_certs = _profile.get('verify_certs', True)\n username = _profile.get('username', None)\n password = _profile.get('password', None)\n timeout = _profile.get('timeout', 10)\n\n if username and password:\n http_auth = (username, password)\n\n if not hosts:\n hosts = ['127.0.0.1:9200']\n if isinstance(hosts, six.string_types):\n hosts = [hosts]\n try:\n if proxies:\n # Custom connection class to use requests module with proxies\n class ProxyConnection(RequestsHttpConnection):\n def __init__(self, *args, **kwargs):\n proxies = kwargs.pop('proxies', {})\n super(ProxyConnection, self).__init__(*args, **kwargs)\n self.session.proxies = proxies\n\n es = elasticsearch.Elasticsearch(\n hosts,\n connection_class=ProxyConnection,\n proxies=proxies,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n else:\n es = elasticsearch.Elasticsearch(\n hosts,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n\n # Try the connection\n es.info()\n except elasticsearch.exceptions.TransportError as err:\n raise CommandExecutionError(\n 'Could not connect to Elasticsearch host/ cluster {0} due to {1}'.format(hosts, err))\n return es\n"
] | # -*- coding: utf-8 -*-
'''
Elasticsearch - A distributed RESTful search and analytics server
Module to provide Elasticsearch compatibility to Salt
(compatible with Elasticsearch version 1.5.2+)
.. versionadded:: 2015.8.0
:depends: `elasticsearch-py <http://elasticsearch-py.readthedocs.org/en/latest/>`_
:configuration: This module accepts connection configuration details either as
parameters or as configuration settings in /etc/salt/minion on the relevant
minions:
.. code-block:: yaml
elasticsearch:
host: '10.10.10.100:9200'
elasticsearch-cluster:
hosts:
- '10.10.10.100:9200'
- '10.10.10.101:9200'
- '10.10.10.102:9200'
elasticsearch-extra:
hosts:
- '10.10.10.100:9200'
use_ssl: True
verify_certs: True
ca_certs: /path/to/custom_ca_bundle.pem
number_of_shards: 1
number_of_replicas: 0
functions_blacklist:
- 'saltutil.find_job'
- 'pillar.items'
- 'grains.items'
proxies:
- http: http://proxy:3128
- https: http://proxy:1080
When specifying proxies the requests backend will be used and the 'proxies'
data structure is passed as-is to that module.
This data can also be passed into pillar. Options passed into opts will
overwrite options passed into pillar.
Some functionality might be limited by elasticsearch-py and Elasticsearch server versions.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
# Import third party libs
try:
import elasticsearch
from elasticsearch import RequestsHttpConnection
logging.getLogger('elasticsearch').setLevel(logging.CRITICAL)
HAS_ELASTICSEARCH = True
except ImportError:
HAS_ELASTICSEARCH = False
def __virtual__():
'''
Only load if elasticsearch libraries exist.
'''
if not HAS_ELASTICSEARCH:
return (False, 'Cannot load module elasticsearch: elasticsearch libraries not found')
return True
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_get(index, id, doc_type='_all', hosts=None, profile=None):
'''
Check for the existence of a document and if it exists, return it
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_get testindex AUx-384m0Bug_8U80wQZ
'''
es = _get_instance(hosts, profile)
try:
return es.get(index=index, id=id, doc_type=doc_type)
except elasticsearch.exceptions.NotFoundError:
return None
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 index_close(index, allow_no_indices=True, expand_wildcards='open', ignore_unavailable=True, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Close specified index.
index
Index to be closed
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 ‘open’, 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_close testindex
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.close(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 close 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_restore(repository, snapshot, body=None, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Restore existing snapshot in specified repository by supplied definition.
repository
Repository name
snapshot
Snapshot name
body
Restore definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
CLI example::
salt myminion elasticsearch.snapshot_restore testrepo testsnapshot '{"indices":"index_1,index_2","ignore_unavailable":true,"include_global_state":true}'
'''
es = _get_instance(hosts, profile)
try:
response = es.snapshot.restore(repository=repository, snapshot=snapshot, body=body)
return response.get('accepted', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot restore 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))
|
saltstack/salt | salt/modules/elasticsearch.py | index_create | python | 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)) | 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}}}' | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L483-L514 | [
"def _get_instance(hosts=None, profile=None):\n '''\n Return the elasticsearch instance\n '''\n es = None\n proxies = None\n use_ssl = False\n ca_certs = None\n verify_certs = True\n http_auth = None\n timeout = 10\n\n if profile is None:\n profile = 'elasticsearch'\n\n if isinstance(profile, six.string_types):\n _profile = __salt__['config.option'](profile, None)\n elif isinstance(profile, dict):\n _profile = profile\n if _profile:\n hosts = _profile.get('host', hosts)\n if not hosts:\n hosts = _profile.get('hosts', hosts)\n proxies = _profile.get('proxies', None)\n use_ssl = _profile.get('use_ssl', False)\n ca_certs = _profile.get('ca_certs', None)\n verify_certs = _profile.get('verify_certs', True)\n username = _profile.get('username', None)\n password = _profile.get('password', None)\n timeout = _profile.get('timeout', 10)\n\n if username and password:\n http_auth = (username, password)\n\n if not hosts:\n hosts = ['127.0.0.1:9200']\n if isinstance(hosts, six.string_types):\n hosts = [hosts]\n try:\n if proxies:\n # Custom connection class to use requests module with proxies\n class ProxyConnection(RequestsHttpConnection):\n def __init__(self, *args, **kwargs):\n proxies = kwargs.pop('proxies', {})\n super(ProxyConnection, self).__init__(*args, **kwargs)\n self.session.proxies = proxies\n\n es = elasticsearch.Elasticsearch(\n hosts,\n connection_class=ProxyConnection,\n proxies=proxies,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n else:\n es = elasticsearch.Elasticsearch(\n hosts,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n\n # Try the connection\n es.info()\n except elasticsearch.exceptions.TransportError as err:\n raise CommandExecutionError(\n 'Could not connect to Elasticsearch host/ cluster {0} due to {1}'.format(hosts, err))\n return es\n"
] | # -*- coding: utf-8 -*-
'''
Elasticsearch - A distributed RESTful search and analytics server
Module to provide Elasticsearch compatibility to Salt
(compatible with Elasticsearch version 1.5.2+)
.. versionadded:: 2015.8.0
:depends: `elasticsearch-py <http://elasticsearch-py.readthedocs.org/en/latest/>`_
:configuration: This module accepts connection configuration details either as
parameters or as configuration settings in /etc/salt/minion on the relevant
minions:
.. code-block:: yaml
elasticsearch:
host: '10.10.10.100:9200'
elasticsearch-cluster:
hosts:
- '10.10.10.100:9200'
- '10.10.10.101:9200'
- '10.10.10.102:9200'
elasticsearch-extra:
hosts:
- '10.10.10.100:9200'
use_ssl: True
verify_certs: True
ca_certs: /path/to/custom_ca_bundle.pem
number_of_shards: 1
number_of_replicas: 0
functions_blacklist:
- 'saltutil.find_job'
- 'pillar.items'
- 'grains.items'
proxies:
- http: http://proxy:3128
- https: http://proxy:1080
When specifying proxies the requests backend will be used and the 'proxies'
data structure is passed as-is to that module.
This data can also be passed into pillar. Options passed into opts will
overwrite options passed into pillar.
Some functionality might be limited by elasticsearch-py and Elasticsearch server versions.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
# Import third party libs
try:
import elasticsearch
from elasticsearch import RequestsHttpConnection
logging.getLogger('elasticsearch').setLevel(logging.CRITICAL)
HAS_ELASTICSEARCH = True
except ImportError:
HAS_ELASTICSEARCH = False
def __virtual__():
'''
Only load if elasticsearch libraries exist.
'''
if not HAS_ELASTICSEARCH:
return (False, 'Cannot load module elasticsearch: elasticsearch libraries not found')
return True
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 document_get(index, id, doc_type='_all', hosts=None, profile=None):
'''
Check for the existence of a document and if it exists, return it
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_get testindex AUx-384m0Bug_8U80wQZ
'''
es = _get_instance(hosts, profile)
try:
return es.get(index=index, id=id, doc_type=doc_type)
except elasticsearch.exceptions.NotFoundError:
return None
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_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 index_close(index, allow_no_indices=True, expand_wildcards='open', ignore_unavailable=True, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Close specified index.
index
Index to be closed
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 ‘open’, 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_close testindex
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.close(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 close 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_restore(repository, snapshot, body=None, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Restore existing snapshot in specified repository by supplied definition.
repository
Repository name
snapshot
Snapshot name
body
Restore definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
CLI example::
salt myminion elasticsearch.snapshot_restore testrepo testsnapshot '{"indices":"index_1,index_2","ignore_unavailable":true,"include_global_state":true}'
'''
es = _get_instance(hosts, profile)
try:
response = es.snapshot.restore(repository=repository, snapshot=snapshot, body=body)
return response.get('accepted', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot restore 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))
|
saltstack/salt | salt/modules/elasticsearch.py | index_delete | python | 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)) | Delete an index
index
Index name
CLI example::
salt myminion elasticsearch.index_delete testindex | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L517-L537 | [
"def _get_instance(hosts=None, profile=None):\n '''\n Return the elasticsearch instance\n '''\n es = None\n proxies = None\n use_ssl = False\n ca_certs = None\n verify_certs = True\n http_auth = None\n timeout = 10\n\n if profile is None:\n profile = 'elasticsearch'\n\n if isinstance(profile, six.string_types):\n _profile = __salt__['config.option'](profile, None)\n elif isinstance(profile, dict):\n _profile = profile\n if _profile:\n hosts = _profile.get('host', hosts)\n if not hosts:\n hosts = _profile.get('hosts', hosts)\n proxies = _profile.get('proxies', None)\n use_ssl = _profile.get('use_ssl', False)\n ca_certs = _profile.get('ca_certs', None)\n verify_certs = _profile.get('verify_certs', True)\n username = _profile.get('username', None)\n password = _profile.get('password', None)\n timeout = _profile.get('timeout', 10)\n\n if username and password:\n http_auth = (username, password)\n\n if not hosts:\n hosts = ['127.0.0.1:9200']\n if isinstance(hosts, six.string_types):\n hosts = [hosts]\n try:\n if proxies:\n # Custom connection class to use requests module with proxies\n class ProxyConnection(RequestsHttpConnection):\n def __init__(self, *args, **kwargs):\n proxies = kwargs.pop('proxies', {})\n super(ProxyConnection, self).__init__(*args, **kwargs)\n self.session.proxies = proxies\n\n es = elasticsearch.Elasticsearch(\n hosts,\n connection_class=ProxyConnection,\n proxies=proxies,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n else:\n es = elasticsearch.Elasticsearch(\n hosts,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n\n # Try the connection\n es.info()\n except elasticsearch.exceptions.TransportError as err:\n raise CommandExecutionError(\n 'Could not connect to Elasticsearch host/ cluster {0} due to {1}'.format(hosts, err))\n return es\n"
] | # -*- coding: utf-8 -*-
'''
Elasticsearch - A distributed RESTful search and analytics server
Module to provide Elasticsearch compatibility to Salt
(compatible with Elasticsearch version 1.5.2+)
.. versionadded:: 2015.8.0
:depends: `elasticsearch-py <http://elasticsearch-py.readthedocs.org/en/latest/>`_
:configuration: This module accepts connection configuration details either as
parameters or as configuration settings in /etc/salt/minion on the relevant
minions:
.. code-block:: yaml
elasticsearch:
host: '10.10.10.100:9200'
elasticsearch-cluster:
hosts:
- '10.10.10.100:9200'
- '10.10.10.101:9200'
- '10.10.10.102:9200'
elasticsearch-extra:
hosts:
- '10.10.10.100:9200'
use_ssl: True
verify_certs: True
ca_certs: /path/to/custom_ca_bundle.pem
number_of_shards: 1
number_of_replicas: 0
functions_blacklist:
- 'saltutil.find_job'
- 'pillar.items'
- 'grains.items'
proxies:
- http: http://proxy:3128
- https: http://proxy:1080
When specifying proxies the requests backend will be used and the 'proxies'
data structure is passed as-is to that module.
This data can also be passed into pillar. Options passed into opts will
overwrite options passed into pillar.
Some functionality might be limited by elasticsearch-py and Elasticsearch server versions.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
# Import third party libs
try:
import elasticsearch
from elasticsearch import RequestsHttpConnection
logging.getLogger('elasticsearch').setLevel(logging.CRITICAL)
HAS_ELASTICSEARCH = True
except ImportError:
HAS_ELASTICSEARCH = False
def __virtual__():
'''
Only load if elasticsearch libraries exist.
'''
if not HAS_ELASTICSEARCH:
return (False, 'Cannot load module elasticsearch: elasticsearch libraries not found')
return True
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 document_get(index, id, doc_type='_all', hosts=None, profile=None):
'''
Check for the existence of a document and if it exists, return it
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_get testindex AUx-384m0Bug_8U80wQZ
'''
es = _get_instance(hosts, profile)
try:
return es.get(index=index, id=id, doc_type=doc_type)
except elasticsearch.exceptions.NotFoundError:
return None
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_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 index_close(index, allow_no_indices=True, expand_wildcards='open', ignore_unavailable=True, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Close specified index.
index
Index to be closed
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 ‘open’, 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_close testindex
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.close(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 close 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_restore(repository, snapshot, body=None, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Restore existing snapshot in specified repository by supplied definition.
repository
Repository name
snapshot
Snapshot name
body
Restore definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
CLI example::
salt myminion elasticsearch.snapshot_restore testrepo testsnapshot '{"indices":"index_1,index_2","ignore_unavailable":true,"include_global_state":true}'
'''
es = _get_instance(hosts, profile)
try:
response = es.snapshot.restore(repository=repository, snapshot=snapshot, body=body)
return response.get('accepted', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot restore 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))
|
saltstack/salt | salt/modules/elasticsearch.py | index_exists | python | 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)) | Return a boolean indicating whether given index exists
index
Index name
CLI example::
salt myminion elasticsearch.index_exists testindex | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L540-L558 | [
"def _get_instance(hosts=None, profile=None):\n '''\n Return the elasticsearch instance\n '''\n es = None\n proxies = None\n use_ssl = False\n ca_certs = None\n verify_certs = True\n http_auth = None\n timeout = 10\n\n if profile is None:\n profile = 'elasticsearch'\n\n if isinstance(profile, six.string_types):\n _profile = __salt__['config.option'](profile, None)\n elif isinstance(profile, dict):\n _profile = profile\n if _profile:\n hosts = _profile.get('host', hosts)\n if not hosts:\n hosts = _profile.get('hosts', hosts)\n proxies = _profile.get('proxies', None)\n use_ssl = _profile.get('use_ssl', False)\n ca_certs = _profile.get('ca_certs', None)\n verify_certs = _profile.get('verify_certs', True)\n username = _profile.get('username', None)\n password = _profile.get('password', None)\n timeout = _profile.get('timeout', 10)\n\n if username and password:\n http_auth = (username, password)\n\n if not hosts:\n hosts = ['127.0.0.1:9200']\n if isinstance(hosts, six.string_types):\n hosts = [hosts]\n try:\n if proxies:\n # Custom connection class to use requests module with proxies\n class ProxyConnection(RequestsHttpConnection):\n def __init__(self, *args, **kwargs):\n proxies = kwargs.pop('proxies', {})\n super(ProxyConnection, self).__init__(*args, **kwargs)\n self.session.proxies = proxies\n\n es = elasticsearch.Elasticsearch(\n hosts,\n connection_class=ProxyConnection,\n proxies=proxies,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n else:\n es = elasticsearch.Elasticsearch(\n hosts,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n\n # Try the connection\n es.info()\n except elasticsearch.exceptions.TransportError as err:\n raise CommandExecutionError(\n 'Could not connect to Elasticsearch host/ cluster {0} due to {1}'.format(hosts, err))\n return es\n"
] | # -*- coding: utf-8 -*-
'''
Elasticsearch - A distributed RESTful search and analytics server
Module to provide Elasticsearch compatibility to Salt
(compatible with Elasticsearch version 1.5.2+)
.. versionadded:: 2015.8.0
:depends: `elasticsearch-py <http://elasticsearch-py.readthedocs.org/en/latest/>`_
:configuration: This module accepts connection configuration details either as
parameters or as configuration settings in /etc/salt/minion on the relevant
minions:
.. code-block:: yaml
elasticsearch:
host: '10.10.10.100:9200'
elasticsearch-cluster:
hosts:
- '10.10.10.100:9200'
- '10.10.10.101:9200'
- '10.10.10.102:9200'
elasticsearch-extra:
hosts:
- '10.10.10.100:9200'
use_ssl: True
verify_certs: True
ca_certs: /path/to/custom_ca_bundle.pem
number_of_shards: 1
number_of_replicas: 0
functions_blacklist:
- 'saltutil.find_job'
- 'pillar.items'
- 'grains.items'
proxies:
- http: http://proxy:3128
- https: http://proxy:1080
When specifying proxies the requests backend will be used and the 'proxies'
data structure is passed as-is to that module.
This data can also be passed into pillar. Options passed into opts will
overwrite options passed into pillar.
Some functionality might be limited by elasticsearch-py and Elasticsearch server versions.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
# Import third party libs
try:
import elasticsearch
from elasticsearch import RequestsHttpConnection
logging.getLogger('elasticsearch').setLevel(logging.CRITICAL)
HAS_ELASTICSEARCH = True
except ImportError:
HAS_ELASTICSEARCH = False
def __virtual__():
'''
Only load if elasticsearch libraries exist.
'''
if not HAS_ELASTICSEARCH:
return (False, 'Cannot load module elasticsearch: elasticsearch libraries not found')
return True
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 document_get(index, id, doc_type='_all', hosts=None, profile=None):
'''
Check for the existence of a document and if it exists, return it
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_get testindex AUx-384m0Bug_8U80wQZ
'''
es = _get_instance(hosts, profile)
try:
return es.get(index=index, id=id, doc_type=doc_type)
except elasticsearch.exceptions.NotFoundError:
return None
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_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 index_close(index, allow_no_indices=True, expand_wildcards='open', ignore_unavailable=True, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Close specified index.
index
Index to be closed
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 ‘open’, 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_close testindex
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.close(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 close 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_restore(repository, snapshot, body=None, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Restore existing snapshot in specified repository by supplied definition.
repository
Repository name
snapshot
Snapshot name
body
Restore definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
CLI example::
salt myminion elasticsearch.snapshot_restore testrepo testsnapshot '{"indices":"index_1,index_2","ignore_unavailable":true,"include_global_state":true}'
'''
es = _get_instance(hosts, profile)
try:
response = es.snapshot.restore(repository=repository, snapshot=snapshot, body=body)
return response.get('accepted', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot restore 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))
|
saltstack/salt | salt/modules/elasticsearch.py | index_get | python | 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)) | Check for the existence of an index and if it exists, return it
index
Index name
CLI example::
salt myminion elasticsearch.index_get testindex | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L561-L579 | [
"def _get_instance(hosts=None, profile=None):\n '''\n Return the elasticsearch instance\n '''\n es = None\n proxies = None\n use_ssl = False\n ca_certs = None\n verify_certs = True\n http_auth = None\n timeout = 10\n\n if profile is None:\n profile = 'elasticsearch'\n\n if isinstance(profile, six.string_types):\n _profile = __salt__['config.option'](profile, None)\n elif isinstance(profile, dict):\n _profile = profile\n if _profile:\n hosts = _profile.get('host', hosts)\n if not hosts:\n hosts = _profile.get('hosts', hosts)\n proxies = _profile.get('proxies', None)\n use_ssl = _profile.get('use_ssl', False)\n ca_certs = _profile.get('ca_certs', None)\n verify_certs = _profile.get('verify_certs', True)\n username = _profile.get('username', None)\n password = _profile.get('password', None)\n timeout = _profile.get('timeout', 10)\n\n if username and password:\n http_auth = (username, password)\n\n if not hosts:\n hosts = ['127.0.0.1:9200']\n if isinstance(hosts, six.string_types):\n hosts = [hosts]\n try:\n if proxies:\n # Custom connection class to use requests module with proxies\n class ProxyConnection(RequestsHttpConnection):\n def __init__(self, *args, **kwargs):\n proxies = kwargs.pop('proxies', {})\n super(ProxyConnection, self).__init__(*args, **kwargs)\n self.session.proxies = proxies\n\n es = elasticsearch.Elasticsearch(\n hosts,\n connection_class=ProxyConnection,\n proxies=proxies,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n else:\n es = elasticsearch.Elasticsearch(\n hosts,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n\n # Try the connection\n es.info()\n except elasticsearch.exceptions.TransportError as err:\n raise CommandExecutionError(\n 'Could not connect to Elasticsearch host/ cluster {0} due to {1}'.format(hosts, err))\n return es\n"
] | # -*- coding: utf-8 -*-
'''
Elasticsearch - A distributed RESTful search and analytics server
Module to provide Elasticsearch compatibility to Salt
(compatible with Elasticsearch version 1.5.2+)
.. versionadded:: 2015.8.0
:depends: `elasticsearch-py <http://elasticsearch-py.readthedocs.org/en/latest/>`_
:configuration: This module accepts connection configuration details either as
parameters or as configuration settings in /etc/salt/minion on the relevant
minions:
.. code-block:: yaml
elasticsearch:
host: '10.10.10.100:9200'
elasticsearch-cluster:
hosts:
- '10.10.10.100:9200'
- '10.10.10.101:9200'
- '10.10.10.102:9200'
elasticsearch-extra:
hosts:
- '10.10.10.100:9200'
use_ssl: True
verify_certs: True
ca_certs: /path/to/custom_ca_bundle.pem
number_of_shards: 1
number_of_replicas: 0
functions_blacklist:
- 'saltutil.find_job'
- 'pillar.items'
- 'grains.items'
proxies:
- http: http://proxy:3128
- https: http://proxy:1080
When specifying proxies the requests backend will be used and the 'proxies'
data structure is passed as-is to that module.
This data can also be passed into pillar. Options passed into opts will
overwrite options passed into pillar.
Some functionality might be limited by elasticsearch-py and Elasticsearch server versions.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
# Import third party libs
try:
import elasticsearch
from elasticsearch import RequestsHttpConnection
logging.getLogger('elasticsearch').setLevel(logging.CRITICAL)
HAS_ELASTICSEARCH = True
except ImportError:
HAS_ELASTICSEARCH = False
def __virtual__():
'''
Only load if elasticsearch libraries exist.
'''
if not HAS_ELASTICSEARCH:
return (False, 'Cannot load module elasticsearch: elasticsearch libraries not found')
return True
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 document_get(index, id, doc_type='_all', hosts=None, profile=None):
'''
Check for the existence of a document and if it exists, return it
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_get testindex AUx-384m0Bug_8U80wQZ
'''
es = _get_instance(hosts, profile)
try:
return es.get(index=index, id=id, doc_type=doc_type)
except elasticsearch.exceptions.NotFoundError:
return None
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_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 index_close(index, allow_no_indices=True, expand_wildcards='open', ignore_unavailable=True, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Close specified index.
index
Index to be closed
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 ‘open’, 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_close testindex
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.close(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 close 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_restore(repository, snapshot, body=None, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Restore existing snapshot in specified repository by supplied definition.
repository
Repository name
snapshot
Snapshot name
body
Restore definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
CLI example::
salt myminion elasticsearch.snapshot_restore testrepo testsnapshot '{"indices":"index_1,index_2","ignore_unavailable":true,"include_global_state":true}'
'''
es = _get_instance(hosts, profile)
try:
response = es.snapshot.restore(repository=repository, snapshot=snapshot, body=body)
return response.get('accepted', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot restore 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))
|
saltstack/salt | salt/modules/elasticsearch.py | index_open | python | 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)) | .. 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 | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L582-L608 | [
"def _get_instance(hosts=None, profile=None):\n '''\n Return the elasticsearch instance\n '''\n es = None\n proxies = None\n use_ssl = False\n ca_certs = None\n verify_certs = True\n http_auth = None\n timeout = 10\n\n if profile is None:\n profile = 'elasticsearch'\n\n if isinstance(profile, six.string_types):\n _profile = __salt__['config.option'](profile, None)\n elif isinstance(profile, dict):\n _profile = profile\n if _profile:\n hosts = _profile.get('host', hosts)\n if not hosts:\n hosts = _profile.get('hosts', hosts)\n proxies = _profile.get('proxies', None)\n use_ssl = _profile.get('use_ssl', False)\n ca_certs = _profile.get('ca_certs', None)\n verify_certs = _profile.get('verify_certs', True)\n username = _profile.get('username', None)\n password = _profile.get('password', None)\n timeout = _profile.get('timeout', 10)\n\n if username and password:\n http_auth = (username, password)\n\n if not hosts:\n hosts = ['127.0.0.1:9200']\n if isinstance(hosts, six.string_types):\n hosts = [hosts]\n try:\n if proxies:\n # Custom connection class to use requests module with proxies\n class ProxyConnection(RequestsHttpConnection):\n def __init__(self, *args, **kwargs):\n proxies = kwargs.pop('proxies', {})\n super(ProxyConnection, self).__init__(*args, **kwargs)\n self.session.proxies = proxies\n\n es = elasticsearch.Elasticsearch(\n hosts,\n connection_class=ProxyConnection,\n proxies=proxies,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n else:\n es = elasticsearch.Elasticsearch(\n hosts,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n\n # Try the connection\n es.info()\n except elasticsearch.exceptions.TransportError as err:\n raise CommandExecutionError(\n 'Could not connect to Elasticsearch host/ cluster {0} due to {1}'.format(hosts, err))\n return es\n"
] | # -*- coding: utf-8 -*-
'''
Elasticsearch - A distributed RESTful search and analytics server
Module to provide Elasticsearch compatibility to Salt
(compatible with Elasticsearch version 1.5.2+)
.. versionadded:: 2015.8.0
:depends: `elasticsearch-py <http://elasticsearch-py.readthedocs.org/en/latest/>`_
:configuration: This module accepts connection configuration details either as
parameters or as configuration settings in /etc/salt/minion on the relevant
minions:
.. code-block:: yaml
elasticsearch:
host: '10.10.10.100:9200'
elasticsearch-cluster:
hosts:
- '10.10.10.100:9200'
- '10.10.10.101:9200'
- '10.10.10.102:9200'
elasticsearch-extra:
hosts:
- '10.10.10.100:9200'
use_ssl: True
verify_certs: True
ca_certs: /path/to/custom_ca_bundle.pem
number_of_shards: 1
number_of_replicas: 0
functions_blacklist:
- 'saltutil.find_job'
- 'pillar.items'
- 'grains.items'
proxies:
- http: http://proxy:3128
- https: http://proxy:1080
When specifying proxies the requests backend will be used and the 'proxies'
data structure is passed as-is to that module.
This data can also be passed into pillar. Options passed into opts will
overwrite options passed into pillar.
Some functionality might be limited by elasticsearch-py and Elasticsearch server versions.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
# Import third party libs
try:
import elasticsearch
from elasticsearch import RequestsHttpConnection
logging.getLogger('elasticsearch').setLevel(logging.CRITICAL)
HAS_ELASTICSEARCH = True
except ImportError:
HAS_ELASTICSEARCH = False
def __virtual__():
'''
Only load if elasticsearch libraries exist.
'''
if not HAS_ELASTICSEARCH:
return (False, 'Cannot load module elasticsearch: elasticsearch libraries not found')
return True
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 document_get(index, id, doc_type='_all', hosts=None, profile=None):
'''
Check for the existence of a document and if it exists, return it
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_get testindex AUx-384m0Bug_8U80wQZ
'''
es = _get_instance(hosts, profile)
try:
return es.get(index=index, id=id, doc_type=doc_type)
except elasticsearch.exceptions.NotFoundError:
return None
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_close(index, allow_no_indices=True, expand_wildcards='open', ignore_unavailable=True, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Close specified index.
index
Index to be closed
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 ‘open’, 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_close testindex
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.close(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 close 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_restore(repository, snapshot, body=None, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Restore existing snapshot in specified repository by supplied definition.
repository
Repository name
snapshot
Snapshot name
body
Restore definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
CLI example::
salt myminion elasticsearch.snapshot_restore testrepo testsnapshot '{"indices":"index_1,index_2","ignore_unavailable":true,"include_global_state":true}'
'''
es = _get_instance(hosts, profile)
try:
response = es.snapshot.restore(repository=repository, snapshot=snapshot, body=body)
return response.get('accepted', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot restore 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))
|
saltstack/salt | salt/modules/elasticsearch.py | mapping_create | python | 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)) | 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 } } } }' | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L640-L670 | [
"def _get_instance(hosts=None, profile=None):\n '''\n Return the elasticsearch instance\n '''\n es = None\n proxies = None\n use_ssl = False\n ca_certs = None\n verify_certs = True\n http_auth = None\n timeout = 10\n\n if profile is None:\n profile = 'elasticsearch'\n\n if isinstance(profile, six.string_types):\n _profile = __salt__['config.option'](profile, None)\n elif isinstance(profile, dict):\n _profile = profile\n if _profile:\n hosts = _profile.get('host', hosts)\n if not hosts:\n hosts = _profile.get('hosts', hosts)\n proxies = _profile.get('proxies', None)\n use_ssl = _profile.get('use_ssl', False)\n ca_certs = _profile.get('ca_certs', None)\n verify_certs = _profile.get('verify_certs', True)\n username = _profile.get('username', None)\n password = _profile.get('password', None)\n timeout = _profile.get('timeout', 10)\n\n if username and password:\n http_auth = (username, password)\n\n if not hosts:\n hosts = ['127.0.0.1:9200']\n if isinstance(hosts, six.string_types):\n hosts = [hosts]\n try:\n if proxies:\n # Custom connection class to use requests module with proxies\n class ProxyConnection(RequestsHttpConnection):\n def __init__(self, *args, **kwargs):\n proxies = kwargs.pop('proxies', {})\n super(ProxyConnection, self).__init__(*args, **kwargs)\n self.session.proxies = proxies\n\n es = elasticsearch.Elasticsearch(\n hosts,\n connection_class=ProxyConnection,\n proxies=proxies,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n else:\n es = elasticsearch.Elasticsearch(\n hosts,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n\n # Try the connection\n es.info()\n except elasticsearch.exceptions.TransportError as err:\n raise CommandExecutionError(\n 'Could not connect to Elasticsearch host/ cluster {0} due to {1}'.format(hosts, err))\n return es\n"
] | # -*- coding: utf-8 -*-
'''
Elasticsearch - A distributed RESTful search and analytics server
Module to provide Elasticsearch compatibility to Salt
(compatible with Elasticsearch version 1.5.2+)
.. versionadded:: 2015.8.0
:depends: `elasticsearch-py <http://elasticsearch-py.readthedocs.org/en/latest/>`_
:configuration: This module accepts connection configuration details either as
parameters or as configuration settings in /etc/salt/minion on the relevant
minions:
.. code-block:: yaml
elasticsearch:
host: '10.10.10.100:9200'
elasticsearch-cluster:
hosts:
- '10.10.10.100:9200'
- '10.10.10.101:9200'
- '10.10.10.102:9200'
elasticsearch-extra:
hosts:
- '10.10.10.100:9200'
use_ssl: True
verify_certs: True
ca_certs: /path/to/custom_ca_bundle.pem
number_of_shards: 1
number_of_replicas: 0
functions_blacklist:
- 'saltutil.find_job'
- 'pillar.items'
- 'grains.items'
proxies:
- http: http://proxy:3128
- https: http://proxy:1080
When specifying proxies the requests backend will be used and the 'proxies'
data structure is passed as-is to that module.
This data can also be passed into pillar. Options passed into opts will
overwrite options passed into pillar.
Some functionality might be limited by elasticsearch-py and Elasticsearch server versions.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
# Import third party libs
try:
import elasticsearch
from elasticsearch import RequestsHttpConnection
logging.getLogger('elasticsearch').setLevel(logging.CRITICAL)
HAS_ELASTICSEARCH = True
except ImportError:
HAS_ELASTICSEARCH = False
def __virtual__():
'''
Only load if elasticsearch libraries exist.
'''
if not HAS_ELASTICSEARCH:
return (False, 'Cannot load module elasticsearch: elasticsearch libraries not found')
return True
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 document_get(index, id, doc_type='_all', hosts=None, profile=None):
'''
Check for the existence of a document and if it exists, return it
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_get testindex AUx-384m0Bug_8U80wQZ
'''
es = _get_instance(hosts, profile)
try:
return es.get(index=index, id=id, doc_type=doc_type)
except elasticsearch.exceptions.NotFoundError:
return None
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 index_close(index, allow_no_indices=True, expand_wildcards='open', ignore_unavailable=True, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Close specified index.
index
Index to be closed
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 ‘open’, 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_close testindex
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.close(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 close index {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_restore(repository, snapshot, body=None, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Restore existing snapshot in specified repository by supplied definition.
repository
Repository name
snapshot
Snapshot name
body
Restore definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
CLI example::
salt myminion elasticsearch.snapshot_restore testrepo testsnapshot '{"indices":"index_1,index_2","ignore_unavailable":true,"include_global_state":true}'
'''
es = _get_instance(hosts, profile)
try:
response = es.snapshot.restore(repository=repository, snapshot=snapshot, body=body)
return response.get('accepted', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot restore 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))
|
saltstack/salt | salt/modules/elasticsearch.py | mapping_delete | python | 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+") | 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 | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L673-L696 | [
"def _get_instance(hosts=None, profile=None):\n '''\n Return the elasticsearch instance\n '''\n es = None\n proxies = None\n use_ssl = False\n ca_certs = None\n verify_certs = True\n http_auth = None\n timeout = 10\n\n if profile is None:\n profile = 'elasticsearch'\n\n if isinstance(profile, six.string_types):\n _profile = __salt__['config.option'](profile, None)\n elif isinstance(profile, dict):\n _profile = profile\n if _profile:\n hosts = _profile.get('host', hosts)\n if not hosts:\n hosts = _profile.get('hosts', hosts)\n proxies = _profile.get('proxies', None)\n use_ssl = _profile.get('use_ssl', False)\n ca_certs = _profile.get('ca_certs', None)\n verify_certs = _profile.get('verify_certs', True)\n username = _profile.get('username', None)\n password = _profile.get('password', None)\n timeout = _profile.get('timeout', 10)\n\n if username and password:\n http_auth = (username, password)\n\n if not hosts:\n hosts = ['127.0.0.1:9200']\n if isinstance(hosts, six.string_types):\n hosts = [hosts]\n try:\n if proxies:\n # Custom connection class to use requests module with proxies\n class ProxyConnection(RequestsHttpConnection):\n def __init__(self, *args, **kwargs):\n proxies = kwargs.pop('proxies', {})\n super(ProxyConnection, self).__init__(*args, **kwargs)\n self.session.proxies = proxies\n\n es = elasticsearch.Elasticsearch(\n hosts,\n connection_class=ProxyConnection,\n proxies=proxies,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n else:\n es = elasticsearch.Elasticsearch(\n hosts,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n\n # Try the connection\n es.info()\n except elasticsearch.exceptions.TransportError as err:\n raise CommandExecutionError(\n 'Could not connect to Elasticsearch host/ cluster {0} due to {1}'.format(hosts, err))\n return es\n"
] | # -*- coding: utf-8 -*-
'''
Elasticsearch - A distributed RESTful search and analytics server
Module to provide Elasticsearch compatibility to Salt
(compatible with Elasticsearch version 1.5.2+)
.. versionadded:: 2015.8.0
:depends: `elasticsearch-py <http://elasticsearch-py.readthedocs.org/en/latest/>`_
:configuration: This module accepts connection configuration details either as
parameters or as configuration settings in /etc/salt/minion on the relevant
minions:
.. code-block:: yaml
elasticsearch:
host: '10.10.10.100:9200'
elasticsearch-cluster:
hosts:
- '10.10.10.100:9200'
- '10.10.10.101:9200'
- '10.10.10.102:9200'
elasticsearch-extra:
hosts:
- '10.10.10.100:9200'
use_ssl: True
verify_certs: True
ca_certs: /path/to/custom_ca_bundle.pem
number_of_shards: 1
number_of_replicas: 0
functions_blacklist:
- 'saltutil.find_job'
- 'pillar.items'
- 'grains.items'
proxies:
- http: http://proxy:3128
- https: http://proxy:1080
When specifying proxies the requests backend will be used and the 'proxies'
data structure is passed as-is to that module.
This data can also be passed into pillar. Options passed into opts will
overwrite options passed into pillar.
Some functionality might be limited by elasticsearch-py and Elasticsearch server versions.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
# Import third party libs
try:
import elasticsearch
from elasticsearch import RequestsHttpConnection
logging.getLogger('elasticsearch').setLevel(logging.CRITICAL)
HAS_ELASTICSEARCH = True
except ImportError:
HAS_ELASTICSEARCH = False
def __virtual__():
'''
Only load if elasticsearch libraries exist.
'''
if not HAS_ELASTICSEARCH:
return (False, 'Cannot load module elasticsearch: elasticsearch libraries not found')
return True
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 document_get(index, id, doc_type='_all', hosts=None, profile=None):
'''
Check for the existence of a document and if it exists, return it
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_get testindex AUx-384m0Bug_8U80wQZ
'''
es = _get_instance(hosts, profile)
try:
return es.get(index=index, id=id, doc_type=doc_type)
except elasticsearch.exceptions.NotFoundError:
return None
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 index_close(index, allow_no_indices=True, expand_wildcards='open', ignore_unavailable=True, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Close specified index.
index
Index to be closed
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 ‘open’, 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_close testindex
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.close(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 close 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_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_restore(repository, snapshot, body=None, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Restore existing snapshot in specified repository by supplied definition.
repository
Repository name
snapshot
Snapshot name
body
Restore definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
CLI example::
salt myminion elasticsearch.snapshot_restore testrepo testsnapshot '{"indices":"index_1,index_2","ignore_unavailable":true,"include_global_state":true}'
'''
es = _get_instance(hosts, profile)
try:
response = es.snapshot.restore(repository=repository, snapshot=snapshot, body=body)
return response.get('accepted', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot restore 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))
|
saltstack/salt | salt/modules/elasticsearch.py | mapping_get | python | 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)) | 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 | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L699-L719 | [
"def _get_instance(hosts=None, profile=None):\n '''\n Return the elasticsearch instance\n '''\n es = None\n proxies = None\n use_ssl = False\n ca_certs = None\n verify_certs = True\n http_auth = None\n timeout = 10\n\n if profile is None:\n profile = 'elasticsearch'\n\n if isinstance(profile, six.string_types):\n _profile = __salt__['config.option'](profile, None)\n elif isinstance(profile, dict):\n _profile = profile\n if _profile:\n hosts = _profile.get('host', hosts)\n if not hosts:\n hosts = _profile.get('hosts', hosts)\n proxies = _profile.get('proxies', None)\n use_ssl = _profile.get('use_ssl', False)\n ca_certs = _profile.get('ca_certs', None)\n verify_certs = _profile.get('verify_certs', True)\n username = _profile.get('username', None)\n password = _profile.get('password', None)\n timeout = _profile.get('timeout', 10)\n\n if username and password:\n http_auth = (username, password)\n\n if not hosts:\n hosts = ['127.0.0.1:9200']\n if isinstance(hosts, six.string_types):\n hosts = [hosts]\n try:\n if proxies:\n # Custom connection class to use requests module with proxies\n class ProxyConnection(RequestsHttpConnection):\n def __init__(self, *args, **kwargs):\n proxies = kwargs.pop('proxies', {})\n super(ProxyConnection, self).__init__(*args, **kwargs)\n self.session.proxies = proxies\n\n es = elasticsearch.Elasticsearch(\n hosts,\n connection_class=ProxyConnection,\n proxies=proxies,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n else:\n es = elasticsearch.Elasticsearch(\n hosts,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n\n # Try the connection\n es.info()\n except elasticsearch.exceptions.TransportError as err:\n raise CommandExecutionError(\n 'Could not connect to Elasticsearch host/ cluster {0} due to {1}'.format(hosts, err))\n return es\n"
] | # -*- coding: utf-8 -*-
'''
Elasticsearch - A distributed RESTful search and analytics server
Module to provide Elasticsearch compatibility to Salt
(compatible with Elasticsearch version 1.5.2+)
.. versionadded:: 2015.8.0
:depends: `elasticsearch-py <http://elasticsearch-py.readthedocs.org/en/latest/>`_
:configuration: This module accepts connection configuration details either as
parameters or as configuration settings in /etc/salt/minion on the relevant
minions:
.. code-block:: yaml
elasticsearch:
host: '10.10.10.100:9200'
elasticsearch-cluster:
hosts:
- '10.10.10.100:9200'
- '10.10.10.101:9200'
- '10.10.10.102:9200'
elasticsearch-extra:
hosts:
- '10.10.10.100:9200'
use_ssl: True
verify_certs: True
ca_certs: /path/to/custom_ca_bundle.pem
number_of_shards: 1
number_of_replicas: 0
functions_blacklist:
- 'saltutil.find_job'
- 'pillar.items'
- 'grains.items'
proxies:
- http: http://proxy:3128
- https: http://proxy:1080
When specifying proxies the requests backend will be used and the 'proxies'
data structure is passed as-is to that module.
This data can also be passed into pillar. Options passed into opts will
overwrite options passed into pillar.
Some functionality might be limited by elasticsearch-py and Elasticsearch server versions.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
# Import third party libs
try:
import elasticsearch
from elasticsearch import RequestsHttpConnection
logging.getLogger('elasticsearch').setLevel(logging.CRITICAL)
HAS_ELASTICSEARCH = True
except ImportError:
HAS_ELASTICSEARCH = False
def __virtual__():
'''
Only load if elasticsearch libraries exist.
'''
if not HAS_ELASTICSEARCH:
return (False, 'Cannot load module elasticsearch: elasticsearch libraries not found')
return True
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 document_get(index, id, doc_type='_all', hosts=None, profile=None):
'''
Check for the existence of a document and if it exists, return it
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_get testindex AUx-384m0Bug_8U80wQZ
'''
es = _get_instance(hosts, profile)
try:
return es.get(index=index, id=id, doc_type=doc_type)
except elasticsearch.exceptions.NotFoundError:
return None
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 index_close(index, allow_no_indices=True, expand_wildcards='open', ignore_unavailable=True, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Close specified index.
index
Index to be closed
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 ‘open’, 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_close testindex
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.close(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 close 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 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_restore(repository, snapshot, body=None, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Restore existing snapshot in specified repository by supplied definition.
repository
Repository name
snapshot
Snapshot name
body
Restore definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
CLI example::
salt myminion elasticsearch.snapshot_restore testrepo testsnapshot '{"indices":"index_1,index_2","ignore_unavailable":true,"include_global_state":true}'
'''
es = _get_instance(hosts, profile)
try:
response = es.snapshot.restore(repository=repository, snapshot=snapshot, body=body)
return response.get('accepted', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot restore 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))
|
saltstack/salt | salt/modules/elasticsearch.py | index_template_create | python | 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)) | 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 } }' | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L722-L751 | [
"def _get_instance(hosts=None, profile=None):\n '''\n Return the elasticsearch instance\n '''\n es = None\n proxies = None\n use_ssl = False\n ca_certs = None\n verify_certs = True\n http_auth = None\n timeout = 10\n\n if profile is None:\n profile = 'elasticsearch'\n\n if isinstance(profile, six.string_types):\n _profile = __salt__['config.option'](profile, None)\n elif isinstance(profile, dict):\n _profile = profile\n if _profile:\n hosts = _profile.get('host', hosts)\n if not hosts:\n hosts = _profile.get('hosts', hosts)\n proxies = _profile.get('proxies', None)\n use_ssl = _profile.get('use_ssl', False)\n ca_certs = _profile.get('ca_certs', None)\n verify_certs = _profile.get('verify_certs', True)\n username = _profile.get('username', None)\n password = _profile.get('password', None)\n timeout = _profile.get('timeout', 10)\n\n if username and password:\n http_auth = (username, password)\n\n if not hosts:\n hosts = ['127.0.0.1:9200']\n if isinstance(hosts, six.string_types):\n hosts = [hosts]\n try:\n if proxies:\n # Custom connection class to use requests module with proxies\n class ProxyConnection(RequestsHttpConnection):\n def __init__(self, *args, **kwargs):\n proxies = kwargs.pop('proxies', {})\n super(ProxyConnection, self).__init__(*args, **kwargs)\n self.session.proxies = proxies\n\n es = elasticsearch.Elasticsearch(\n hosts,\n connection_class=ProxyConnection,\n proxies=proxies,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n else:\n es = elasticsearch.Elasticsearch(\n hosts,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n\n # Try the connection\n es.info()\n except elasticsearch.exceptions.TransportError as err:\n raise CommandExecutionError(\n 'Could not connect to Elasticsearch host/ cluster {0} due to {1}'.format(hosts, err))\n return es\n"
] | # -*- coding: utf-8 -*-
'''
Elasticsearch - A distributed RESTful search and analytics server
Module to provide Elasticsearch compatibility to Salt
(compatible with Elasticsearch version 1.5.2+)
.. versionadded:: 2015.8.0
:depends: `elasticsearch-py <http://elasticsearch-py.readthedocs.org/en/latest/>`_
:configuration: This module accepts connection configuration details either as
parameters or as configuration settings in /etc/salt/minion on the relevant
minions:
.. code-block:: yaml
elasticsearch:
host: '10.10.10.100:9200'
elasticsearch-cluster:
hosts:
- '10.10.10.100:9200'
- '10.10.10.101:9200'
- '10.10.10.102:9200'
elasticsearch-extra:
hosts:
- '10.10.10.100:9200'
use_ssl: True
verify_certs: True
ca_certs: /path/to/custom_ca_bundle.pem
number_of_shards: 1
number_of_replicas: 0
functions_blacklist:
- 'saltutil.find_job'
- 'pillar.items'
- 'grains.items'
proxies:
- http: http://proxy:3128
- https: http://proxy:1080
When specifying proxies the requests backend will be used and the 'proxies'
data structure is passed as-is to that module.
This data can also be passed into pillar. Options passed into opts will
overwrite options passed into pillar.
Some functionality might be limited by elasticsearch-py and Elasticsearch server versions.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
# Import third party libs
try:
import elasticsearch
from elasticsearch import RequestsHttpConnection
logging.getLogger('elasticsearch').setLevel(logging.CRITICAL)
HAS_ELASTICSEARCH = True
except ImportError:
HAS_ELASTICSEARCH = False
def __virtual__():
'''
Only load if elasticsearch libraries exist.
'''
if not HAS_ELASTICSEARCH:
return (False, 'Cannot load module elasticsearch: elasticsearch libraries not found')
return True
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 document_get(index, id, doc_type='_all', hosts=None, profile=None):
'''
Check for the existence of a document and if it exists, return it
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_get testindex AUx-384m0Bug_8U80wQZ
'''
es = _get_instance(hosts, profile)
try:
return es.get(index=index, id=id, doc_type=doc_type)
except elasticsearch.exceptions.NotFoundError:
return None
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 index_close(index, allow_no_indices=True, expand_wildcards='open', ignore_unavailable=True, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Close specified index.
index
Index to be closed
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 ‘open’, 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_close testindex
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.close(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 close 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_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_restore(repository, snapshot, body=None, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Restore existing snapshot in specified repository by supplied definition.
repository
Repository name
snapshot
Snapshot name
body
Restore definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
CLI example::
salt myminion elasticsearch.snapshot_restore testrepo testsnapshot '{"indices":"index_1,index_2","ignore_unavailable":true,"include_global_state":true}'
'''
es = _get_instance(hosts, profile)
try:
response = es.snapshot.restore(repository=repository, snapshot=snapshot, body=body)
return response.get('accepted', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot restore 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))
|
saltstack/salt | salt/modules/elasticsearch.py | index_template_delete | python | 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)) | Delete an index template (type) along with its data
name
Index template name
CLI example::
salt myminion elasticsearch.index_template_delete testindex_templ user | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L754-L773 | [
"def _get_instance(hosts=None, profile=None):\n '''\n Return the elasticsearch instance\n '''\n es = None\n proxies = None\n use_ssl = False\n ca_certs = None\n verify_certs = True\n http_auth = None\n timeout = 10\n\n if profile is None:\n profile = 'elasticsearch'\n\n if isinstance(profile, six.string_types):\n _profile = __salt__['config.option'](profile, None)\n elif isinstance(profile, dict):\n _profile = profile\n if _profile:\n hosts = _profile.get('host', hosts)\n if not hosts:\n hosts = _profile.get('hosts', hosts)\n proxies = _profile.get('proxies', None)\n use_ssl = _profile.get('use_ssl', False)\n ca_certs = _profile.get('ca_certs', None)\n verify_certs = _profile.get('verify_certs', True)\n username = _profile.get('username', None)\n password = _profile.get('password', None)\n timeout = _profile.get('timeout', 10)\n\n if username and password:\n http_auth = (username, password)\n\n if not hosts:\n hosts = ['127.0.0.1:9200']\n if isinstance(hosts, six.string_types):\n hosts = [hosts]\n try:\n if proxies:\n # Custom connection class to use requests module with proxies\n class ProxyConnection(RequestsHttpConnection):\n def __init__(self, *args, **kwargs):\n proxies = kwargs.pop('proxies', {})\n super(ProxyConnection, self).__init__(*args, **kwargs)\n self.session.proxies = proxies\n\n es = elasticsearch.Elasticsearch(\n hosts,\n connection_class=ProxyConnection,\n proxies=proxies,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n else:\n es = elasticsearch.Elasticsearch(\n hosts,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n\n # Try the connection\n es.info()\n except elasticsearch.exceptions.TransportError as err:\n raise CommandExecutionError(\n 'Could not connect to Elasticsearch host/ cluster {0} due to {1}'.format(hosts, err))\n return es\n"
] | # -*- coding: utf-8 -*-
'''
Elasticsearch - A distributed RESTful search and analytics server
Module to provide Elasticsearch compatibility to Salt
(compatible with Elasticsearch version 1.5.2+)
.. versionadded:: 2015.8.0
:depends: `elasticsearch-py <http://elasticsearch-py.readthedocs.org/en/latest/>`_
:configuration: This module accepts connection configuration details either as
parameters or as configuration settings in /etc/salt/minion on the relevant
minions:
.. code-block:: yaml
elasticsearch:
host: '10.10.10.100:9200'
elasticsearch-cluster:
hosts:
- '10.10.10.100:9200'
- '10.10.10.101:9200'
- '10.10.10.102:9200'
elasticsearch-extra:
hosts:
- '10.10.10.100:9200'
use_ssl: True
verify_certs: True
ca_certs: /path/to/custom_ca_bundle.pem
number_of_shards: 1
number_of_replicas: 0
functions_blacklist:
- 'saltutil.find_job'
- 'pillar.items'
- 'grains.items'
proxies:
- http: http://proxy:3128
- https: http://proxy:1080
When specifying proxies the requests backend will be used and the 'proxies'
data structure is passed as-is to that module.
This data can also be passed into pillar. Options passed into opts will
overwrite options passed into pillar.
Some functionality might be limited by elasticsearch-py and Elasticsearch server versions.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
# Import third party libs
try:
import elasticsearch
from elasticsearch import RequestsHttpConnection
logging.getLogger('elasticsearch').setLevel(logging.CRITICAL)
HAS_ELASTICSEARCH = True
except ImportError:
HAS_ELASTICSEARCH = False
def __virtual__():
'''
Only load if elasticsearch libraries exist.
'''
if not HAS_ELASTICSEARCH:
return (False, 'Cannot load module elasticsearch: elasticsearch libraries not found')
return True
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 document_get(index, id, doc_type='_all', hosts=None, profile=None):
'''
Check for the existence of a document and if it exists, return it
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_get testindex AUx-384m0Bug_8U80wQZ
'''
es = _get_instance(hosts, profile)
try:
return es.get(index=index, id=id, doc_type=doc_type)
except elasticsearch.exceptions.NotFoundError:
return None
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 index_close(index, allow_no_indices=True, expand_wildcards='open', ignore_unavailable=True, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Close specified index.
index
Index to be closed
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 ‘open’, 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_close testindex
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.close(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 close 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_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_restore(repository, snapshot, body=None, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Restore existing snapshot in specified repository by supplied definition.
repository
Repository name
snapshot
Snapshot name
body
Restore definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
CLI example::
salt myminion elasticsearch.snapshot_restore testrepo testsnapshot '{"indices":"index_1,index_2","ignore_unavailable":true,"include_global_state":true}'
'''
es = _get_instance(hosts, profile)
try:
response = es.snapshot.restore(repository=repository, snapshot=snapshot, body=body)
return response.get('accepted', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot restore 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))
|
saltstack/salt | salt/modules/elasticsearch.py | index_template_exists | python | 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)) | Return a boolean indicating whether given index template exists
name
Index template name
CLI example::
salt myminion elasticsearch.index_template_exists testindex_templ | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L776-L791 | [
"def _get_instance(hosts=None, profile=None):\n '''\n Return the elasticsearch instance\n '''\n es = None\n proxies = None\n use_ssl = False\n ca_certs = None\n verify_certs = True\n http_auth = None\n timeout = 10\n\n if profile is None:\n profile = 'elasticsearch'\n\n if isinstance(profile, six.string_types):\n _profile = __salt__['config.option'](profile, None)\n elif isinstance(profile, dict):\n _profile = profile\n if _profile:\n hosts = _profile.get('host', hosts)\n if not hosts:\n hosts = _profile.get('hosts', hosts)\n proxies = _profile.get('proxies', None)\n use_ssl = _profile.get('use_ssl', False)\n ca_certs = _profile.get('ca_certs', None)\n verify_certs = _profile.get('verify_certs', True)\n username = _profile.get('username', None)\n password = _profile.get('password', None)\n timeout = _profile.get('timeout', 10)\n\n if username and password:\n http_auth = (username, password)\n\n if not hosts:\n hosts = ['127.0.0.1:9200']\n if isinstance(hosts, six.string_types):\n hosts = [hosts]\n try:\n if proxies:\n # Custom connection class to use requests module with proxies\n class ProxyConnection(RequestsHttpConnection):\n def __init__(self, *args, **kwargs):\n proxies = kwargs.pop('proxies', {})\n super(ProxyConnection, self).__init__(*args, **kwargs)\n self.session.proxies = proxies\n\n es = elasticsearch.Elasticsearch(\n hosts,\n connection_class=ProxyConnection,\n proxies=proxies,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n else:\n es = elasticsearch.Elasticsearch(\n hosts,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n\n # Try the connection\n es.info()\n except elasticsearch.exceptions.TransportError as err:\n raise CommandExecutionError(\n 'Could not connect to Elasticsearch host/ cluster {0} due to {1}'.format(hosts, err))\n return es\n"
] | # -*- coding: utf-8 -*-
'''
Elasticsearch - A distributed RESTful search and analytics server
Module to provide Elasticsearch compatibility to Salt
(compatible with Elasticsearch version 1.5.2+)
.. versionadded:: 2015.8.0
:depends: `elasticsearch-py <http://elasticsearch-py.readthedocs.org/en/latest/>`_
:configuration: This module accepts connection configuration details either as
parameters or as configuration settings in /etc/salt/minion on the relevant
minions:
.. code-block:: yaml
elasticsearch:
host: '10.10.10.100:9200'
elasticsearch-cluster:
hosts:
- '10.10.10.100:9200'
- '10.10.10.101:9200'
- '10.10.10.102:9200'
elasticsearch-extra:
hosts:
- '10.10.10.100:9200'
use_ssl: True
verify_certs: True
ca_certs: /path/to/custom_ca_bundle.pem
number_of_shards: 1
number_of_replicas: 0
functions_blacklist:
- 'saltutil.find_job'
- 'pillar.items'
- 'grains.items'
proxies:
- http: http://proxy:3128
- https: http://proxy:1080
When specifying proxies the requests backend will be used and the 'proxies'
data structure is passed as-is to that module.
This data can also be passed into pillar. Options passed into opts will
overwrite options passed into pillar.
Some functionality might be limited by elasticsearch-py and Elasticsearch server versions.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
# Import third party libs
try:
import elasticsearch
from elasticsearch import RequestsHttpConnection
logging.getLogger('elasticsearch').setLevel(logging.CRITICAL)
HAS_ELASTICSEARCH = True
except ImportError:
HAS_ELASTICSEARCH = False
def __virtual__():
'''
Only load if elasticsearch libraries exist.
'''
if not HAS_ELASTICSEARCH:
return (False, 'Cannot load module elasticsearch: elasticsearch libraries not found')
return True
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 document_get(index, id, doc_type='_all', hosts=None, profile=None):
'''
Check for the existence of a document and if it exists, return it
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_get testindex AUx-384m0Bug_8U80wQZ
'''
es = _get_instance(hosts, profile)
try:
return es.get(index=index, id=id, doc_type=doc_type)
except elasticsearch.exceptions.NotFoundError:
return None
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 index_close(index, allow_no_indices=True, expand_wildcards='open', ignore_unavailable=True, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Close specified index.
index
Index to be closed
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 ‘open’, 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_close testindex
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.close(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 close 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_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_restore(repository, snapshot, body=None, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Restore existing snapshot in specified repository by supplied definition.
repository
Repository name
snapshot
Snapshot name
body
Restore definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
CLI example::
salt myminion elasticsearch.snapshot_restore testrepo testsnapshot '{"indices":"index_1,index_2","ignore_unavailable":true,"include_global_state":true}'
'''
es = _get_instance(hosts, profile)
try:
response = es.snapshot.restore(repository=repository, snapshot=snapshot, body=body)
return response.get('accepted', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot restore 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))
|
saltstack/salt | salt/modules/elasticsearch.py | index_template_get | python | 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)) | Retrieve template definition of index or index/type
name
Index template name
CLI example::
salt myminion elasticsearch.index_template_get testindex_templ | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L794-L812 | [
"def _get_instance(hosts=None, profile=None):\n '''\n Return the elasticsearch instance\n '''\n es = None\n proxies = None\n use_ssl = False\n ca_certs = None\n verify_certs = True\n http_auth = None\n timeout = 10\n\n if profile is None:\n profile = 'elasticsearch'\n\n if isinstance(profile, six.string_types):\n _profile = __salt__['config.option'](profile, None)\n elif isinstance(profile, dict):\n _profile = profile\n if _profile:\n hosts = _profile.get('host', hosts)\n if not hosts:\n hosts = _profile.get('hosts', hosts)\n proxies = _profile.get('proxies', None)\n use_ssl = _profile.get('use_ssl', False)\n ca_certs = _profile.get('ca_certs', None)\n verify_certs = _profile.get('verify_certs', True)\n username = _profile.get('username', None)\n password = _profile.get('password', None)\n timeout = _profile.get('timeout', 10)\n\n if username and password:\n http_auth = (username, password)\n\n if not hosts:\n hosts = ['127.0.0.1:9200']\n if isinstance(hosts, six.string_types):\n hosts = [hosts]\n try:\n if proxies:\n # Custom connection class to use requests module with proxies\n class ProxyConnection(RequestsHttpConnection):\n def __init__(self, *args, **kwargs):\n proxies = kwargs.pop('proxies', {})\n super(ProxyConnection, self).__init__(*args, **kwargs)\n self.session.proxies = proxies\n\n es = elasticsearch.Elasticsearch(\n hosts,\n connection_class=ProxyConnection,\n proxies=proxies,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n else:\n es = elasticsearch.Elasticsearch(\n hosts,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n\n # Try the connection\n es.info()\n except elasticsearch.exceptions.TransportError as err:\n raise CommandExecutionError(\n 'Could not connect to Elasticsearch host/ cluster {0} due to {1}'.format(hosts, err))\n return es\n"
] | # -*- coding: utf-8 -*-
'''
Elasticsearch - A distributed RESTful search and analytics server
Module to provide Elasticsearch compatibility to Salt
(compatible with Elasticsearch version 1.5.2+)
.. versionadded:: 2015.8.0
:depends: `elasticsearch-py <http://elasticsearch-py.readthedocs.org/en/latest/>`_
:configuration: This module accepts connection configuration details either as
parameters or as configuration settings in /etc/salt/minion on the relevant
minions:
.. code-block:: yaml
elasticsearch:
host: '10.10.10.100:9200'
elasticsearch-cluster:
hosts:
- '10.10.10.100:9200'
- '10.10.10.101:9200'
- '10.10.10.102:9200'
elasticsearch-extra:
hosts:
- '10.10.10.100:9200'
use_ssl: True
verify_certs: True
ca_certs: /path/to/custom_ca_bundle.pem
number_of_shards: 1
number_of_replicas: 0
functions_blacklist:
- 'saltutil.find_job'
- 'pillar.items'
- 'grains.items'
proxies:
- http: http://proxy:3128
- https: http://proxy:1080
When specifying proxies the requests backend will be used and the 'proxies'
data structure is passed as-is to that module.
This data can also be passed into pillar. Options passed into opts will
overwrite options passed into pillar.
Some functionality might be limited by elasticsearch-py and Elasticsearch server versions.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
# Import third party libs
try:
import elasticsearch
from elasticsearch import RequestsHttpConnection
logging.getLogger('elasticsearch').setLevel(logging.CRITICAL)
HAS_ELASTICSEARCH = True
except ImportError:
HAS_ELASTICSEARCH = False
def __virtual__():
'''
Only load if elasticsearch libraries exist.
'''
if not HAS_ELASTICSEARCH:
return (False, 'Cannot load module elasticsearch: elasticsearch libraries not found')
return True
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 document_get(index, id, doc_type='_all', hosts=None, profile=None):
'''
Check for the existence of a document and if it exists, return it
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_get testindex AUx-384m0Bug_8U80wQZ
'''
es = _get_instance(hosts, profile)
try:
return es.get(index=index, id=id, doc_type=doc_type)
except elasticsearch.exceptions.NotFoundError:
return None
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 index_close(index, allow_no_indices=True, expand_wildcards='open', ignore_unavailable=True, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Close specified index.
index
Index to be closed
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 ‘open’, 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_close testindex
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.close(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 close 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 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_restore(repository, snapshot, body=None, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Restore existing snapshot in specified repository by supplied definition.
repository
Repository name
snapshot
Snapshot name
body
Restore definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
CLI example::
salt myminion elasticsearch.snapshot_restore testrepo testsnapshot '{"indices":"index_1,index_2","ignore_unavailable":true,"include_global_state":true}'
'''
es = _get_instance(hosts, profile)
try:
response = es.snapshot.restore(repository=repository, snapshot=snapshot, body=body)
return response.get('accepted', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot restore 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))
|
saltstack/salt | salt/modules/elasticsearch.py | pipeline_get | python | 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+") | .. versionadded:: 2017.7.0
Retrieve Ingest pipeline definition. Available since Elasticsearch 5.0.
id
Pipeline id
CLI example::
salt myminion elasticsearch.pipeline_get mypipeline | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L815-L837 | [
"def _get_instance(hosts=None, profile=None):\n '''\n Return the elasticsearch instance\n '''\n es = None\n proxies = None\n use_ssl = False\n ca_certs = None\n verify_certs = True\n http_auth = None\n timeout = 10\n\n if profile is None:\n profile = 'elasticsearch'\n\n if isinstance(profile, six.string_types):\n _profile = __salt__['config.option'](profile, None)\n elif isinstance(profile, dict):\n _profile = profile\n if _profile:\n hosts = _profile.get('host', hosts)\n if not hosts:\n hosts = _profile.get('hosts', hosts)\n proxies = _profile.get('proxies', None)\n use_ssl = _profile.get('use_ssl', False)\n ca_certs = _profile.get('ca_certs', None)\n verify_certs = _profile.get('verify_certs', True)\n username = _profile.get('username', None)\n password = _profile.get('password', None)\n timeout = _profile.get('timeout', 10)\n\n if username and password:\n http_auth = (username, password)\n\n if not hosts:\n hosts = ['127.0.0.1:9200']\n if isinstance(hosts, six.string_types):\n hosts = [hosts]\n try:\n if proxies:\n # Custom connection class to use requests module with proxies\n class ProxyConnection(RequestsHttpConnection):\n def __init__(self, *args, **kwargs):\n proxies = kwargs.pop('proxies', {})\n super(ProxyConnection, self).__init__(*args, **kwargs)\n self.session.proxies = proxies\n\n es = elasticsearch.Elasticsearch(\n hosts,\n connection_class=ProxyConnection,\n proxies=proxies,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n else:\n es = elasticsearch.Elasticsearch(\n hosts,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n\n # Try the connection\n es.info()\n except elasticsearch.exceptions.TransportError as err:\n raise CommandExecutionError(\n 'Could not connect to Elasticsearch host/ cluster {0} due to {1}'.format(hosts, err))\n return es\n"
] | # -*- coding: utf-8 -*-
'''
Elasticsearch - A distributed RESTful search and analytics server
Module to provide Elasticsearch compatibility to Salt
(compatible with Elasticsearch version 1.5.2+)
.. versionadded:: 2015.8.0
:depends: `elasticsearch-py <http://elasticsearch-py.readthedocs.org/en/latest/>`_
:configuration: This module accepts connection configuration details either as
parameters or as configuration settings in /etc/salt/minion on the relevant
minions:
.. code-block:: yaml
elasticsearch:
host: '10.10.10.100:9200'
elasticsearch-cluster:
hosts:
- '10.10.10.100:9200'
- '10.10.10.101:9200'
- '10.10.10.102:9200'
elasticsearch-extra:
hosts:
- '10.10.10.100:9200'
use_ssl: True
verify_certs: True
ca_certs: /path/to/custom_ca_bundle.pem
number_of_shards: 1
number_of_replicas: 0
functions_blacklist:
- 'saltutil.find_job'
- 'pillar.items'
- 'grains.items'
proxies:
- http: http://proxy:3128
- https: http://proxy:1080
When specifying proxies the requests backend will be used and the 'proxies'
data structure is passed as-is to that module.
This data can also be passed into pillar. Options passed into opts will
overwrite options passed into pillar.
Some functionality might be limited by elasticsearch-py and Elasticsearch server versions.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
# Import third party libs
try:
import elasticsearch
from elasticsearch import RequestsHttpConnection
logging.getLogger('elasticsearch').setLevel(logging.CRITICAL)
HAS_ELASTICSEARCH = True
except ImportError:
HAS_ELASTICSEARCH = False
def __virtual__():
'''
Only load if elasticsearch libraries exist.
'''
if not HAS_ELASTICSEARCH:
return (False, 'Cannot load module elasticsearch: elasticsearch libraries not found')
return True
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 document_get(index, id, doc_type='_all', hosts=None, profile=None):
'''
Check for the existence of a document and if it exists, return it
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_get testindex AUx-384m0Bug_8U80wQZ
'''
es = _get_instance(hosts, profile)
try:
return es.get(index=index, id=id, doc_type=doc_type)
except elasticsearch.exceptions.NotFoundError:
return None
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 index_close(index, allow_no_indices=True, expand_wildcards='open', ignore_unavailable=True, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Close specified index.
index
Index to be closed
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 ‘open’, 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_close testindex
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.close(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 close 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_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_restore(repository, snapshot, body=None, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Restore existing snapshot in specified repository by supplied definition.
repository
Repository name
snapshot
Snapshot name
body
Restore definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
CLI example::
salt myminion elasticsearch.snapshot_restore testrepo testsnapshot '{"indices":"index_1,index_2","ignore_unavailable":true,"include_global_state":true}'
'''
es = _get_instance(hosts, profile)
try:
response = es.snapshot.restore(repository=repository, snapshot=snapshot, body=body)
return response.get('accepted', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot restore 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))
|
saltstack/salt | salt/modules/elasticsearch.py | pipeline_delete | python | 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+") | .. versionadded:: 2017.7.0
Delete Ingest pipeline. Available since Elasticsearch 5.0.
id
Pipeline id
CLI example::
salt myminion elasticsearch.pipeline_delete mypipeline | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L840-L863 | [
"def _get_instance(hosts=None, profile=None):\n '''\n Return the elasticsearch instance\n '''\n es = None\n proxies = None\n use_ssl = False\n ca_certs = None\n verify_certs = True\n http_auth = None\n timeout = 10\n\n if profile is None:\n profile = 'elasticsearch'\n\n if isinstance(profile, six.string_types):\n _profile = __salt__['config.option'](profile, None)\n elif isinstance(profile, dict):\n _profile = profile\n if _profile:\n hosts = _profile.get('host', hosts)\n if not hosts:\n hosts = _profile.get('hosts', hosts)\n proxies = _profile.get('proxies', None)\n use_ssl = _profile.get('use_ssl', False)\n ca_certs = _profile.get('ca_certs', None)\n verify_certs = _profile.get('verify_certs', True)\n username = _profile.get('username', None)\n password = _profile.get('password', None)\n timeout = _profile.get('timeout', 10)\n\n if username and password:\n http_auth = (username, password)\n\n if not hosts:\n hosts = ['127.0.0.1:9200']\n if isinstance(hosts, six.string_types):\n hosts = [hosts]\n try:\n if proxies:\n # Custom connection class to use requests module with proxies\n class ProxyConnection(RequestsHttpConnection):\n def __init__(self, *args, **kwargs):\n proxies = kwargs.pop('proxies', {})\n super(ProxyConnection, self).__init__(*args, **kwargs)\n self.session.proxies = proxies\n\n es = elasticsearch.Elasticsearch(\n hosts,\n connection_class=ProxyConnection,\n proxies=proxies,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n else:\n es = elasticsearch.Elasticsearch(\n hosts,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n\n # Try the connection\n es.info()\n except elasticsearch.exceptions.TransportError as err:\n raise CommandExecutionError(\n 'Could not connect to Elasticsearch host/ cluster {0} due to {1}'.format(hosts, err))\n return es\n"
] | # -*- coding: utf-8 -*-
'''
Elasticsearch - A distributed RESTful search and analytics server
Module to provide Elasticsearch compatibility to Salt
(compatible with Elasticsearch version 1.5.2+)
.. versionadded:: 2015.8.0
:depends: `elasticsearch-py <http://elasticsearch-py.readthedocs.org/en/latest/>`_
:configuration: This module accepts connection configuration details either as
parameters or as configuration settings in /etc/salt/minion on the relevant
minions:
.. code-block:: yaml
elasticsearch:
host: '10.10.10.100:9200'
elasticsearch-cluster:
hosts:
- '10.10.10.100:9200'
- '10.10.10.101:9200'
- '10.10.10.102:9200'
elasticsearch-extra:
hosts:
- '10.10.10.100:9200'
use_ssl: True
verify_certs: True
ca_certs: /path/to/custom_ca_bundle.pem
number_of_shards: 1
number_of_replicas: 0
functions_blacklist:
- 'saltutil.find_job'
- 'pillar.items'
- 'grains.items'
proxies:
- http: http://proxy:3128
- https: http://proxy:1080
When specifying proxies the requests backend will be used and the 'proxies'
data structure is passed as-is to that module.
This data can also be passed into pillar. Options passed into opts will
overwrite options passed into pillar.
Some functionality might be limited by elasticsearch-py and Elasticsearch server versions.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
# Import third party libs
try:
import elasticsearch
from elasticsearch import RequestsHttpConnection
logging.getLogger('elasticsearch').setLevel(logging.CRITICAL)
HAS_ELASTICSEARCH = True
except ImportError:
HAS_ELASTICSEARCH = False
def __virtual__():
'''
Only load if elasticsearch libraries exist.
'''
if not HAS_ELASTICSEARCH:
return (False, 'Cannot load module elasticsearch: elasticsearch libraries not found')
return True
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 document_get(index, id, doc_type='_all', hosts=None, profile=None):
'''
Check for the existence of a document and if it exists, return it
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_get testindex AUx-384m0Bug_8U80wQZ
'''
es = _get_instance(hosts, profile)
try:
return es.get(index=index, id=id, doc_type=doc_type)
except elasticsearch.exceptions.NotFoundError:
return None
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 index_close(index, allow_no_indices=True, expand_wildcards='open', ignore_unavailable=True, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Close specified index.
index
Index to be closed
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 ‘open’, 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_close testindex
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.close(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 close 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_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_restore(repository, snapshot, body=None, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Restore existing snapshot in specified repository by supplied definition.
repository
Repository name
snapshot
Snapshot name
body
Restore definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
CLI example::
salt myminion elasticsearch.snapshot_restore testrepo testsnapshot '{"indices":"index_1,index_2","ignore_unavailable":true,"include_global_state":true}'
'''
es = _get_instance(hosts, profile)
try:
response = es.snapshot.restore(repository=repository, snapshot=snapshot, body=body)
return response.get('accepted', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot restore 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))
|
saltstack/salt | salt/modules/elasticsearch.py | pipeline_create | python | 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+") | .. 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}}"}}]}' | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L866-L888 | [
"def _get_instance(hosts=None, profile=None):\n '''\n Return the elasticsearch instance\n '''\n es = None\n proxies = None\n use_ssl = False\n ca_certs = None\n verify_certs = True\n http_auth = None\n timeout = 10\n\n if profile is None:\n profile = 'elasticsearch'\n\n if isinstance(profile, six.string_types):\n _profile = __salt__['config.option'](profile, None)\n elif isinstance(profile, dict):\n _profile = profile\n if _profile:\n hosts = _profile.get('host', hosts)\n if not hosts:\n hosts = _profile.get('hosts', hosts)\n proxies = _profile.get('proxies', None)\n use_ssl = _profile.get('use_ssl', False)\n ca_certs = _profile.get('ca_certs', None)\n verify_certs = _profile.get('verify_certs', True)\n username = _profile.get('username', None)\n password = _profile.get('password', None)\n timeout = _profile.get('timeout', 10)\n\n if username and password:\n http_auth = (username, password)\n\n if not hosts:\n hosts = ['127.0.0.1:9200']\n if isinstance(hosts, six.string_types):\n hosts = [hosts]\n try:\n if proxies:\n # Custom connection class to use requests module with proxies\n class ProxyConnection(RequestsHttpConnection):\n def __init__(self, *args, **kwargs):\n proxies = kwargs.pop('proxies', {})\n super(ProxyConnection, self).__init__(*args, **kwargs)\n self.session.proxies = proxies\n\n es = elasticsearch.Elasticsearch(\n hosts,\n connection_class=ProxyConnection,\n proxies=proxies,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n else:\n es = elasticsearch.Elasticsearch(\n hosts,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n\n # Try the connection\n es.info()\n except elasticsearch.exceptions.TransportError as err:\n raise CommandExecutionError(\n 'Could not connect to Elasticsearch host/ cluster {0} due to {1}'.format(hosts, err))\n return es\n"
] | # -*- coding: utf-8 -*-
'''
Elasticsearch - A distributed RESTful search and analytics server
Module to provide Elasticsearch compatibility to Salt
(compatible with Elasticsearch version 1.5.2+)
.. versionadded:: 2015.8.0
:depends: `elasticsearch-py <http://elasticsearch-py.readthedocs.org/en/latest/>`_
:configuration: This module accepts connection configuration details either as
parameters or as configuration settings in /etc/salt/minion on the relevant
minions:
.. code-block:: yaml
elasticsearch:
host: '10.10.10.100:9200'
elasticsearch-cluster:
hosts:
- '10.10.10.100:9200'
- '10.10.10.101:9200'
- '10.10.10.102:9200'
elasticsearch-extra:
hosts:
- '10.10.10.100:9200'
use_ssl: True
verify_certs: True
ca_certs: /path/to/custom_ca_bundle.pem
number_of_shards: 1
number_of_replicas: 0
functions_blacklist:
- 'saltutil.find_job'
- 'pillar.items'
- 'grains.items'
proxies:
- http: http://proxy:3128
- https: http://proxy:1080
When specifying proxies the requests backend will be used and the 'proxies'
data structure is passed as-is to that module.
This data can also be passed into pillar. Options passed into opts will
overwrite options passed into pillar.
Some functionality might be limited by elasticsearch-py and Elasticsearch server versions.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
# Import third party libs
try:
import elasticsearch
from elasticsearch import RequestsHttpConnection
logging.getLogger('elasticsearch').setLevel(logging.CRITICAL)
HAS_ELASTICSEARCH = True
except ImportError:
HAS_ELASTICSEARCH = False
def __virtual__():
'''
Only load if elasticsearch libraries exist.
'''
if not HAS_ELASTICSEARCH:
return (False, 'Cannot load module elasticsearch: elasticsearch libraries not found')
return True
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 document_get(index, id, doc_type='_all', hosts=None, profile=None):
'''
Check for the existence of a document and if it exists, return it
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_get testindex AUx-384m0Bug_8U80wQZ
'''
es = _get_instance(hosts, profile)
try:
return es.get(index=index, id=id, doc_type=doc_type)
except elasticsearch.exceptions.NotFoundError:
return None
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 index_close(index, allow_no_indices=True, expand_wildcards='open', ignore_unavailable=True, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Close specified index.
index
Index to be closed
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 ‘open’, 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_close testindex
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.close(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 close 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_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_restore(repository, snapshot, body=None, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Restore existing snapshot in specified repository by supplied definition.
repository
Repository name
snapshot
Snapshot name
body
Restore definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
CLI example::
salt myminion elasticsearch.snapshot_restore testrepo testsnapshot '{"indices":"index_1,index_2","ignore_unavailable":true,"include_global_state":true}'
'''
es = _get_instance(hosts, profile)
try:
response = es.snapshot.restore(repository=repository, snapshot=snapshot, body=body)
return response.get('accepted', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot restore 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))
|
saltstack/salt | salt/modules/elasticsearch.py | pipeline_simulate | python | 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+") | .. 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 | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L891-L914 | [
"def _get_instance(hosts=None, profile=None):\n '''\n Return the elasticsearch instance\n '''\n es = None\n proxies = None\n use_ssl = False\n ca_certs = None\n verify_certs = True\n http_auth = None\n timeout = 10\n\n if profile is None:\n profile = 'elasticsearch'\n\n if isinstance(profile, six.string_types):\n _profile = __salt__['config.option'](profile, None)\n elif isinstance(profile, dict):\n _profile = profile\n if _profile:\n hosts = _profile.get('host', hosts)\n if not hosts:\n hosts = _profile.get('hosts', hosts)\n proxies = _profile.get('proxies', None)\n use_ssl = _profile.get('use_ssl', False)\n ca_certs = _profile.get('ca_certs', None)\n verify_certs = _profile.get('verify_certs', True)\n username = _profile.get('username', None)\n password = _profile.get('password', None)\n timeout = _profile.get('timeout', 10)\n\n if username and password:\n http_auth = (username, password)\n\n if not hosts:\n hosts = ['127.0.0.1:9200']\n if isinstance(hosts, six.string_types):\n hosts = [hosts]\n try:\n if proxies:\n # Custom connection class to use requests module with proxies\n class ProxyConnection(RequestsHttpConnection):\n def __init__(self, *args, **kwargs):\n proxies = kwargs.pop('proxies', {})\n super(ProxyConnection, self).__init__(*args, **kwargs)\n self.session.proxies = proxies\n\n es = elasticsearch.Elasticsearch(\n hosts,\n connection_class=ProxyConnection,\n proxies=proxies,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n else:\n es = elasticsearch.Elasticsearch(\n hosts,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n\n # Try the connection\n es.info()\n except elasticsearch.exceptions.TransportError as err:\n raise CommandExecutionError(\n 'Could not connect to Elasticsearch host/ cluster {0} due to {1}'.format(hosts, err))\n return es\n"
] | # -*- coding: utf-8 -*-
'''
Elasticsearch - A distributed RESTful search and analytics server
Module to provide Elasticsearch compatibility to Salt
(compatible with Elasticsearch version 1.5.2+)
.. versionadded:: 2015.8.0
:depends: `elasticsearch-py <http://elasticsearch-py.readthedocs.org/en/latest/>`_
:configuration: This module accepts connection configuration details either as
parameters or as configuration settings in /etc/salt/minion on the relevant
minions:
.. code-block:: yaml
elasticsearch:
host: '10.10.10.100:9200'
elasticsearch-cluster:
hosts:
- '10.10.10.100:9200'
- '10.10.10.101:9200'
- '10.10.10.102:9200'
elasticsearch-extra:
hosts:
- '10.10.10.100:9200'
use_ssl: True
verify_certs: True
ca_certs: /path/to/custom_ca_bundle.pem
number_of_shards: 1
number_of_replicas: 0
functions_blacklist:
- 'saltutil.find_job'
- 'pillar.items'
- 'grains.items'
proxies:
- http: http://proxy:3128
- https: http://proxy:1080
When specifying proxies the requests backend will be used and the 'proxies'
data structure is passed as-is to that module.
This data can also be passed into pillar. Options passed into opts will
overwrite options passed into pillar.
Some functionality might be limited by elasticsearch-py and Elasticsearch server versions.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
# Import third party libs
try:
import elasticsearch
from elasticsearch import RequestsHttpConnection
logging.getLogger('elasticsearch').setLevel(logging.CRITICAL)
HAS_ELASTICSEARCH = True
except ImportError:
HAS_ELASTICSEARCH = False
def __virtual__():
'''
Only load if elasticsearch libraries exist.
'''
if not HAS_ELASTICSEARCH:
return (False, 'Cannot load module elasticsearch: elasticsearch libraries not found')
return True
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 document_get(index, id, doc_type='_all', hosts=None, profile=None):
'''
Check for the existence of a document and if it exists, return it
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_get testindex AUx-384m0Bug_8U80wQZ
'''
es = _get_instance(hosts, profile)
try:
return es.get(index=index, id=id, doc_type=doc_type)
except elasticsearch.exceptions.NotFoundError:
return None
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 index_close(index, allow_no_indices=True, expand_wildcards='open', ignore_unavailable=True, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Close specified index.
index
Index to be closed
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 ‘open’, 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_close testindex
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.close(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 close 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 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_restore(repository, snapshot, body=None, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Restore existing snapshot in specified repository by supplied definition.
repository
Repository name
snapshot
Snapshot name
body
Restore definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
CLI example::
salt myminion elasticsearch.snapshot_restore testrepo testsnapshot '{"indices":"index_1,index_2","ignore_unavailable":true,"include_global_state":true}'
'''
es = _get_instance(hosts, profile)
try:
response = es.snapshot.restore(repository=repository, snapshot=snapshot, body=body)
return response.get('accepted', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot restore 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))
|
saltstack/salt | salt/modules/elasticsearch.py | search_template_get | python | 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)) | .. versionadded:: 2017.7.0
Obtain existing search template definition.
id
Template ID
CLI example::
salt myminion elasticsearch.search_template_get mytemplate | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L917-L937 | [
"def _get_instance(hosts=None, profile=None):\n '''\n Return the elasticsearch instance\n '''\n es = None\n proxies = None\n use_ssl = False\n ca_certs = None\n verify_certs = True\n http_auth = None\n timeout = 10\n\n if profile is None:\n profile = 'elasticsearch'\n\n if isinstance(profile, six.string_types):\n _profile = __salt__['config.option'](profile, None)\n elif isinstance(profile, dict):\n _profile = profile\n if _profile:\n hosts = _profile.get('host', hosts)\n if not hosts:\n hosts = _profile.get('hosts', hosts)\n proxies = _profile.get('proxies', None)\n use_ssl = _profile.get('use_ssl', False)\n ca_certs = _profile.get('ca_certs', None)\n verify_certs = _profile.get('verify_certs', True)\n username = _profile.get('username', None)\n password = _profile.get('password', None)\n timeout = _profile.get('timeout', 10)\n\n if username and password:\n http_auth = (username, password)\n\n if not hosts:\n hosts = ['127.0.0.1:9200']\n if isinstance(hosts, six.string_types):\n hosts = [hosts]\n try:\n if proxies:\n # Custom connection class to use requests module with proxies\n class ProxyConnection(RequestsHttpConnection):\n def __init__(self, *args, **kwargs):\n proxies = kwargs.pop('proxies', {})\n super(ProxyConnection, self).__init__(*args, **kwargs)\n self.session.proxies = proxies\n\n es = elasticsearch.Elasticsearch(\n hosts,\n connection_class=ProxyConnection,\n proxies=proxies,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n else:\n es = elasticsearch.Elasticsearch(\n hosts,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n\n # Try the connection\n es.info()\n except elasticsearch.exceptions.TransportError as err:\n raise CommandExecutionError(\n 'Could not connect to Elasticsearch host/ cluster {0} due to {1}'.format(hosts, err))\n return es\n"
] | # -*- coding: utf-8 -*-
'''
Elasticsearch - A distributed RESTful search and analytics server
Module to provide Elasticsearch compatibility to Salt
(compatible with Elasticsearch version 1.5.2+)
.. versionadded:: 2015.8.0
:depends: `elasticsearch-py <http://elasticsearch-py.readthedocs.org/en/latest/>`_
:configuration: This module accepts connection configuration details either as
parameters or as configuration settings in /etc/salt/minion on the relevant
minions:
.. code-block:: yaml
elasticsearch:
host: '10.10.10.100:9200'
elasticsearch-cluster:
hosts:
- '10.10.10.100:9200'
- '10.10.10.101:9200'
- '10.10.10.102:9200'
elasticsearch-extra:
hosts:
- '10.10.10.100:9200'
use_ssl: True
verify_certs: True
ca_certs: /path/to/custom_ca_bundle.pem
number_of_shards: 1
number_of_replicas: 0
functions_blacklist:
- 'saltutil.find_job'
- 'pillar.items'
- 'grains.items'
proxies:
- http: http://proxy:3128
- https: http://proxy:1080
When specifying proxies the requests backend will be used and the 'proxies'
data structure is passed as-is to that module.
This data can also be passed into pillar. Options passed into opts will
overwrite options passed into pillar.
Some functionality might be limited by elasticsearch-py and Elasticsearch server versions.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
# Import third party libs
try:
import elasticsearch
from elasticsearch import RequestsHttpConnection
logging.getLogger('elasticsearch').setLevel(logging.CRITICAL)
HAS_ELASTICSEARCH = True
except ImportError:
HAS_ELASTICSEARCH = False
def __virtual__():
'''
Only load if elasticsearch libraries exist.
'''
if not HAS_ELASTICSEARCH:
return (False, 'Cannot load module elasticsearch: elasticsearch libraries not found')
return True
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 document_get(index, id, doc_type='_all', hosts=None, profile=None):
'''
Check for the existence of a document and if it exists, return it
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_get testindex AUx-384m0Bug_8U80wQZ
'''
es = _get_instance(hosts, profile)
try:
return es.get(index=index, id=id, doc_type=doc_type)
except elasticsearch.exceptions.NotFoundError:
return None
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 index_close(index, allow_no_indices=True, expand_wildcards='open', ignore_unavailable=True, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Close specified index.
index
Index to be closed
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 ‘open’, 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_close testindex
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.close(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 close 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_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_restore(repository, snapshot, body=None, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Restore existing snapshot in specified repository by supplied definition.
repository
Repository name
snapshot
Snapshot name
body
Restore definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
CLI example::
salt myminion elasticsearch.snapshot_restore testrepo testsnapshot '{"indices":"index_1,index_2","ignore_unavailable":true,"include_global_state":true}'
'''
es = _get_instance(hosts, profile)
try:
response = es.snapshot.restore(repository=repository, snapshot=snapshot, body=body)
return response.get('accepted', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot restore 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))
|
saltstack/salt | salt/modules/elasticsearch.py | search_template_create | python | 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)) | .. 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}}"}}}}' | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L940-L962 | [
"def _get_instance(hosts=None, profile=None):\n '''\n Return the elasticsearch instance\n '''\n es = None\n proxies = None\n use_ssl = False\n ca_certs = None\n verify_certs = True\n http_auth = None\n timeout = 10\n\n if profile is None:\n profile = 'elasticsearch'\n\n if isinstance(profile, six.string_types):\n _profile = __salt__['config.option'](profile, None)\n elif isinstance(profile, dict):\n _profile = profile\n if _profile:\n hosts = _profile.get('host', hosts)\n if not hosts:\n hosts = _profile.get('hosts', hosts)\n proxies = _profile.get('proxies', None)\n use_ssl = _profile.get('use_ssl', False)\n ca_certs = _profile.get('ca_certs', None)\n verify_certs = _profile.get('verify_certs', True)\n username = _profile.get('username', None)\n password = _profile.get('password', None)\n timeout = _profile.get('timeout', 10)\n\n if username and password:\n http_auth = (username, password)\n\n if not hosts:\n hosts = ['127.0.0.1:9200']\n if isinstance(hosts, six.string_types):\n hosts = [hosts]\n try:\n if proxies:\n # Custom connection class to use requests module with proxies\n class ProxyConnection(RequestsHttpConnection):\n def __init__(self, *args, **kwargs):\n proxies = kwargs.pop('proxies', {})\n super(ProxyConnection, self).__init__(*args, **kwargs)\n self.session.proxies = proxies\n\n es = elasticsearch.Elasticsearch(\n hosts,\n connection_class=ProxyConnection,\n proxies=proxies,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n else:\n es = elasticsearch.Elasticsearch(\n hosts,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n\n # Try the connection\n es.info()\n except elasticsearch.exceptions.TransportError as err:\n raise CommandExecutionError(\n 'Could not connect to Elasticsearch host/ cluster {0} due to {1}'.format(hosts, err))\n return es\n"
] | # -*- coding: utf-8 -*-
'''
Elasticsearch - A distributed RESTful search and analytics server
Module to provide Elasticsearch compatibility to Salt
(compatible with Elasticsearch version 1.5.2+)
.. versionadded:: 2015.8.0
:depends: `elasticsearch-py <http://elasticsearch-py.readthedocs.org/en/latest/>`_
:configuration: This module accepts connection configuration details either as
parameters or as configuration settings in /etc/salt/minion on the relevant
minions:
.. code-block:: yaml
elasticsearch:
host: '10.10.10.100:9200'
elasticsearch-cluster:
hosts:
- '10.10.10.100:9200'
- '10.10.10.101:9200'
- '10.10.10.102:9200'
elasticsearch-extra:
hosts:
- '10.10.10.100:9200'
use_ssl: True
verify_certs: True
ca_certs: /path/to/custom_ca_bundle.pem
number_of_shards: 1
number_of_replicas: 0
functions_blacklist:
- 'saltutil.find_job'
- 'pillar.items'
- 'grains.items'
proxies:
- http: http://proxy:3128
- https: http://proxy:1080
When specifying proxies the requests backend will be used and the 'proxies'
data structure is passed as-is to that module.
This data can also be passed into pillar. Options passed into opts will
overwrite options passed into pillar.
Some functionality might be limited by elasticsearch-py and Elasticsearch server versions.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
# Import third party libs
try:
import elasticsearch
from elasticsearch import RequestsHttpConnection
logging.getLogger('elasticsearch').setLevel(logging.CRITICAL)
HAS_ELASTICSEARCH = True
except ImportError:
HAS_ELASTICSEARCH = False
def __virtual__():
'''
Only load if elasticsearch libraries exist.
'''
if not HAS_ELASTICSEARCH:
return (False, 'Cannot load module elasticsearch: elasticsearch libraries not found')
return True
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 document_get(index, id, doc_type='_all', hosts=None, profile=None):
'''
Check for the existence of a document and if it exists, return it
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_get testindex AUx-384m0Bug_8U80wQZ
'''
es = _get_instance(hosts, profile)
try:
return es.get(index=index, id=id, doc_type=doc_type)
except elasticsearch.exceptions.NotFoundError:
return None
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 index_close(index, allow_no_indices=True, expand_wildcards='open', ignore_unavailable=True, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Close specified index.
index
Index to be closed
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 ‘open’, 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_close testindex
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.close(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 close 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_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_restore(repository, snapshot, body=None, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Restore existing snapshot in specified repository by supplied definition.
repository
Repository name
snapshot
Snapshot name
body
Restore definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
CLI example::
salt myminion elasticsearch.snapshot_restore testrepo testsnapshot '{"indices":"index_1,index_2","ignore_unavailable":true,"include_global_state":true}'
'''
es = _get_instance(hosts, profile)
try:
response = es.snapshot.restore(repository=repository, snapshot=snapshot, body=body)
return response.get('accepted', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot restore 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))
|
saltstack/salt | salt/modules/elasticsearch.py | search_template_delete | python | 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)) | .. versionadded:: 2017.7.0
Delete existing search template definition.
id
Template ID
CLI example::
salt myminion elasticsearch.search_template_delete mytemplate | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L965-L987 | [
"def _get_instance(hosts=None, profile=None):\n '''\n Return the elasticsearch instance\n '''\n es = None\n proxies = None\n use_ssl = False\n ca_certs = None\n verify_certs = True\n http_auth = None\n timeout = 10\n\n if profile is None:\n profile = 'elasticsearch'\n\n if isinstance(profile, six.string_types):\n _profile = __salt__['config.option'](profile, None)\n elif isinstance(profile, dict):\n _profile = profile\n if _profile:\n hosts = _profile.get('host', hosts)\n if not hosts:\n hosts = _profile.get('hosts', hosts)\n proxies = _profile.get('proxies', None)\n use_ssl = _profile.get('use_ssl', False)\n ca_certs = _profile.get('ca_certs', None)\n verify_certs = _profile.get('verify_certs', True)\n username = _profile.get('username', None)\n password = _profile.get('password', None)\n timeout = _profile.get('timeout', 10)\n\n if username and password:\n http_auth = (username, password)\n\n if not hosts:\n hosts = ['127.0.0.1:9200']\n if isinstance(hosts, six.string_types):\n hosts = [hosts]\n try:\n if proxies:\n # Custom connection class to use requests module with proxies\n class ProxyConnection(RequestsHttpConnection):\n def __init__(self, *args, **kwargs):\n proxies = kwargs.pop('proxies', {})\n super(ProxyConnection, self).__init__(*args, **kwargs)\n self.session.proxies = proxies\n\n es = elasticsearch.Elasticsearch(\n hosts,\n connection_class=ProxyConnection,\n proxies=proxies,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n else:\n es = elasticsearch.Elasticsearch(\n hosts,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n\n # Try the connection\n es.info()\n except elasticsearch.exceptions.TransportError as err:\n raise CommandExecutionError(\n 'Could not connect to Elasticsearch host/ cluster {0} due to {1}'.format(hosts, err))\n return es\n"
] | # -*- coding: utf-8 -*-
'''
Elasticsearch - A distributed RESTful search and analytics server
Module to provide Elasticsearch compatibility to Salt
(compatible with Elasticsearch version 1.5.2+)
.. versionadded:: 2015.8.0
:depends: `elasticsearch-py <http://elasticsearch-py.readthedocs.org/en/latest/>`_
:configuration: This module accepts connection configuration details either as
parameters or as configuration settings in /etc/salt/minion on the relevant
minions:
.. code-block:: yaml
elasticsearch:
host: '10.10.10.100:9200'
elasticsearch-cluster:
hosts:
- '10.10.10.100:9200'
- '10.10.10.101:9200'
- '10.10.10.102:9200'
elasticsearch-extra:
hosts:
- '10.10.10.100:9200'
use_ssl: True
verify_certs: True
ca_certs: /path/to/custom_ca_bundle.pem
number_of_shards: 1
number_of_replicas: 0
functions_blacklist:
- 'saltutil.find_job'
- 'pillar.items'
- 'grains.items'
proxies:
- http: http://proxy:3128
- https: http://proxy:1080
When specifying proxies the requests backend will be used and the 'proxies'
data structure is passed as-is to that module.
This data can also be passed into pillar. Options passed into opts will
overwrite options passed into pillar.
Some functionality might be limited by elasticsearch-py and Elasticsearch server versions.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
# Import third party libs
try:
import elasticsearch
from elasticsearch import RequestsHttpConnection
logging.getLogger('elasticsearch').setLevel(logging.CRITICAL)
HAS_ELASTICSEARCH = True
except ImportError:
HAS_ELASTICSEARCH = False
def __virtual__():
'''
Only load if elasticsearch libraries exist.
'''
if not HAS_ELASTICSEARCH:
return (False, 'Cannot load module elasticsearch: elasticsearch libraries not found')
return True
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 document_get(index, id, doc_type='_all', hosts=None, profile=None):
'''
Check for the existence of a document and if it exists, return it
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_get testindex AUx-384m0Bug_8U80wQZ
'''
es = _get_instance(hosts, profile)
try:
return es.get(index=index, id=id, doc_type=doc_type)
except elasticsearch.exceptions.NotFoundError:
return None
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 index_close(index, allow_no_indices=True, expand_wildcards='open', ignore_unavailable=True, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Close specified index.
index
Index to be closed
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 ‘open’, 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_close testindex
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.close(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 close 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 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_restore(repository, snapshot, body=None, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Restore existing snapshot in specified repository by supplied definition.
repository
Repository name
snapshot
Snapshot name
body
Restore definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
CLI example::
salt myminion elasticsearch.snapshot_restore testrepo testsnapshot '{"indices":"index_1,index_2","ignore_unavailable":true,"include_global_state":true}'
'''
es = _get_instance(hosts, profile)
try:
response = es.snapshot.restore(repository=repository, snapshot=snapshot, body=body)
return response.get('accepted', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot restore 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))
|
saltstack/salt | salt/modules/elasticsearch.py | repository_get | python | 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)) | .. 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 | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L990-L1012 | [
"def _get_instance(hosts=None, profile=None):\n '''\n Return the elasticsearch instance\n '''\n es = None\n proxies = None\n use_ssl = False\n ca_certs = None\n verify_certs = True\n http_auth = None\n timeout = 10\n\n if profile is None:\n profile = 'elasticsearch'\n\n if isinstance(profile, six.string_types):\n _profile = __salt__['config.option'](profile, None)\n elif isinstance(profile, dict):\n _profile = profile\n if _profile:\n hosts = _profile.get('host', hosts)\n if not hosts:\n hosts = _profile.get('hosts', hosts)\n proxies = _profile.get('proxies', None)\n use_ssl = _profile.get('use_ssl', False)\n ca_certs = _profile.get('ca_certs', None)\n verify_certs = _profile.get('verify_certs', True)\n username = _profile.get('username', None)\n password = _profile.get('password', None)\n timeout = _profile.get('timeout', 10)\n\n if username and password:\n http_auth = (username, password)\n\n if not hosts:\n hosts = ['127.0.0.1:9200']\n if isinstance(hosts, six.string_types):\n hosts = [hosts]\n try:\n if proxies:\n # Custom connection class to use requests module with proxies\n class ProxyConnection(RequestsHttpConnection):\n def __init__(self, *args, **kwargs):\n proxies = kwargs.pop('proxies', {})\n super(ProxyConnection, self).__init__(*args, **kwargs)\n self.session.proxies = proxies\n\n es = elasticsearch.Elasticsearch(\n hosts,\n connection_class=ProxyConnection,\n proxies=proxies,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n else:\n es = elasticsearch.Elasticsearch(\n hosts,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n\n # Try the connection\n es.info()\n except elasticsearch.exceptions.TransportError as err:\n raise CommandExecutionError(\n 'Could not connect to Elasticsearch host/ cluster {0} due to {1}'.format(hosts, err))\n return es\n"
] | # -*- coding: utf-8 -*-
'''
Elasticsearch - A distributed RESTful search and analytics server
Module to provide Elasticsearch compatibility to Salt
(compatible with Elasticsearch version 1.5.2+)
.. versionadded:: 2015.8.0
:depends: `elasticsearch-py <http://elasticsearch-py.readthedocs.org/en/latest/>`_
:configuration: This module accepts connection configuration details either as
parameters or as configuration settings in /etc/salt/minion on the relevant
minions:
.. code-block:: yaml
elasticsearch:
host: '10.10.10.100:9200'
elasticsearch-cluster:
hosts:
- '10.10.10.100:9200'
- '10.10.10.101:9200'
- '10.10.10.102:9200'
elasticsearch-extra:
hosts:
- '10.10.10.100:9200'
use_ssl: True
verify_certs: True
ca_certs: /path/to/custom_ca_bundle.pem
number_of_shards: 1
number_of_replicas: 0
functions_blacklist:
- 'saltutil.find_job'
- 'pillar.items'
- 'grains.items'
proxies:
- http: http://proxy:3128
- https: http://proxy:1080
When specifying proxies the requests backend will be used and the 'proxies'
data structure is passed as-is to that module.
This data can also be passed into pillar. Options passed into opts will
overwrite options passed into pillar.
Some functionality might be limited by elasticsearch-py and Elasticsearch server versions.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
# Import third party libs
try:
import elasticsearch
from elasticsearch import RequestsHttpConnection
logging.getLogger('elasticsearch').setLevel(logging.CRITICAL)
HAS_ELASTICSEARCH = True
except ImportError:
HAS_ELASTICSEARCH = False
def __virtual__():
'''
Only load if elasticsearch libraries exist.
'''
if not HAS_ELASTICSEARCH:
return (False, 'Cannot load module elasticsearch: elasticsearch libraries not found')
return True
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 document_get(index, id, doc_type='_all', hosts=None, profile=None):
'''
Check for the existence of a document and if it exists, return it
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_get testindex AUx-384m0Bug_8U80wQZ
'''
es = _get_instance(hosts, profile)
try:
return es.get(index=index, id=id, doc_type=doc_type)
except elasticsearch.exceptions.NotFoundError:
return None
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 index_close(index, allow_no_indices=True, expand_wildcards='open', ignore_unavailable=True, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Close specified index.
index
Index to be closed
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 ‘open’, 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_close testindex
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.close(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 close 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_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_restore(repository, snapshot, body=None, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Restore existing snapshot in specified repository by supplied definition.
repository
Repository name
snapshot
Snapshot name
body
Restore definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
CLI example::
salt myminion elasticsearch.snapshot_restore testrepo testsnapshot '{"indices":"index_1,index_2","ignore_unavailable":true,"include_global_state":true}'
'''
es = _get_instance(hosts, profile)
try:
response = es.snapshot.restore(repository=repository, snapshot=snapshot, body=body)
return response.get('accepted', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot restore 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))
|
saltstack/salt | salt/modules/elasticsearch.py | repository_create | python | 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)) | .. 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}}' | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L1015-L1037 | [
"def _get_instance(hosts=None, profile=None):\n '''\n Return the elasticsearch instance\n '''\n es = None\n proxies = None\n use_ssl = False\n ca_certs = None\n verify_certs = True\n http_auth = None\n timeout = 10\n\n if profile is None:\n profile = 'elasticsearch'\n\n if isinstance(profile, six.string_types):\n _profile = __salt__['config.option'](profile, None)\n elif isinstance(profile, dict):\n _profile = profile\n if _profile:\n hosts = _profile.get('host', hosts)\n if not hosts:\n hosts = _profile.get('hosts', hosts)\n proxies = _profile.get('proxies', None)\n use_ssl = _profile.get('use_ssl', False)\n ca_certs = _profile.get('ca_certs', None)\n verify_certs = _profile.get('verify_certs', True)\n username = _profile.get('username', None)\n password = _profile.get('password', None)\n timeout = _profile.get('timeout', 10)\n\n if username and password:\n http_auth = (username, password)\n\n if not hosts:\n hosts = ['127.0.0.1:9200']\n if isinstance(hosts, six.string_types):\n hosts = [hosts]\n try:\n if proxies:\n # Custom connection class to use requests module with proxies\n class ProxyConnection(RequestsHttpConnection):\n def __init__(self, *args, **kwargs):\n proxies = kwargs.pop('proxies', {})\n super(ProxyConnection, self).__init__(*args, **kwargs)\n self.session.proxies = proxies\n\n es = elasticsearch.Elasticsearch(\n hosts,\n connection_class=ProxyConnection,\n proxies=proxies,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n else:\n es = elasticsearch.Elasticsearch(\n hosts,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n\n # Try the connection\n es.info()\n except elasticsearch.exceptions.TransportError as err:\n raise CommandExecutionError(\n 'Could not connect to Elasticsearch host/ cluster {0} due to {1}'.format(hosts, err))\n return es\n"
] | # -*- coding: utf-8 -*-
'''
Elasticsearch - A distributed RESTful search and analytics server
Module to provide Elasticsearch compatibility to Salt
(compatible with Elasticsearch version 1.5.2+)
.. versionadded:: 2015.8.0
:depends: `elasticsearch-py <http://elasticsearch-py.readthedocs.org/en/latest/>`_
:configuration: This module accepts connection configuration details either as
parameters or as configuration settings in /etc/salt/minion on the relevant
minions:
.. code-block:: yaml
elasticsearch:
host: '10.10.10.100:9200'
elasticsearch-cluster:
hosts:
- '10.10.10.100:9200'
- '10.10.10.101:9200'
- '10.10.10.102:9200'
elasticsearch-extra:
hosts:
- '10.10.10.100:9200'
use_ssl: True
verify_certs: True
ca_certs: /path/to/custom_ca_bundle.pem
number_of_shards: 1
number_of_replicas: 0
functions_blacklist:
- 'saltutil.find_job'
- 'pillar.items'
- 'grains.items'
proxies:
- http: http://proxy:3128
- https: http://proxy:1080
When specifying proxies the requests backend will be used and the 'proxies'
data structure is passed as-is to that module.
This data can also be passed into pillar. Options passed into opts will
overwrite options passed into pillar.
Some functionality might be limited by elasticsearch-py and Elasticsearch server versions.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
# Import third party libs
try:
import elasticsearch
from elasticsearch import RequestsHttpConnection
logging.getLogger('elasticsearch').setLevel(logging.CRITICAL)
HAS_ELASTICSEARCH = True
except ImportError:
HAS_ELASTICSEARCH = False
def __virtual__():
'''
Only load if elasticsearch libraries exist.
'''
if not HAS_ELASTICSEARCH:
return (False, 'Cannot load module elasticsearch: elasticsearch libraries not found')
return True
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 document_get(index, id, doc_type='_all', hosts=None, profile=None):
'''
Check for the existence of a document and if it exists, return it
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_get testindex AUx-384m0Bug_8U80wQZ
'''
es = _get_instance(hosts, profile)
try:
return es.get(index=index, id=id, doc_type=doc_type)
except elasticsearch.exceptions.NotFoundError:
return None
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 index_close(index, allow_no_indices=True, expand_wildcards='open', ignore_unavailable=True, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Close specified index.
index
Index to be closed
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 ‘open’, 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_close testindex
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.close(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 close 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_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_restore(repository, snapshot, body=None, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Restore existing snapshot in specified repository by supplied definition.
repository
Repository name
snapshot
Snapshot name
body
Restore definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
CLI example::
salt myminion elasticsearch.snapshot_restore testrepo testsnapshot '{"indices":"index_1,index_2","ignore_unavailable":true,"include_global_state":true}'
'''
es = _get_instance(hosts, profile)
try:
response = es.snapshot.restore(repository=repository, snapshot=snapshot, body=body)
return response.get('accepted', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot restore 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))
|
saltstack/salt | salt/modules/elasticsearch.py | repository_delete | python | 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)) | .. versionadded:: 2017.7.0
Delete existing repository.
name
Repository name
CLI example::
salt myminion elasticsearch.repository_delete testrepo | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L1040-L1062 | [
"def _get_instance(hosts=None, profile=None):\n '''\n Return the elasticsearch instance\n '''\n es = None\n proxies = None\n use_ssl = False\n ca_certs = None\n verify_certs = True\n http_auth = None\n timeout = 10\n\n if profile is None:\n profile = 'elasticsearch'\n\n if isinstance(profile, six.string_types):\n _profile = __salt__['config.option'](profile, None)\n elif isinstance(profile, dict):\n _profile = profile\n if _profile:\n hosts = _profile.get('host', hosts)\n if not hosts:\n hosts = _profile.get('hosts', hosts)\n proxies = _profile.get('proxies', None)\n use_ssl = _profile.get('use_ssl', False)\n ca_certs = _profile.get('ca_certs', None)\n verify_certs = _profile.get('verify_certs', True)\n username = _profile.get('username', None)\n password = _profile.get('password', None)\n timeout = _profile.get('timeout', 10)\n\n if username and password:\n http_auth = (username, password)\n\n if not hosts:\n hosts = ['127.0.0.1:9200']\n if isinstance(hosts, six.string_types):\n hosts = [hosts]\n try:\n if proxies:\n # Custom connection class to use requests module with proxies\n class ProxyConnection(RequestsHttpConnection):\n def __init__(self, *args, **kwargs):\n proxies = kwargs.pop('proxies', {})\n super(ProxyConnection, self).__init__(*args, **kwargs)\n self.session.proxies = proxies\n\n es = elasticsearch.Elasticsearch(\n hosts,\n connection_class=ProxyConnection,\n proxies=proxies,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n else:\n es = elasticsearch.Elasticsearch(\n hosts,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n\n # Try the connection\n es.info()\n except elasticsearch.exceptions.TransportError as err:\n raise CommandExecutionError(\n 'Could not connect to Elasticsearch host/ cluster {0} due to {1}'.format(hosts, err))\n return es\n"
] | # -*- coding: utf-8 -*-
'''
Elasticsearch - A distributed RESTful search and analytics server
Module to provide Elasticsearch compatibility to Salt
(compatible with Elasticsearch version 1.5.2+)
.. versionadded:: 2015.8.0
:depends: `elasticsearch-py <http://elasticsearch-py.readthedocs.org/en/latest/>`_
:configuration: This module accepts connection configuration details either as
parameters or as configuration settings in /etc/salt/minion on the relevant
minions:
.. code-block:: yaml
elasticsearch:
host: '10.10.10.100:9200'
elasticsearch-cluster:
hosts:
- '10.10.10.100:9200'
- '10.10.10.101:9200'
- '10.10.10.102:9200'
elasticsearch-extra:
hosts:
- '10.10.10.100:9200'
use_ssl: True
verify_certs: True
ca_certs: /path/to/custom_ca_bundle.pem
number_of_shards: 1
number_of_replicas: 0
functions_blacklist:
- 'saltutil.find_job'
- 'pillar.items'
- 'grains.items'
proxies:
- http: http://proxy:3128
- https: http://proxy:1080
When specifying proxies the requests backend will be used and the 'proxies'
data structure is passed as-is to that module.
This data can also be passed into pillar. Options passed into opts will
overwrite options passed into pillar.
Some functionality might be limited by elasticsearch-py and Elasticsearch server versions.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
# Import third party libs
try:
import elasticsearch
from elasticsearch import RequestsHttpConnection
logging.getLogger('elasticsearch').setLevel(logging.CRITICAL)
HAS_ELASTICSEARCH = True
except ImportError:
HAS_ELASTICSEARCH = False
def __virtual__():
'''
Only load if elasticsearch libraries exist.
'''
if not HAS_ELASTICSEARCH:
return (False, 'Cannot load module elasticsearch: elasticsearch libraries not found')
return True
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 document_get(index, id, doc_type='_all', hosts=None, profile=None):
'''
Check for the existence of a document and if it exists, return it
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_get testindex AUx-384m0Bug_8U80wQZ
'''
es = _get_instance(hosts, profile)
try:
return es.get(index=index, id=id, doc_type=doc_type)
except elasticsearch.exceptions.NotFoundError:
return None
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 index_close(index, allow_no_indices=True, expand_wildcards='open', ignore_unavailable=True, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Close specified index.
index
Index to be closed
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 ‘open’, 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_close testindex
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.close(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 close 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_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_restore(repository, snapshot, body=None, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Restore existing snapshot in specified repository by supplied definition.
repository
Repository name
snapshot
Snapshot name
body
Restore definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
CLI example::
salt myminion elasticsearch.snapshot_restore testrepo testsnapshot '{"indices":"index_1,index_2","ignore_unavailable":true,"include_global_state":true}'
'''
es = _get_instance(hosts, profile)
try:
response = es.snapshot.restore(repository=repository, snapshot=snapshot, body=body)
return response.get('accepted', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot restore 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))
|
saltstack/salt | salt/modules/elasticsearch.py | repository_verify | python | 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)) | .. 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 | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L1065-L1085 | [
"def _get_instance(hosts=None, profile=None):\n '''\n Return the elasticsearch instance\n '''\n es = None\n proxies = None\n use_ssl = False\n ca_certs = None\n verify_certs = True\n http_auth = None\n timeout = 10\n\n if profile is None:\n profile = 'elasticsearch'\n\n if isinstance(profile, six.string_types):\n _profile = __salt__['config.option'](profile, None)\n elif isinstance(profile, dict):\n _profile = profile\n if _profile:\n hosts = _profile.get('host', hosts)\n if not hosts:\n hosts = _profile.get('hosts', hosts)\n proxies = _profile.get('proxies', None)\n use_ssl = _profile.get('use_ssl', False)\n ca_certs = _profile.get('ca_certs', None)\n verify_certs = _profile.get('verify_certs', True)\n username = _profile.get('username', None)\n password = _profile.get('password', None)\n timeout = _profile.get('timeout', 10)\n\n if username and password:\n http_auth = (username, password)\n\n if not hosts:\n hosts = ['127.0.0.1:9200']\n if isinstance(hosts, six.string_types):\n hosts = [hosts]\n try:\n if proxies:\n # Custom connection class to use requests module with proxies\n class ProxyConnection(RequestsHttpConnection):\n def __init__(self, *args, **kwargs):\n proxies = kwargs.pop('proxies', {})\n super(ProxyConnection, self).__init__(*args, **kwargs)\n self.session.proxies = proxies\n\n es = elasticsearch.Elasticsearch(\n hosts,\n connection_class=ProxyConnection,\n proxies=proxies,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n else:\n es = elasticsearch.Elasticsearch(\n hosts,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n\n # Try the connection\n es.info()\n except elasticsearch.exceptions.TransportError as err:\n raise CommandExecutionError(\n 'Could not connect to Elasticsearch host/ cluster {0} due to {1}'.format(hosts, err))\n return es\n"
] | # -*- coding: utf-8 -*-
'''
Elasticsearch - A distributed RESTful search and analytics server
Module to provide Elasticsearch compatibility to Salt
(compatible with Elasticsearch version 1.5.2+)
.. versionadded:: 2015.8.0
:depends: `elasticsearch-py <http://elasticsearch-py.readthedocs.org/en/latest/>`_
:configuration: This module accepts connection configuration details either as
parameters or as configuration settings in /etc/salt/minion on the relevant
minions:
.. code-block:: yaml
elasticsearch:
host: '10.10.10.100:9200'
elasticsearch-cluster:
hosts:
- '10.10.10.100:9200'
- '10.10.10.101:9200'
- '10.10.10.102:9200'
elasticsearch-extra:
hosts:
- '10.10.10.100:9200'
use_ssl: True
verify_certs: True
ca_certs: /path/to/custom_ca_bundle.pem
number_of_shards: 1
number_of_replicas: 0
functions_blacklist:
- 'saltutil.find_job'
- 'pillar.items'
- 'grains.items'
proxies:
- http: http://proxy:3128
- https: http://proxy:1080
When specifying proxies the requests backend will be used and the 'proxies'
data structure is passed as-is to that module.
This data can also be passed into pillar. Options passed into opts will
overwrite options passed into pillar.
Some functionality might be limited by elasticsearch-py and Elasticsearch server versions.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
# Import third party libs
try:
import elasticsearch
from elasticsearch import RequestsHttpConnection
logging.getLogger('elasticsearch').setLevel(logging.CRITICAL)
HAS_ELASTICSEARCH = True
except ImportError:
HAS_ELASTICSEARCH = False
def __virtual__():
'''
Only load if elasticsearch libraries exist.
'''
if not HAS_ELASTICSEARCH:
return (False, 'Cannot load module elasticsearch: elasticsearch libraries not found')
return True
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 document_get(index, id, doc_type='_all', hosts=None, profile=None):
'''
Check for the existence of a document and if it exists, return it
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_get testindex AUx-384m0Bug_8U80wQZ
'''
es = _get_instance(hosts, profile)
try:
return es.get(index=index, id=id, doc_type=doc_type)
except elasticsearch.exceptions.NotFoundError:
return None
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 index_close(index, allow_no_indices=True, expand_wildcards='open', ignore_unavailable=True, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Close specified index.
index
Index to be closed
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 ‘open’, 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_close testindex
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.close(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 close 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 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_restore(repository, snapshot, body=None, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Restore existing snapshot in specified repository by supplied definition.
repository
Repository name
snapshot
Snapshot name
body
Restore definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
CLI example::
salt myminion elasticsearch.snapshot_restore testrepo testsnapshot '{"indices":"index_1,index_2","ignore_unavailable":true,"include_global_state":true}'
'''
es = _get_instance(hosts, profile)
try:
response = es.snapshot.restore(repository=repository, snapshot=snapshot, body=body)
return response.get('accepted', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot restore 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))
|
saltstack/salt | salt/modules/elasticsearch.py | snapshot_status | python | 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)) | .. 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 | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L1088-L1110 | [
"def _get_instance(hosts=None, profile=None):\n '''\n Return the elasticsearch instance\n '''\n es = None\n proxies = None\n use_ssl = False\n ca_certs = None\n verify_certs = True\n http_auth = None\n timeout = 10\n\n if profile is None:\n profile = 'elasticsearch'\n\n if isinstance(profile, six.string_types):\n _profile = __salt__['config.option'](profile, None)\n elif isinstance(profile, dict):\n _profile = profile\n if _profile:\n hosts = _profile.get('host', hosts)\n if not hosts:\n hosts = _profile.get('hosts', hosts)\n proxies = _profile.get('proxies', None)\n use_ssl = _profile.get('use_ssl', False)\n ca_certs = _profile.get('ca_certs', None)\n verify_certs = _profile.get('verify_certs', True)\n username = _profile.get('username', None)\n password = _profile.get('password', None)\n timeout = _profile.get('timeout', 10)\n\n if username and password:\n http_auth = (username, password)\n\n if not hosts:\n hosts = ['127.0.0.1:9200']\n if isinstance(hosts, six.string_types):\n hosts = [hosts]\n try:\n if proxies:\n # Custom connection class to use requests module with proxies\n class ProxyConnection(RequestsHttpConnection):\n def __init__(self, *args, **kwargs):\n proxies = kwargs.pop('proxies', {})\n super(ProxyConnection, self).__init__(*args, **kwargs)\n self.session.proxies = proxies\n\n es = elasticsearch.Elasticsearch(\n hosts,\n connection_class=ProxyConnection,\n proxies=proxies,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n else:\n es = elasticsearch.Elasticsearch(\n hosts,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n\n # Try the connection\n es.info()\n except elasticsearch.exceptions.TransportError as err:\n raise CommandExecutionError(\n 'Could not connect to Elasticsearch host/ cluster {0} due to {1}'.format(hosts, err))\n return es\n"
] | # -*- coding: utf-8 -*-
'''
Elasticsearch - A distributed RESTful search and analytics server
Module to provide Elasticsearch compatibility to Salt
(compatible with Elasticsearch version 1.5.2+)
.. versionadded:: 2015.8.0
:depends: `elasticsearch-py <http://elasticsearch-py.readthedocs.org/en/latest/>`_
:configuration: This module accepts connection configuration details either as
parameters or as configuration settings in /etc/salt/minion on the relevant
minions:
.. code-block:: yaml
elasticsearch:
host: '10.10.10.100:9200'
elasticsearch-cluster:
hosts:
- '10.10.10.100:9200'
- '10.10.10.101:9200'
- '10.10.10.102:9200'
elasticsearch-extra:
hosts:
- '10.10.10.100:9200'
use_ssl: True
verify_certs: True
ca_certs: /path/to/custom_ca_bundle.pem
number_of_shards: 1
number_of_replicas: 0
functions_blacklist:
- 'saltutil.find_job'
- 'pillar.items'
- 'grains.items'
proxies:
- http: http://proxy:3128
- https: http://proxy:1080
When specifying proxies the requests backend will be used and the 'proxies'
data structure is passed as-is to that module.
This data can also be passed into pillar. Options passed into opts will
overwrite options passed into pillar.
Some functionality might be limited by elasticsearch-py and Elasticsearch server versions.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
# Import third party libs
try:
import elasticsearch
from elasticsearch import RequestsHttpConnection
logging.getLogger('elasticsearch').setLevel(logging.CRITICAL)
HAS_ELASTICSEARCH = True
except ImportError:
HAS_ELASTICSEARCH = False
def __virtual__():
'''
Only load if elasticsearch libraries exist.
'''
if not HAS_ELASTICSEARCH:
return (False, 'Cannot load module elasticsearch: elasticsearch libraries not found')
return True
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 document_get(index, id, doc_type='_all', hosts=None, profile=None):
'''
Check for the existence of a document and if it exists, return it
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_get testindex AUx-384m0Bug_8U80wQZ
'''
es = _get_instance(hosts, profile)
try:
return es.get(index=index, id=id, doc_type=doc_type)
except elasticsearch.exceptions.NotFoundError:
return None
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 index_close(index, allow_no_indices=True, expand_wildcards='open', ignore_unavailable=True, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Close specified index.
index
Index to be closed
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 ‘open’, 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_close testindex
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.close(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 close 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_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_restore(repository, snapshot, body=None, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Restore existing snapshot in specified repository by supplied definition.
repository
Repository name
snapshot
Snapshot name
body
Restore definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
CLI example::
salt myminion elasticsearch.snapshot_restore testrepo testsnapshot '{"indices":"index_1,index_2","ignore_unavailable":true,"include_global_state":true}'
'''
es = _get_instance(hosts, profile)
try:
response = es.snapshot.restore(repository=repository, snapshot=snapshot, body=body)
return response.get('accepted', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot restore 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))
|
saltstack/salt | salt/modules/elasticsearch.py | snapshot_get | python | 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)) | .. 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 | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L1113-L1135 | [
"def _get_instance(hosts=None, profile=None):\n '''\n Return the elasticsearch instance\n '''\n es = None\n proxies = None\n use_ssl = False\n ca_certs = None\n verify_certs = True\n http_auth = None\n timeout = 10\n\n if profile is None:\n profile = 'elasticsearch'\n\n if isinstance(profile, six.string_types):\n _profile = __salt__['config.option'](profile, None)\n elif isinstance(profile, dict):\n _profile = profile\n if _profile:\n hosts = _profile.get('host', hosts)\n if not hosts:\n hosts = _profile.get('hosts', hosts)\n proxies = _profile.get('proxies', None)\n use_ssl = _profile.get('use_ssl', False)\n ca_certs = _profile.get('ca_certs', None)\n verify_certs = _profile.get('verify_certs', True)\n username = _profile.get('username', None)\n password = _profile.get('password', None)\n timeout = _profile.get('timeout', 10)\n\n if username and password:\n http_auth = (username, password)\n\n if not hosts:\n hosts = ['127.0.0.1:9200']\n if isinstance(hosts, six.string_types):\n hosts = [hosts]\n try:\n if proxies:\n # Custom connection class to use requests module with proxies\n class ProxyConnection(RequestsHttpConnection):\n def __init__(self, *args, **kwargs):\n proxies = kwargs.pop('proxies', {})\n super(ProxyConnection, self).__init__(*args, **kwargs)\n self.session.proxies = proxies\n\n es = elasticsearch.Elasticsearch(\n hosts,\n connection_class=ProxyConnection,\n proxies=proxies,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n else:\n es = elasticsearch.Elasticsearch(\n hosts,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n\n # Try the connection\n es.info()\n except elasticsearch.exceptions.TransportError as err:\n raise CommandExecutionError(\n 'Could not connect to Elasticsearch host/ cluster {0} due to {1}'.format(hosts, err))\n return es\n"
] | # -*- coding: utf-8 -*-
'''
Elasticsearch - A distributed RESTful search and analytics server
Module to provide Elasticsearch compatibility to Salt
(compatible with Elasticsearch version 1.5.2+)
.. versionadded:: 2015.8.0
:depends: `elasticsearch-py <http://elasticsearch-py.readthedocs.org/en/latest/>`_
:configuration: This module accepts connection configuration details either as
parameters or as configuration settings in /etc/salt/minion on the relevant
minions:
.. code-block:: yaml
elasticsearch:
host: '10.10.10.100:9200'
elasticsearch-cluster:
hosts:
- '10.10.10.100:9200'
- '10.10.10.101:9200'
- '10.10.10.102:9200'
elasticsearch-extra:
hosts:
- '10.10.10.100:9200'
use_ssl: True
verify_certs: True
ca_certs: /path/to/custom_ca_bundle.pem
number_of_shards: 1
number_of_replicas: 0
functions_blacklist:
- 'saltutil.find_job'
- 'pillar.items'
- 'grains.items'
proxies:
- http: http://proxy:3128
- https: http://proxy:1080
When specifying proxies the requests backend will be used and the 'proxies'
data structure is passed as-is to that module.
This data can also be passed into pillar. Options passed into opts will
overwrite options passed into pillar.
Some functionality might be limited by elasticsearch-py and Elasticsearch server versions.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
# Import third party libs
try:
import elasticsearch
from elasticsearch import RequestsHttpConnection
logging.getLogger('elasticsearch').setLevel(logging.CRITICAL)
HAS_ELASTICSEARCH = True
except ImportError:
HAS_ELASTICSEARCH = False
def __virtual__():
'''
Only load if elasticsearch libraries exist.
'''
if not HAS_ELASTICSEARCH:
return (False, 'Cannot load module elasticsearch: elasticsearch libraries not found')
return True
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 document_get(index, id, doc_type='_all', hosts=None, profile=None):
'''
Check for the existence of a document and if it exists, return it
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_get testindex AUx-384m0Bug_8U80wQZ
'''
es = _get_instance(hosts, profile)
try:
return es.get(index=index, id=id, doc_type=doc_type)
except elasticsearch.exceptions.NotFoundError:
return None
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 index_close(index, allow_no_indices=True, expand_wildcards='open', ignore_unavailable=True, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Close specified index.
index
Index to be closed
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 ‘open’, 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_close testindex
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.close(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 close 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_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_restore(repository, snapshot, body=None, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Restore existing snapshot in specified repository by supplied definition.
repository
Repository name
snapshot
Snapshot name
body
Restore definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
CLI example::
salt myminion elasticsearch.snapshot_restore testrepo testsnapshot '{"indices":"index_1,index_2","ignore_unavailable":true,"include_global_state":true}'
'''
es = _get_instance(hosts, profile)
try:
response = es.snapshot.restore(repository=repository, snapshot=snapshot, body=body)
return response.get('accepted', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot restore 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))
|
saltstack/salt | salt/modules/elasticsearch.py | snapshot_create | python | 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)) | .. 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}' | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L1138-L1162 | [
"def _get_instance(hosts=None, profile=None):\n '''\n Return the elasticsearch instance\n '''\n es = None\n proxies = None\n use_ssl = False\n ca_certs = None\n verify_certs = True\n http_auth = None\n timeout = 10\n\n if profile is None:\n profile = 'elasticsearch'\n\n if isinstance(profile, six.string_types):\n _profile = __salt__['config.option'](profile, None)\n elif isinstance(profile, dict):\n _profile = profile\n if _profile:\n hosts = _profile.get('host', hosts)\n if not hosts:\n hosts = _profile.get('hosts', hosts)\n proxies = _profile.get('proxies', None)\n use_ssl = _profile.get('use_ssl', False)\n ca_certs = _profile.get('ca_certs', None)\n verify_certs = _profile.get('verify_certs', True)\n username = _profile.get('username', None)\n password = _profile.get('password', None)\n timeout = _profile.get('timeout', 10)\n\n if username and password:\n http_auth = (username, password)\n\n if not hosts:\n hosts = ['127.0.0.1:9200']\n if isinstance(hosts, six.string_types):\n hosts = [hosts]\n try:\n if proxies:\n # Custom connection class to use requests module with proxies\n class ProxyConnection(RequestsHttpConnection):\n def __init__(self, *args, **kwargs):\n proxies = kwargs.pop('proxies', {})\n super(ProxyConnection, self).__init__(*args, **kwargs)\n self.session.proxies = proxies\n\n es = elasticsearch.Elasticsearch(\n hosts,\n connection_class=ProxyConnection,\n proxies=proxies,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n else:\n es = elasticsearch.Elasticsearch(\n hosts,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n\n # Try the connection\n es.info()\n except elasticsearch.exceptions.TransportError as err:\n raise CommandExecutionError(\n 'Could not connect to Elasticsearch host/ cluster {0} due to {1}'.format(hosts, err))\n return es\n"
] | # -*- coding: utf-8 -*-
'''
Elasticsearch - A distributed RESTful search and analytics server
Module to provide Elasticsearch compatibility to Salt
(compatible with Elasticsearch version 1.5.2+)
.. versionadded:: 2015.8.0
:depends: `elasticsearch-py <http://elasticsearch-py.readthedocs.org/en/latest/>`_
:configuration: This module accepts connection configuration details either as
parameters or as configuration settings in /etc/salt/minion on the relevant
minions:
.. code-block:: yaml
elasticsearch:
host: '10.10.10.100:9200'
elasticsearch-cluster:
hosts:
- '10.10.10.100:9200'
- '10.10.10.101:9200'
- '10.10.10.102:9200'
elasticsearch-extra:
hosts:
- '10.10.10.100:9200'
use_ssl: True
verify_certs: True
ca_certs: /path/to/custom_ca_bundle.pem
number_of_shards: 1
number_of_replicas: 0
functions_blacklist:
- 'saltutil.find_job'
- 'pillar.items'
- 'grains.items'
proxies:
- http: http://proxy:3128
- https: http://proxy:1080
When specifying proxies the requests backend will be used and the 'proxies'
data structure is passed as-is to that module.
This data can also be passed into pillar. Options passed into opts will
overwrite options passed into pillar.
Some functionality might be limited by elasticsearch-py and Elasticsearch server versions.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
# Import third party libs
try:
import elasticsearch
from elasticsearch import RequestsHttpConnection
logging.getLogger('elasticsearch').setLevel(logging.CRITICAL)
HAS_ELASTICSEARCH = True
except ImportError:
HAS_ELASTICSEARCH = False
def __virtual__():
'''
Only load if elasticsearch libraries exist.
'''
if not HAS_ELASTICSEARCH:
return (False, 'Cannot load module elasticsearch: elasticsearch libraries not found')
return True
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 document_get(index, id, doc_type='_all', hosts=None, profile=None):
'''
Check for the existence of a document and if it exists, return it
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_get testindex AUx-384m0Bug_8U80wQZ
'''
es = _get_instance(hosts, profile)
try:
return es.get(index=index, id=id, doc_type=doc_type)
except elasticsearch.exceptions.NotFoundError:
return None
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 index_close(index, allow_no_indices=True, expand_wildcards='open', ignore_unavailable=True, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Close specified index.
index
Index to be closed
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 ‘open’, 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_close testindex
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.close(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 close 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_restore(repository, snapshot, body=None, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Restore existing snapshot in specified repository by supplied definition.
repository
Repository name
snapshot
Snapshot name
body
Restore definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
CLI example::
salt myminion elasticsearch.snapshot_restore testrepo testsnapshot '{"indices":"index_1,index_2","ignore_unavailable":true,"include_global_state":true}'
'''
es = _get_instance(hosts, profile)
try:
response = es.snapshot.restore(repository=repository, snapshot=snapshot, body=body)
return response.get('accepted', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot restore 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))
|
saltstack/salt | salt/modules/elasticsearch.py | snapshot_delete | python | 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)) | .. versionadded:: 2017.7.0
Delete snapshot from specified repository.
repository
Repository name
snapshot
Snapshot name
CLI example::
salt myminion elasticsearch.snapshot_delete testrepo testsnapshot | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L1192-L1216 | [
"def _get_instance(hosts=None, profile=None):\n '''\n Return the elasticsearch instance\n '''\n es = None\n proxies = None\n use_ssl = False\n ca_certs = None\n verify_certs = True\n http_auth = None\n timeout = 10\n\n if profile is None:\n profile = 'elasticsearch'\n\n if isinstance(profile, six.string_types):\n _profile = __salt__['config.option'](profile, None)\n elif isinstance(profile, dict):\n _profile = profile\n if _profile:\n hosts = _profile.get('host', hosts)\n if not hosts:\n hosts = _profile.get('hosts', hosts)\n proxies = _profile.get('proxies', None)\n use_ssl = _profile.get('use_ssl', False)\n ca_certs = _profile.get('ca_certs', None)\n verify_certs = _profile.get('verify_certs', True)\n username = _profile.get('username', None)\n password = _profile.get('password', None)\n timeout = _profile.get('timeout', 10)\n\n if username and password:\n http_auth = (username, password)\n\n if not hosts:\n hosts = ['127.0.0.1:9200']\n if isinstance(hosts, six.string_types):\n hosts = [hosts]\n try:\n if proxies:\n # Custom connection class to use requests module with proxies\n class ProxyConnection(RequestsHttpConnection):\n def __init__(self, *args, **kwargs):\n proxies = kwargs.pop('proxies', {})\n super(ProxyConnection, self).__init__(*args, **kwargs)\n self.session.proxies = proxies\n\n es = elasticsearch.Elasticsearch(\n hosts,\n connection_class=ProxyConnection,\n proxies=proxies,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n else:\n es = elasticsearch.Elasticsearch(\n hosts,\n use_ssl=use_ssl,\n ca_certs=ca_certs,\n verify_certs=verify_certs,\n http_auth=http_auth,\n timeout=timeout,\n )\n\n # Try the connection\n es.info()\n except elasticsearch.exceptions.TransportError as err:\n raise CommandExecutionError(\n 'Could not connect to Elasticsearch host/ cluster {0} due to {1}'.format(hosts, err))\n return es\n"
] | # -*- coding: utf-8 -*-
'''
Elasticsearch - A distributed RESTful search and analytics server
Module to provide Elasticsearch compatibility to Salt
(compatible with Elasticsearch version 1.5.2+)
.. versionadded:: 2015.8.0
:depends: `elasticsearch-py <http://elasticsearch-py.readthedocs.org/en/latest/>`_
:configuration: This module accepts connection configuration details either as
parameters or as configuration settings in /etc/salt/minion on the relevant
minions:
.. code-block:: yaml
elasticsearch:
host: '10.10.10.100:9200'
elasticsearch-cluster:
hosts:
- '10.10.10.100:9200'
- '10.10.10.101:9200'
- '10.10.10.102:9200'
elasticsearch-extra:
hosts:
- '10.10.10.100:9200'
use_ssl: True
verify_certs: True
ca_certs: /path/to/custom_ca_bundle.pem
number_of_shards: 1
number_of_replicas: 0
functions_blacklist:
- 'saltutil.find_job'
- 'pillar.items'
- 'grains.items'
proxies:
- http: http://proxy:3128
- https: http://proxy:1080
When specifying proxies the requests backend will be used and the 'proxies'
data structure is passed as-is to that module.
This data can also be passed into pillar. Options passed into opts will
overwrite options passed into pillar.
Some functionality might be limited by elasticsearch-py and Elasticsearch server versions.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
# Import third party libs
try:
import elasticsearch
from elasticsearch import RequestsHttpConnection
logging.getLogger('elasticsearch').setLevel(logging.CRITICAL)
HAS_ELASTICSEARCH = True
except ImportError:
HAS_ELASTICSEARCH = False
def __virtual__():
'''
Only load if elasticsearch libraries exist.
'''
if not HAS_ELASTICSEARCH:
return (False, 'Cannot load module elasticsearch: elasticsearch libraries not found')
return True
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 document_get(index, id, doc_type='_all', hosts=None, profile=None):
'''
Check for the existence of a document and if it exists, return it
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_get testindex AUx-384m0Bug_8U80wQZ
'''
es = _get_instance(hosts, profile)
try:
return es.get(index=index, id=id, doc_type=doc_type)
except elasticsearch.exceptions.NotFoundError:
return None
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 index_close(index, allow_no_indices=True, expand_wildcards='open', ignore_unavailable=True, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Close specified index.
index
Index to be closed
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 ‘open’, 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_close testindex
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.close(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 close 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_restore(repository, snapshot, body=None, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Restore existing snapshot in specified repository by supplied definition.
repository
Repository name
snapshot
Snapshot name
body
Restore definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
CLI example::
salt myminion elasticsearch.snapshot_restore testrepo testsnapshot '{"indices":"index_1,index_2","ignore_unavailable":true,"include_global_state":true}'
'''
es = _get_instance(hosts, profile)
try:
response = es.snapshot.restore(repository=repository, snapshot=snapshot, body=body)
return response.get('accepted', False)
except elasticsearch.TransportError as e:
raise CommandExecutionError("Cannot restore snapshot {0} in repository {1}, server returned code {2} with message {3}".format(snapshot, repository, e.status_code, e.error))
|
saltstack/salt | salt/states/snap.py | installed | python | 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 | Ensure that the named snap package is installed
name
The snap package
channel
Optional. The channel to install the package from. | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/snap.py#L19-L86 | null | # -*- coding: utf-8 -*-
'''
Management of snap packages
===============================================
'''
from __future__ import absolute_import, print_function, unicode_literals
import salt.utils.path
__virtualname__ = 'snap'
def __virtual__():
if salt.utils.path.which('snap'):
return __virtualname__
return (False, 'The snap state module cannot be loaded: the "snap" binary is not in the path.')
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
|
saltstack/salt | salt/states/snap.py | removed | python | 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 | Ensure that the named snap package is not installed
name
The snap package | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/snap.py#L89-L121 | null | # -*- coding: utf-8 -*-
'''
Management of snap packages
===============================================
'''
from __future__ import absolute_import, print_function, unicode_literals
import salt.utils.path
__virtualname__ = 'snap'
def __virtual__():
if salt.utils.path.which('snap'):
return __virtualname__
return (False, 'The snap state module cannot be loaded: the "snap" binary is not in the path.')
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
|
saltstack/salt | salt/beacons/watchdog.py | _get_queue | python | 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'] | Check the context for the notifier and construct it if not present | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/watchdog.py#L80-L99 | null | # -*- coding: utf-8 -*-
'''
watchdog beacon
.. versionadded:: 2019.2.0
Watch files and translate the changes into salt events
:depends: - watchdog Python module >= 0.8.3
'''
# Import Python libs
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import collections
import logging
from salt.ext.six.moves import map
# Import third party libs
try:
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
HAS_WATCHDOG = True
except ImportError:
HAS_WATCHDOG = False
class FileSystemEventHandler(object):
""" A dummy class to make the import work """
def __init__(self):
pass
__virtualname__ = 'watchdog'
log = logging.getLogger(__name__)
DEFAULT_MASK = [
'create',
'delete',
'modify',
'move',
]
class Handler(FileSystemEventHandler):
def __init__(self, queue, masks=None):
super(Handler, self).__init__()
self.masks = masks or DEFAULT_MASK
self.queue = queue
def on_created(self, event):
self._append_if_mask(event, 'create')
def on_modified(self, event):
self._append_if_mask(event, 'modify')
def on_deleted(self, event):
self._append_if_mask(event, 'delete')
def on_moved(self, event):
self._append_if_mask(event, 'move')
def _append_if_mask(self, event, mask):
logging.debug(event)
self._append_path_if_mask(event, mask)
def _append_path_if_mask(self, event, mask):
if mask in self.masks:
self.queue.append(event)
def __virtual__():
if HAS_WATCHDOG:
return __virtualname__
return False
class ValidationError(Exception):
pass
def validate(config):
'''
Validate the beacon configuration
'''
try:
_validate(config)
return True, 'Valid beacon configuration'
except ValidationError as error:
return False, str(error)
def _validate(config):
if not isinstance(config, list):
raise ValidationError(
'Configuration for watchdog beacon must be a list.')
_config = {}
for part in config:
_config.update(part)
if 'directories' not in _config:
raise ValidationError(
'Configuration for watchdog beacon must include directories.')
if not isinstance(_config['directories'], dict):
raise ValidationError(
'Configuration for watchdog beacon directories must be a '
'dictionary.')
for path in _config['directories']:
_validate_path(_config['directories'][path])
def _validate_path(path_config):
if not isinstance(path_config, dict):
raise ValidationError(
'Configuration for watchdog beacon directory path must be '
'a dictionary.')
if 'mask' in path_config:
_validate_mask(path_config['mask'])
def _validate_mask(mask_config):
valid_mask = [
'create',
'modify',
'delete',
'move',
]
if not isinstance(mask_config, list):
raise ValidationError(
'Configuration for watchdog beacon mask must be list.')
if any(mask not in valid_mask for mask in mask_config):
raise ValidationError(
'Configuration for watchdog beacon contains invalid mask')
def to_salt_event(event):
return {
'tag': __virtualname__,
'path': event.src_path,
'change': event.event_type,
}
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 close(config):
observer = __context__.pop('watchdog.observer', None)
if observer:
observer.stop()
|
saltstack/salt | salt/beacons/watchdog.py | validate | python | def validate(config):
'''
Validate the beacon configuration
'''
try:
_validate(config)
return True, 'Valid beacon configuration'
except ValidationError as error:
return False, str(error) | Validate the beacon configuration | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/watchdog.py#L106-L115 | [
"def _validate(config):\n if not isinstance(config, list):\n raise ValidationError(\n 'Configuration for watchdog beacon must be a list.')\n\n _config = {}\n for part in config:\n _config.update(part)\n\n if 'directories' not in _config:\n raise ValidationError(\n 'Configuration for watchdog beacon must include directories.')\n\n if not isinstance(_config['directories'], dict):\n raise ValidationError(\n 'Configuration for watchdog beacon directories must be a '\n 'dictionary.')\n\n for path in _config['directories']:\n _validate_path(_config['directories'][path])\n"
] | # -*- coding: utf-8 -*-
'''
watchdog beacon
.. versionadded:: 2019.2.0
Watch files and translate the changes into salt events
:depends: - watchdog Python module >= 0.8.3
'''
# Import Python libs
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import collections
import logging
from salt.ext.six.moves import map
# Import third party libs
try:
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
HAS_WATCHDOG = True
except ImportError:
HAS_WATCHDOG = False
class FileSystemEventHandler(object):
""" A dummy class to make the import work """
def __init__(self):
pass
__virtualname__ = 'watchdog'
log = logging.getLogger(__name__)
DEFAULT_MASK = [
'create',
'delete',
'modify',
'move',
]
class Handler(FileSystemEventHandler):
def __init__(self, queue, masks=None):
super(Handler, self).__init__()
self.masks = masks or DEFAULT_MASK
self.queue = queue
def on_created(self, event):
self._append_if_mask(event, 'create')
def on_modified(self, event):
self._append_if_mask(event, 'modify')
def on_deleted(self, event):
self._append_if_mask(event, 'delete')
def on_moved(self, event):
self._append_if_mask(event, 'move')
def _append_if_mask(self, event, mask):
logging.debug(event)
self._append_path_if_mask(event, mask)
def _append_path_if_mask(self, event, mask):
if mask in self.masks:
self.queue.append(event)
def __virtual__():
if HAS_WATCHDOG:
return __virtualname__
return False
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']
class ValidationError(Exception):
pass
def _validate(config):
if not isinstance(config, list):
raise ValidationError(
'Configuration for watchdog beacon must be a list.')
_config = {}
for part in config:
_config.update(part)
if 'directories' not in _config:
raise ValidationError(
'Configuration for watchdog beacon must include directories.')
if not isinstance(_config['directories'], dict):
raise ValidationError(
'Configuration for watchdog beacon directories must be a '
'dictionary.')
for path in _config['directories']:
_validate_path(_config['directories'][path])
def _validate_path(path_config):
if not isinstance(path_config, dict):
raise ValidationError(
'Configuration for watchdog beacon directory path must be '
'a dictionary.')
if 'mask' in path_config:
_validate_mask(path_config['mask'])
def _validate_mask(mask_config):
valid_mask = [
'create',
'modify',
'delete',
'move',
]
if not isinstance(mask_config, list):
raise ValidationError(
'Configuration for watchdog beacon mask must be list.')
if any(mask not in valid_mask for mask in mask_config):
raise ValidationError(
'Configuration for watchdog beacon contains invalid mask')
def to_salt_event(event):
return {
'tag': __virtualname__,
'path': event.src_path,
'change': event.event_type,
}
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 close(config):
observer = __context__.pop('watchdog.observer', None)
if observer:
observer.stop()
|
saltstack/salt | salt/beacons/watchdog.py | beacon | python | 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 | 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 | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/watchdog.py#L175-L210 | [
"def _get_queue(config):\n '''\n Check the context for the notifier and construct it if not present\n '''\n\n if 'watchdog.observer' not in __context__:\n queue = collections.deque()\n observer = Observer()\n for path in config.get('directories', {}):\n path_params = config.get('directories').get(path)\n masks = path_params.get('mask', DEFAULT_MASK)\n event_handler = Handler(queue, masks)\n observer.schedule(event_handler, path)\n\n observer.start()\n\n __context__['watchdog.observer'] = observer\n __context__['watchdog.queue'] = queue\n\n return __context__['watchdog.queue']\n",
"def to_salt_event(event):\n return {\n 'tag': __virtualname__,\n 'path': event.src_path,\n 'change': event.event_type,\n }\n"
] | # -*- coding: utf-8 -*-
'''
watchdog beacon
.. versionadded:: 2019.2.0
Watch files and translate the changes into salt events
:depends: - watchdog Python module >= 0.8.3
'''
# Import Python libs
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import collections
import logging
from salt.ext.six.moves import map
# Import third party libs
try:
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
HAS_WATCHDOG = True
except ImportError:
HAS_WATCHDOG = False
class FileSystemEventHandler(object):
""" A dummy class to make the import work """
def __init__(self):
pass
__virtualname__ = 'watchdog'
log = logging.getLogger(__name__)
DEFAULT_MASK = [
'create',
'delete',
'modify',
'move',
]
class Handler(FileSystemEventHandler):
def __init__(self, queue, masks=None):
super(Handler, self).__init__()
self.masks = masks or DEFAULT_MASK
self.queue = queue
def on_created(self, event):
self._append_if_mask(event, 'create')
def on_modified(self, event):
self._append_if_mask(event, 'modify')
def on_deleted(self, event):
self._append_if_mask(event, 'delete')
def on_moved(self, event):
self._append_if_mask(event, 'move')
def _append_if_mask(self, event, mask):
logging.debug(event)
self._append_path_if_mask(event, mask)
def _append_path_if_mask(self, event, mask):
if mask in self.masks:
self.queue.append(event)
def __virtual__():
if HAS_WATCHDOG:
return __virtualname__
return False
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']
class ValidationError(Exception):
pass
def validate(config):
'''
Validate the beacon configuration
'''
try:
_validate(config)
return True, 'Valid beacon configuration'
except ValidationError as error:
return False, str(error)
def _validate(config):
if not isinstance(config, list):
raise ValidationError(
'Configuration for watchdog beacon must be a list.')
_config = {}
for part in config:
_config.update(part)
if 'directories' not in _config:
raise ValidationError(
'Configuration for watchdog beacon must include directories.')
if not isinstance(_config['directories'], dict):
raise ValidationError(
'Configuration for watchdog beacon directories must be a '
'dictionary.')
for path in _config['directories']:
_validate_path(_config['directories'][path])
def _validate_path(path_config):
if not isinstance(path_config, dict):
raise ValidationError(
'Configuration for watchdog beacon directory path must be '
'a dictionary.')
if 'mask' in path_config:
_validate_mask(path_config['mask'])
def _validate_mask(mask_config):
valid_mask = [
'create',
'modify',
'delete',
'move',
]
if not isinstance(mask_config, list):
raise ValidationError(
'Configuration for watchdog beacon mask must be list.')
if any(mask not in valid_mask for mask in mask_config):
raise ValidationError(
'Configuration for watchdog beacon contains invalid mask')
def to_salt_event(event):
return {
'tag': __virtualname__,
'path': event.src_path,
'change': event.event_type,
}
def close(config):
observer = __context__.pop('watchdog.observer', None)
if observer:
observer.stop()
|
saltstack/salt | salt/states/trafficserver.py | bounce_cluster | python | 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 | 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 | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/trafficserver.py#L20-L43 | null | # -*- coding: utf-8 -*-
'''
Control Apache Traffic Server
=============================
.. versionadded:: 2015.8.0
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
def __virtual__():
'''
Only load if the Traffic Server module is available in __salt__
'''
return 'trafficserver' if 'trafficserver.set_config' in __salt__ else False
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
|
saltstack/salt | salt/states/trafficserver.py | bounce_local | python | 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 | 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 | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/trafficserver.py#L46-L83 | null | # -*- coding: utf-8 -*-
'''
Control Apache Traffic Server
=============================
.. versionadded:: 2015.8.0
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
def __virtual__():
'''
Only load if the Traffic Server module is available in __salt__
'''
return 'trafficserver' if 'trafficserver.set_config' in __salt__ else False
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 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
|
saltstack/salt | salt/states/trafficserver.py | clear_cluster | python | 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 | Clears accumulated statistics on all nodes in the cluster.
.. code-block:: yaml
clear_ats_cluster:
trafficserver.clear_cluster | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/trafficserver.py#L86-L108 | null | # -*- coding: utf-8 -*-
'''
Control Apache Traffic Server
=============================
.. versionadded:: 2015.8.0
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
def __virtual__():
'''
Only load if the Traffic Server module is available in __salt__
'''
return 'trafficserver' if 'trafficserver.set_config' in __salt__ else False
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_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
|
saltstack/salt | salt/states/trafficserver.py | clear_node | python | 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 | Clears accumulated statistics on the local node.
.. code-block:: yaml
clear_ats_node:
trafficserver.clear_node | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/trafficserver.py#L111-L133 | null | # -*- coding: utf-8 -*-
'''
Control Apache Traffic Server
=============================
.. versionadded:: 2015.8.0
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
def __virtual__():
'''
Only load if the Traffic Server module is available in __salt__
'''
return 'trafficserver' if 'trafficserver.set_config' in __salt__ else False
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 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
|
saltstack/salt | salt/states/trafficserver.py | restart_cluster | python | 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 | 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 | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/trafficserver.py#L136-L160 | null | # -*- coding: utf-8 -*-
'''
Control Apache Traffic Server
=============================
.. versionadded:: 2015.8.0
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
def __virtual__():
'''
Only load if the Traffic Server module is available in __salt__
'''
return 'trafficserver' if 'trafficserver.set_config' in __salt__ else False
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_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
|
saltstack/salt | salt/states/trafficserver.py | restart_local | python | 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 | 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 | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/trafficserver.py#L163-L199 | null | # -*- coding: utf-8 -*-
'''
Control Apache Traffic Server
=============================
.. versionadded:: 2015.8.0
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
def __virtual__():
'''
Only load if the Traffic Server module is available in __salt__
'''
return 'trafficserver' if 'trafficserver.set_config' in __salt__ else False
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 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
|
saltstack/salt | salt/states/trafficserver.py | config | python | 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 | 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 | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/trafficserver.py#L202-L236 | null | # -*- coding: utf-8 -*-
'''
Control Apache Traffic Server
=============================
.. versionadded:: 2015.8.0
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
def __virtual__():
'''
Only load if the Traffic Server module is available in __salt__
'''
return 'trafficserver' if 'trafficserver.set_config' in __salt__ else False
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 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
|
saltstack/salt | salt/states/trafficserver.py | shutdown | python | 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 | Shut down Traffic Server on the local node.
.. code-block:: yaml
shutdown_ats:
trafficserver.shutdown | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/trafficserver.py#L239-L261 | null | # -*- coding: utf-8 -*-
'''
Control Apache Traffic Server
=============================
.. versionadded:: 2015.8.0
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
def __virtual__():
'''
Only load if the Traffic Server module is available in __salt__
'''
return 'trafficserver' if 'trafficserver.set_config' in __salt__ else False
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 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
|
saltstack/salt | salt/states/trafficserver.py | startup | python | 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 | Start Traffic Server on the local node.
.. code-block:: yaml
startup_ats:
trafficserver.startup | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/trafficserver.py#L264-L286 | null | # -*- coding: utf-8 -*-
'''
Control Apache Traffic Server
=============================
.. versionadded:: 2015.8.0
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
def __virtual__():
'''
Only load if the Traffic Server module is available in __salt__
'''
return 'trafficserver' if 'trafficserver.set_config' in __salt__ else False
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 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
|
saltstack/salt | salt/states/trafficserver.py | refresh | python | 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 | 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 | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/trafficserver.py#L289-L315 | null | # -*- coding: utf-8 -*-
'''
Control Apache Traffic Server
=============================
.. versionadded:: 2015.8.0
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
def __virtual__():
'''
Only load if the Traffic Server module is available in __salt__
'''
return 'trafficserver' if 'trafficserver.set_config' in __salt__ else False
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 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
|
saltstack/salt | salt/states/trafficserver.py | zero_cluster | python | 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 | Reset performance statistics to zero across the cluster.
.. code-block:: yaml
zero_ats_cluster:
trafficserver.zero_cluster | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/trafficserver.py#L318-L340 | null | # -*- coding: utf-8 -*-
'''
Control Apache Traffic Server
=============================
.. versionadded:: 2015.8.0
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
def __virtual__():
'''
Only load if the Traffic Server module is available in __salt__
'''
return 'trafficserver' if 'trafficserver.set_config' in __salt__ else False
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_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
|
saltstack/salt | salt/states/trafficserver.py | zero_node | python | 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 | Reset performance statistics to zero on the local node.
.. code-block:: yaml
zero_ats_node:
trafficserver.zero_node | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/trafficserver.py#L343-L365 | null | # -*- coding: utf-8 -*-
'''
Control Apache Traffic Server
=============================
.. versionadded:: 2015.8.0
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
def __virtual__():
'''
Only load if the Traffic Server module is available in __salt__
'''
return 'trafficserver' if 'trafficserver.set_config' in __salt__ else False
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 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
|
saltstack/salt | salt/states/trafficserver.py | offline | python | 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 | 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 | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/trafficserver.py#L368-L396 | null | # -*- coding: utf-8 -*-
'''
Control Apache Traffic Server
=============================
.. versionadded:: 2015.8.0
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
def __virtual__():
'''
Only load if the Traffic Server module is available in __salt__
'''
return 'trafficserver' if 'trafficserver.set_config' in __salt__ else False
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
|
saltstack/salt | salt/states/grafana_datasource.py | present | python | 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 | 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 | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/grafana_datasource.py#L39-L116 | [
"def _diff(old, new):\n old_keys = old.keys()\n old = old.copy()\n new = new.copy()\n for key in old_keys:\n if key == 'id' or key == 'orgId':\n del old[key]\n elif key not in new.keys():\n del old[key]\n elif old[key] == new[key]:\n del old[key]\n del new[key]\n return {'old': old, 'new': new}\n",
"def _get_headers(profile):\n return {\n 'Accept': 'application/json',\n 'Authorization': 'Bearer {0}'.format(profile['grafana_token'])\n }\n",
"def _get_url(profile, datasource_id):\n return '{0}/api/datasources/{1}'.format(\n profile['grafana_url'],\n datasource_id\n )\n",
"def _get_json_data(name,\n type,\n url,\n access='proxy',\n user='',\n password='',\n database='',\n basic_auth=False,\n basic_auth_user='',\n basic_auth_password='',\n is_default=False,\n json_data=None):\n return {\n 'name': name,\n 'type': type,\n 'url': url,\n 'access': access,\n 'user': user,\n 'password': password,\n 'database': database,\n 'basicAuth': basic_auth,\n 'basicAuthUser': basic_auth_user,\n 'basicAuthPassword': basic_auth_password,\n 'isDefault': is_default,\n 'jsonData': json_data,\n }\n",
"def _get_datasource(profile, name):\n response = requests.get(\n '{0}/api/datasources'.format(profile['grafana_url']),\n headers=_get_headers(profile),\n timeout=profile.get('grafana_timeout', 3),\n )\n data = response.json()\n for datasource in data:\n if datasource['name'] == name:\n return datasource\n return None\n"
] | # -*- coding: utf-8 -*-
'''
Manage Grafana v2.0 data sources
.. versionadded:: 2016.3.0
.. code-block:: yaml
grafana:
grafana_timeout: 3
grafana_token: qwertyuiop
grafana_url: 'https://url.com'
.. code-block:: yaml
Ensure influxdb data source is present:
grafana_datasource.present:
- name: influxdb
- type: influxdb
- url: http://localhost:8086
- access: proxy
- basic_auth: true
- basic_auth_user: myuser
- basic_auth_password: mypass
- is_default: true
'''
from __future__ import absolute_import, print_function, unicode_literals
import requests
from salt.ext.six import string_types
def __virtual__():
'''Only load if grafana v2.0 is configured.'''
return __salt__['config.get']('grafana_version', 1) == 2
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 _get_url(profile, datasource_id):
return '{0}/api/datasources/{1}'.format(
profile['grafana_url'],
datasource_id
)
def _get_datasource(profile, name):
response = requests.get(
'{0}/api/datasources'.format(profile['grafana_url']),
headers=_get_headers(profile),
timeout=profile.get('grafana_timeout', 3),
)
data = response.json()
for datasource in data:
if datasource['name'] == name:
return datasource
return None
def _get_headers(profile):
return {
'Accept': 'application/json',
'Authorization': 'Bearer {0}'.format(profile['grafana_token'])
}
def _get_json_data(name,
type,
url,
access='proxy',
user='',
password='',
database='',
basic_auth=False,
basic_auth_user='',
basic_auth_password='',
is_default=False,
json_data=None):
return {
'name': name,
'type': type,
'url': url,
'access': access,
'user': user,
'password': password,
'database': database,
'basicAuth': basic_auth,
'basicAuthUser': basic_auth_user,
'basicAuthPassword': basic_auth_password,
'isDefault': is_default,
'jsonData': json_data,
}
def _diff(old, new):
old_keys = old.keys()
old = old.copy()
new = new.copy()
for key in old_keys:
if key == 'id' or key == 'orgId':
del old[key]
elif key not in new.keys():
del old[key]
elif old[key] == new[key]:
del old[key]
del new[key]
return {'old': old, 'new': new}
|
saltstack/salt | salt/states/grafana_datasource.py | absent | python | 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 | Ensure that a data source is present.
name
Name of the data source to remove. | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/grafana_datasource.py#L119-L146 | [
"def _get_headers(profile):\n return {\n 'Accept': 'application/json',\n 'Authorization': 'Bearer {0}'.format(profile['grafana_token'])\n }\n",
"def _get_url(profile, datasource_id):\n return '{0}/api/datasources/{1}'.format(\n profile['grafana_url'],\n datasource_id\n )\n",
"def _get_datasource(profile, name):\n response = requests.get(\n '{0}/api/datasources'.format(profile['grafana_url']),\n headers=_get_headers(profile),\n timeout=profile.get('grafana_timeout', 3),\n )\n data = response.json()\n for datasource in data:\n if datasource['name'] == name:\n return datasource\n return None\n"
] | # -*- coding: utf-8 -*-
'''
Manage Grafana v2.0 data sources
.. versionadded:: 2016.3.0
.. code-block:: yaml
grafana:
grafana_timeout: 3
grafana_token: qwertyuiop
grafana_url: 'https://url.com'
.. code-block:: yaml
Ensure influxdb data source is present:
grafana_datasource.present:
- name: influxdb
- type: influxdb
- url: http://localhost:8086
- access: proxy
- basic_auth: true
- basic_auth_user: myuser
- basic_auth_password: mypass
- is_default: true
'''
from __future__ import absolute_import, print_function, unicode_literals
import requests
from salt.ext.six import string_types
def __virtual__():
'''Only load if grafana v2.0 is configured.'''
return __salt__['config.get']('grafana_version', 1) == 2
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 _get_url(profile, datasource_id):
return '{0}/api/datasources/{1}'.format(
profile['grafana_url'],
datasource_id
)
def _get_datasource(profile, name):
response = requests.get(
'{0}/api/datasources'.format(profile['grafana_url']),
headers=_get_headers(profile),
timeout=profile.get('grafana_timeout', 3),
)
data = response.json()
for datasource in data:
if datasource['name'] == name:
return datasource
return None
def _get_headers(profile):
return {
'Accept': 'application/json',
'Authorization': 'Bearer {0}'.format(profile['grafana_token'])
}
def _get_json_data(name,
type,
url,
access='proxy',
user='',
password='',
database='',
basic_auth=False,
basic_auth_user='',
basic_auth_password='',
is_default=False,
json_data=None):
return {
'name': name,
'type': type,
'url': url,
'access': access,
'user': user,
'password': password,
'database': database,
'basicAuth': basic_auth,
'basicAuthUser': basic_auth_user,
'basicAuthPassword': basic_auth_password,
'isDefault': is_default,
'jsonData': json_data,
}
def _diff(old, new):
old_keys = old.keys()
old = old.copy()
new = new.copy()
for key in old_keys:
if key == 'id' or key == 'orgId':
del old[key]
elif key not in new.keys():
del old[key]
elif old[key] == new[key]:
del old[key]
del new[key]
return {'old': old, 'new': new}
|
saltstack/salt | salt/modules/neutronng.py | compare_changes | python | 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 | Compare two dicts returning only keys that exist in the first dict and are
different in the second one | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutronng.py#L51-L61 | null | # -*- coding: utf-8 -*-
'''
Neutron module for interacting with OpenStack Neutron
.. versionadded:: 2018.3.0
:depends:shade
Example configuration
.. code-block:: yaml
neutron:
cloud: default
.. code-block:: yaml
neutron:
auth:
username: admin
password: password123
user_domain_name: mydomain
project_name: myproject
project_domain_name: myproject
auth_url: https://example.org:5000/v3
identity_api_version: 3
'''
from __future__ import absolute_import, print_function, unicode_literals
HAS_SHADE = False
try:
import shade
HAS_SHADE = True
except ImportError:
pass
__virtualname__ = 'neutronng'
def __virtual__():
'''
Only load this module if shade python module is installed
'''
if HAS_SHADE:
return __virtualname__
return (False, 'The neutronng execution module failed to \
load: shade python module is not available')
def _clean_kwargs(keep_name=False, **kwargs):
'''
Sanatize the the arguments for use with shade
'''
if 'name' in kwargs and not keep_name:
kwargs['name_or_id'] = kwargs.pop('name')
return __utils__['args.clean_kwargs'](**kwargs)
def setup_clouds(auth=None):
'''
Call functions to create Shade cloud objects in __context__ to take
advantage of Shade's in-memory caching across several states
'''
get_operator_cloud(auth)
get_openstack_cloud(auth)
def get_operator_cloud(auth=None):
'''
Return an operator_cloud
'''
if auth is None:
auth = __salt__['config.option']('neutron', {})
if 'shade_opcloud' in __context__:
if __context__['shade_opcloud'].auth == auth:
return __context__['shade_opcloud']
__context__['shade_opcloud'] = shade.operator_cloud(**auth)
return __context__['shade_opcloud']
def get_openstack_cloud(auth=None):
'''
Return an openstack_cloud
'''
if auth is None:
auth = __salt__['config.option']('neutron', {})
if 'shade_oscloud' in __context__:
if __context__['shade_oscloud'].auth == auth:
return __context__['shade_oscloud']
__context__['shade_oscloud'] = shade.openstack_cloud(**auth)
return __context__['shade_oscloud']
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)
|
saltstack/salt | salt/modules/neutronng.py | network_create | python | 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) | 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 | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutronng.py#L109-L147 | [
"def _clean_kwargs(keep_name=False, **kwargs):\n '''\n Sanatize the the arguments for use with shade\n '''\n if 'name' in kwargs and not keep_name:\n kwargs['name_or_id'] = kwargs.pop('name')\n\n return __utils__['args.clean_kwargs'](**kwargs)\n",
"def get_operator_cloud(auth=None):\n '''\n Return an operator_cloud\n '''\n if auth is None:\n auth = __salt__['config.option']('neutron', {})\n if 'shade_opcloud' in __context__:\n if __context__['shade_opcloud'].auth == auth:\n return __context__['shade_opcloud']\n __context__['shade_opcloud'] = shade.operator_cloud(**auth)\n return __context__['shade_opcloud']\n"
] | # -*- coding: utf-8 -*-
'''
Neutron module for interacting with OpenStack Neutron
.. versionadded:: 2018.3.0
:depends:shade
Example configuration
.. code-block:: yaml
neutron:
cloud: default
.. code-block:: yaml
neutron:
auth:
username: admin
password: password123
user_domain_name: mydomain
project_name: myproject
project_domain_name: myproject
auth_url: https://example.org:5000/v3
identity_api_version: 3
'''
from __future__ import absolute_import, print_function, unicode_literals
HAS_SHADE = False
try:
import shade
HAS_SHADE = True
except ImportError:
pass
__virtualname__ = 'neutronng'
def __virtual__():
'''
Only load this module if shade python module is installed
'''
if HAS_SHADE:
return __virtualname__
return (False, 'The neutronng execution module failed to \
load: shade python module is not available')
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 _clean_kwargs(keep_name=False, **kwargs):
'''
Sanatize the the arguments for use with shade
'''
if 'name' in kwargs and not keep_name:
kwargs['name_or_id'] = kwargs.pop('name')
return __utils__['args.clean_kwargs'](**kwargs)
def setup_clouds(auth=None):
'''
Call functions to create Shade cloud objects in __context__ to take
advantage of Shade's in-memory caching across several states
'''
get_operator_cloud(auth)
get_openstack_cloud(auth)
def get_operator_cloud(auth=None):
'''
Return an operator_cloud
'''
if auth is None:
auth = __salt__['config.option']('neutron', {})
if 'shade_opcloud' in __context__:
if __context__['shade_opcloud'].auth == auth:
return __context__['shade_opcloud']
__context__['shade_opcloud'] = shade.operator_cloud(**auth)
return __context__['shade_opcloud']
def get_openstack_cloud(auth=None):
'''
Return an openstack_cloud
'''
if auth is None:
auth = __salt__['config.option']('neutron', {})
if 'shade_oscloud' in __context__:
if __context__['shade_oscloud'].auth == auth:
return __context__['shade_oscloud']
__context__['shade_oscloud'] = shade.openstack_cloud(**auth)
return __context__['shade_oscloud']
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)
|
saltstack/salt | salt/modules/neutronng.py | network_delete | python | 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) | 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 | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutronng.py#L150-L167 | [
"def _clean_kwargs(keep_name=False, **kwargs):\n '''\n Sanatize the the arguments for use with shade\n '''\n if 'name' in kwargs and not keep_name:\n kwargs['name_or_id'] = kwargs.pop('name')\n\n return __utils__['args.clean_kwargs'](**kwargs)\n",
"def get_operator_cloud(auth=None):\n '''\n Return an operator_cloud\n '''\n if auth is None:\n auth = __salt__['config.option']('neutron', {})\n if 'shade_opcloud' in __context__:\n if __context__['shade_opcloud'].auth == auth:\n return __context__['shade_opcloud']\n __context__['shade_opcloud'] = shade.operator_cloud(**auth)\n return __context__['shade_opcloud']\n"
] | # -*- coding: utf-8 -*-
'''
Neutron module for interacting with OpenStack Neutron
.. versionadded:: 2018.3.0
:depends:shade
Example configuration
.. code-block:: yaml
neutron:
cloud: default
.. code-block:: yaml
neutron:
auth:
username: admin
password: password123
user_domain_name: mydomain
project_name: myproject
project_domain_name: myproject
auth_url: https://example.org:5000/v3
identity_api_version: 3
'''
from __future__ import absolute_import, print_function, unicode_literals
HAS_SHADE = False
try:
import shade
HAS_SHADE = True
except ImportError:
pass
__virtualname__ = 'neutronng'
def __virtual__():
'''
Only load this module if shade python module is installed
'''
if HAS_SHADE:
return __virtualname__
return (False, 'The neutronng execution module failed to \
load: shade python module is not available')
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 _clean_kwargs(keep_name=False, **kwargs):
'''
Sanatize the the arguments for use with shade
'''
if 'name' in kwargs and not keep_name:
kwargs['name_or_id'] = kwargs.pop('name')
return __utils__['args.clean_kwargs'](**kwargs)
def setup_clouds(auth=None):
'''
Call functions to create Shade cloud objects in __context__ to take
advantage of Shade's in-memory caching across several states
'''
get_operator_cloud(auth)
get_openstack_cloud(auth)
def get_operator_cloud(auth=None):
'''
Return an operator_cloud
'''
if auth is None:
auth = __salt__['config.option']('neutron', {})
if 'shade_opcloud' in __context__:
if __context__['shade_opcloud'].auth == auth:
return __context__['shade_opcloud']
__context__['shade_opcloud'] = shade.operator_cloud(**auth)
return __context__['shade_opcloud']
def get_openstack_cloud(auth=None):
'''
Return an openstack_cloud
'''
if auth is None:
auth = __salt__['config.option']('neutron', {})
if 'shade_oscloud' in __context__:
if __context__['shade_oscloud'].auth == auth:
return __context__['shade_oscloud']
__context__['shade_oscloud'] = shade.openstack_cloud(**auth)
return __context__['shade_oscloud']
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 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)
|
saltstack/salt | salt/modules/neutronng.py | list_networks | python | 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) | 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"}' | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutronng.py#L170-L188 | [
"def _clean_kwargs(keep_name=False, **kwargs):\n '''\n Sanatize the the arguments for use with shade\n '''\n if 'name' in kwargs and not keep_name:\n kwargs['name_or_id'] = kwargs.pop('name')\n\n return __utils__['args.clean_kwargs'](**kwargs)\n",
"def get_operator_cloud(auth=None):\n '''\n Return an operator_cloud\n '''\n if auth is None:\n auth = __salt__['config.option']('neutron', {})\n if 'shade_opcloud' in __context__:\n if __context__['shade_opcloud'].auth == auth:\n return __context__['shade_opcloud']\n __context__['shade_opcloud'] = shade.operator_cloud(**auth)\n return __context__['shade_opcloud']\n"
] | # -*- coding: utf-8 -*-
'''
Neutron module for interacting with OpenStack Neutron
.. versionadded:: 2018.3.0
:depends:shade
Example configuration
.. code-block:: yaml
neutron:
cloud: default
.. code-block:: yaml
neutron:
auth:
username: admin
password: password123
user_domain_name: mydomain
project_name: myproject
project_domain_name: myproject
auth_url: https://example.org:5000/v3
identity_api_version: 3
'''
from __future__ import absolute_import, print_function, unicode_literals
HAS_SHADE = False
try:
import shade
HAS_SHADE = True
except ImportError:
pass
__virtualname__ = 'neutronng'
def __virtual__():
'''
Only load this module if shade python module is installed
'''
if HAS_SHADE:
return __virtualname__
return (False, 'The neutronng execution module failed to \
load: shade python module is not available')
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 _clean_kwargs(keep_name=False, **kwargs):
'''
Sanatize the the arguments for use with shade
'''
if 'name' in kwargs and not keep_name:
kwargs['name_or_id'] = kwargs.pop('name')
return __utils__['args.clean_kwargs'](**kwargs)
def setup_clouds(auth=None):
'''
Call functions to create Shade cloud objects in __context__ to take
advantage of Shade's in-memory caching across several states
'''
get_operator_cloud(auth)
get_openstack_cloud(auth)
def get_operator_cloud(auth=None):
'''
Return an operator_cloud
'''
if auth is None:
auth = __salt__['config.option']('neutron', {})
if 'shade_opcloud' in __context__:
if __context__['shade_opcloud'].auth == auth:
return __context__['shade_opcloud']
__context__['shade_opcloud'] = shade.operator_cloud(**auth)
return __context__['shade_opcloud']
def get_openstack_cloud(auth=None):
'''
Return an openstack_cloud
'''
if auth is None:
auth = __salt__['config.option']('neutron', {})
if 'shade_oscloud' in __context__:
if __context__['shade_oscloud'].auth == auth:
return __context__['shade_oscloud']
__context__['shade_oscloud'] = shade.openstack_cloud(**auth)
return __context__['shade_oscloud']
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 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)
|
saltstack/salt | salt/modules/neutronng.py | network_get | python | 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) | 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 | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutronng.py#L191-L207 | [
"def _clean_kwargs(keep_name=False, **kwargs):\n '''\n Sanatize the the arguments for use with shade\n '''\n if 'name' in kwargs and not keep_name:\n kwargs['name_or_id'] = kwargs.pop('name')\n\n return __utils__['args.clean_kwargs'](**kwargs)\n",
"def get_operator_cloud(auth=None):\n '''\n Return an operator_cloud\n '''\n if auth is None:\n auth = __salt__['config.option']('neutron', {})\n if 'shade_opcloud' in __context__:\n if __context__['shade_opcloud'].auth == auth:\n return __context__['shade_opcloud']\n __context__['shade_opcloud'] = shade.operator_cloud(**auth)\n return __context__['shade_opcloud']\n"
] | # -*- coding: utf-8 -*-
'''
Neutron module for interacting with OpenStack Neutron
.. versionadded:: 2018.3.0
:depends:shade
Example configuration
.. code-block:: yaml
neutron:
cloud: default
.. code-block:: yaml
neutron:
auth:
username: admin
password: password123
user_domain_name: mydomain
project_name: myproject
project_domain_name: myproject
auth_url: https://example.org:5000/v3
identity_api_version: 3
'''
from __future__ import absolute_import, print_function, unicode_literals
HAS_SHADE = False
try:
import shade
HAS_SHADE = True
except ImportError:
pass
__virtualname__ = 'neutronng'
def __virtual__():
'''
Only load this module if shade python module is installed
'''
if HAS_SHADE:
return __virtualname__
return (False, 'The neutronng execution module failed to \
load: shade python module is not available')
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 _clean_kwargs(keep_name=False, **kwargs):
'''
Sanatize the the arguments for use with shade
'''
if 'name' in kwargs and not keep_name:
kwargs['name_or_id'] = kwargs.pop('name')
return __utils__['args.clean_kwargs'](**kwargs)
def setup_clouds(auth=None):
'''
Call functions to create Shade cloud objects in __context__ to take
advantage of Shade's in-memory caching across several states
'''
get_operator_cloud(auth)
get_openstack_cloud(auth)
def get_operator_cloud(auth=None):
'''
Return an operator_cloud
'''
if auth is None:
auth = __salt__['config.option']('neutron', {})
if 'shade_opcloud' in __context__:
if __context__['shade_opcloud'].auth == auth:
return __context__['shade_opcloud']
__context__['shade_opcloud'] = shade.operator_cloud(**auth)
return __context__['shade_opcloud']
def get_openstack_cloud(auth=None):
'''
Return an openstack_cloud
'''
if auth is None:
auth = __salt__['config.option']('neutron', {})
if 'shade_oscloud' in __context__:
if __context__['shade_oscloud'].auth == auth:
return __context__['shade_oscloud']
__context__['shade_oscloud'] = shade.openstack_cloud(**auth)
return __context__['shade_oscloud']
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 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)
|
saltstack/salt | salt/modules/neutronng.py | subnet_create | python | 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) | 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"]' | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutronng.py#L210-L285 | [
"def _clean_kwargs(keep_name=False, **kwargs):\n '''\n Sanatize the the arguments for use with shade\n '''\n if 'name' in kwargs and not keep_name:\n kwargs['name_or_id'] = kwargs.pop('name')\n\n return __utils__['args.clean_kwargs'](**kwargs)\n",
"def get_operator_cloud(auth=None):\n '''\n Return an operator_cloud\n '''\n if auth is None:\n auth = __salt__['config.option']('neutron', {})\n if 'shade_opcloud' in __context__:\n if __context__['shade_opcloud'].auth == auth:\n return __context__['shade_opcloud']\n __context__['shade_opcloud'] = shade.operator_cloud(**auth)\n return __context__['shade_opcloud']\n"
] | # -*- coding: utf-8 -*-
'''
Neutron module for interacting with OpenStack Neutron
.. versionadded:: 2018.3.0
:depends:shade
Example configuration
.. code-block:: yaml
neutron:
cloud: default
.. code-block:: yaml
neutron:
auth:
username: admin
password: password123
user_domain_name: mydomain
project_name: myproject
project_domain_name: myproject
auth_url: https://example.org:5000/v3
identity_api_version: 3
'''
from __future__ import absolute_import, print_function, unicode_literals
HAS_SHADE = False
try:
import shade
HAS_SHADE = True
except ImportError:
pass
__virtualname__ = 'neutronng'
def __virtual__():
'''
Only load this module if shade python module is installed
'''
if HAS_SHADE:
return __virtualname__
return (False, 'The neutronng execution module failed to \
load: shade python module is not available')
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 _clean_kwargs(keep_name=False, **kwargs):
'''
Sanatize the the arguments for use with shade
'''
if 'name' in kwargs and not keep_name:
kwargs['name_or_id'] = kwargs.pop('name')
return __utils__['args.clean_kwargs'](**kwargs)
def setup_clouds(auth=None):
'''
Call functions to create Shade cloud objects in __context__ to take
advantage of Shade's in-memory caching across several states
'''
get_operator_cloud(auth)
get_openstack_cloud(auth)
def get_operator_cloud(auth=None):
'''
Return an operator_cloud
'''
if auth is None:
auth = __salt__['config.option']('neutron', {})
if 'shade_opcloud' in __context__:
if __context__['shade_opcloud'].auth == auth:
return __context__['shade_opcloud']
__context__['shade_opcloud'] = shade.operator_cloud(**auth)
return __context__['shade_opcloud']
def get_openstack_cloud(auth=None):
'''
Return an openstack_cloud
'''
if auth is None:
auth = __salt__['config.option']('neutron', {})
if 'shade_oscloud' in __context__:
if __context__['shade_oscloud'].auth == auth:
return __context__['shade_oscloud']
__context__['shade_oscloud'] = shade.openstack_cloud(**auth)
return __context__['shade_oscloud']
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_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)
|
saltstack/salt | salt/modules/neutronng.py | subnet_update | python | 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) | 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"]' | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutronng.py#L288-L328 | [
"def _clean_kwargs(keep_name=False, **kwargs):\n '''\n Sanatize the the arguments for use with shade\n '''\n if 'name' in kwargs and not keep_name:\n kwargs['name_or_id'] = kwargs.pop('name')\n\n return __utils__['args.clean_kwargs'](**kwargs)\n",
"def get_operator_cloud(auth=None):\n '''\n Return an operator_cloud\n '''\n if auth is None:\n auth = __salt__['config.option']('neutron', {})\n if 'shade_opcloud' in __context__:\n if __context__['shade_opcloud'].auth == auth:\n return __context__['shade_opcloud']\n __context__['shade_opcloud'] = shade.operator_cloud(**auth)\n return __context__['shade_opcloud']\n"
] | # -*- coding: utf-8 -*-
'''
Neutron module for interacting with OpenStack Neutron
.. versionadded:: 2018.3.0
:depends:shade
Example configuration
.. code-block:: yaml
neutron:
cloud: default
.. code-block:: yaml
neutron:
auth:
username: admin
password: password123
user_domain_name: mydomain
project_name: myproject
project_domain_name: myproject
auth_url: https://example.org:5000/v3
identity_api_version: 3
'''
from __future__ import absolute_import, print_function, unicode_literals
HAS_SHADE = False
try:
import shade
HAS_SHADE = True
except ImportError:
pass
__virtualname__ = 'neutronng'
def __virtual__():
'''
Only load this module if shade python module is installed
'''
if HAS_SHADE:
return __virtualname__
return (False, 'The neutronng execution module failed to \
load: shade python module is not available')
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 _clean_kwargs(keep_name=False, **kwargs):
'''
Sanatize the the arguments for use with shade
'''
if 'name' in kwargs and not keep_name:
kwargs['name_or_id'] = kwargs.pop('name')
return __utils__['args.clean_kwargs'](**kwargs)
def setup_clouds(auth=None):
'''
Call functions to create Shade cloud objects in __context__ to take
advantage of Shade's in-memory caching across several states
'''
get_operator_cloud(auth)
get_openstack_cloud(auth)
def get_operator_cloud(auth=None):
'''
Return an operator_cloud
'''
if auth is None:
auth = __salt__['config.option']('neutron', {})
if 'shade_opcloud' in __context__:
if __context__['shade_opcloud'].auth == auth:
return __context__['shade_opcloud']
__context__['shade_opcloud'] = shade.operator_cloud(**auth)
return __context__['shade_opcloud']
def get_openstack_cloud(auth=None):
'''
Return an openstack_cloud
'''
if auth is None:
auth = __salt__['config.option']('neutron', {})
if 'shade_oscloud' in __context__:
if __context__['shade_oscloud'].auth == auth:
return __context__['shade_oscloud']
__context__['shade_oscloud'] = shade.openstack_cloud(**auth)
return __context__['shade_oscloud']
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_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)
|
saltstack/salt | salt/modules/neutronng.py | subnet_delete | python | 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) | 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 | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutronng.py#L331-L349 | [
"def _clean_kwargs(keep_name=False, **kwargs):\n '''\n Sanatize the the arguments for use with shade\n '''\n if 'name' in kwargs and not keep_name:\n kwargs['name_or_id'] = kwargs.pop('name')\n\n return __utils__['args.clean_kwargs'](**kwargs)\n",
"def get_operator_cloud(auth=None):\n '''\n Return an operator_cloud\n '''\n if auth is None:\n auth = __salt__['config.option']('neutron', {})\n if 'shade_opcloud' in __context__:\n if __context__['shade_opcloud'].auth == auth:\n return __context__['shade_opcloud']\n __context__['shade_opcloud'] = shade.operator_cloud(**auth)\n return __context__['shade_opcloud']\n"
] | # -*- coding: utf-8 -*-
'''
Neutron module for interacting with OpenStack Neutron
.. versionadded:: 2018.3.0
:depends:shade
Example configuration
.. code-block:: yaml
neutron:
cloud: default
.. code-block:: yaml
neutron:
auth:
username: admin
password: password123
user_domain_name: mydomain
project_name: myproject
project_domain_name: myproject
auth_url: https://example.org:5000/v3
identity_api_version: 3
'''
from __future__ import absolute_import, print_function, unicode_literals
HAS_SHADE = False
try:
import shade
HAS_SHADE = True
except ImportError:
pass
__virtualname__ = 'neutronng'
def __virtual__():
'''
Only load this module if shade python module is installed
'''
if HAS_SHADE:
return __virtualname__
return (False, 'The neutronng execution module failed to \
load: shade python module is not available')
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 _clean_kwargs(keep_name=False, **kwargs):
'''
Sanatize the the arguments for use with shade
'''
if 'name' in kwargs and not keep_name:
kwargs['name_or_id'] = kwargs.pop('name')
return __utils__['args.clean_kwargs'](**kwargs)
def setup_clouds(auth=None):
'''
Call functions to create Shade cloud objects in __context__ to take
advantage of Shade's in-memory caching across several states
'''
get_operator_cloud(auth)
get_openstack_cloud(auth)
def get_operator_cloud(auth=None):
'''
Return an operator_cloud
'''
if auth is None:
auth = __salt__['config.option']('neutron', {})
if 'shade_opcloud' in __context__:
if __context__['shade_opcloud'].auth == auth:
return __context__['shade_opcloud']
__context__['shade_opcloud'] = shade.operator_cloud(**auth)
return __context__['shade_opcloud']
def get_openstack_cloud(auth=None):
'''
Return an openstack_cloud
'''
if auth is None:
auth = __salt__['config.option']('neutron', {})
if 'shade_oscloud' in __context__:
if __context__['shade_oscloud'].auth == auth:
return __context__['shade_oscloud']
__context__['shade_oscloud'] = shade.openstack_cloud(**auth)
return __context__['shade_oscloud']
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 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)
|
saltstack/salt | salt/modules/neutronng.py | list_subnets | python | 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) | 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"}' | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutronng.py#L352-L370 | [
"def _clean_kwargs(keep_name=False, **kwargs):\n '''\n Sanatize the the arguments for use with shade\n '''\n if 'name' in kwargs and not keep_name:\n kwargs['name_or_id'] = kwargs.pop('name')\n\n return __utils__['args.clean_kwargs'](**kwargs)\n",
"def get_operator_cloud(auth=None):\n '''\n Return an operator_cloud\n '''\n if auth is None:\n auth = __salt__['config.option']('neutron', {})\n if 'shade_opcloud' in __context__:\n if __context__['shade_opcloud'].auth == auth:\n return __context__['shade_opcloud']\n __context__['shade_opcloud'] = shade.operator_cloud(**auth)\n return __context__['shade_opcloud']\n"
] | # -*- coding: utf-8 -*-
'''
Neutron module for interacting with OpenStack Neutron
.. versionadded:: 2018.3.0
:depends:shade
Example configuration
.. code-block:: yaml
neutron:
cloud: default
.. code-block:: yaml
neutron:
auth:
username: admin
password: password123
user_domain_name: mydomain
project_name: myproject
project_domain_name: myproject
auth_url: https://example.org:5000/v3
identity_api_version: 3
'''
from __future__ import absolute_import, print_function, unicode_literals
HAS_SHADE = False
try:
import shade
HAS_SHADE = True
except ImportError:
pass
__virtualname__ = 'neutronng'
def __virtual__():
'''
Only load this module if shade python module is installed
'''
if HAS_SHADE:
return __virtualname__
return (False, 'The neutronng execution module failed to \
load: shade python module is not available')
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 _clean_kwargs(keep_name=False, **kwargs):
'''
Sanatize the the arguments for use with shade
'''
if 'name' in kwargs and not keep_name:
kwargs['name_or_id'] = kwargs.pop('name')
return __utils__['args.clean_kwargs'](**kwargs)
def setup_clouds(auth=None):
'''
Call functions to create Shade cloud objects in __context__ to take
advantage of Shade's in-memory caching across several states
'''
get_operator_cloud(auth)
get_openstack_cloud(auth)
def get_operator_cloud(auth=None):
'''
Return an operator_cloud
'''
if auth is None:
auth = __salt__['config.option']('neutron', {})
if 'shade_opcloud' in __context__:
if __context__['shade_opcloud'].auth == auth:
return __context__['shade_opcloud']
__context__['shade_opcloud'] = shade.operator_cloud(**auth)
return __context__['shade_opcloud']
def get_openstack_cloud(auth=None):
'''
Return an openstack_cloud
'''
if auth is None:
auth = __salt__['config.option']('neutron', {})
if 'shade_oscloud' in __context__:
if __context__['shade_oscloud'].auth == auth:
return __context__['shade_oscloud']
__context__['shade_oscloud'] = shade.openstack_cloud(**auth)
return __context__['shade_oscloud']
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 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)
|
saltstack/salt | salt/modules/neutronng.py | subnet_get | python | 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) | 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 | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutronng.py#L373-L389 | [
"def _clean_kwargs(keep_name=False, **kwargs):\n '''\n Sanatize the the arguments for use with shade\n '''\n if 'name' in kwargs and not keep_name:\n kwargs['name_or_id'] = kwargs.pop('name')\n\n return __utils__['args.clean_kwargs'](**kwargs)\n",
"def get_operator_cloud(auth=None):\n '''\n Return an operator_cloud\n '''\n if auth is None:\n auth = __salt__['config.option']('neutron', {})\n if 'shade_opcloud' in __context__:\n if __context__['shade_opcloud'].auth == auth:\n return __context__['shade_opcloud']\n __context__['shade_opcloud'] = shade.operator_cloud(**auth)\n return __context__['shade_opcloud']\n"
] | # -*- coding: utf-8 -*-
'''
Neutron module for interacting with OpenStack Neutron
.. versionadded:: 2018.3.0
:depends:shade
Example configuration
.. code-block:: yaml
neutron:
cloud: default
.. code-block:: yaml
neutron:
auth:
username: admin
password: password123
user_domain_name: mydomain
project_name: myproject
project_domain_name: myproject
auth_url: https://example.org:5000/v3
identity_api_version: 3
'''
from __future__ import absolute_import, print_function, unicode_literals
HAS_SHADE = False
try:
import shade
HAS_SHADE = True
except ImportError:
pass
__virtualname__ = 'neutronng'
def __virtual__():
'''
Only load this module if shade python module is installed
'''
if HAS_SHADE:
return __virtualname__
return (False, 'The neutronng execution module failed to \
load: shade python module is not available')
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 _clean_kwargs(keep_name=False, **kwargs):
'''
Sanatize the the arguments for use with shade
'''
if 'name' in kwargs and not keep_name:
kwargs['name_or_id'] = kwargs.pop('name')
return __utils__['args.clean_kwargs'](**kwargs)
def setup_clouds(auth=None):
'''
Call functions to create Shade cloud objects in __context__ to take
advantage of Shade's in-memory caching across several states
'''
get_operator_cloud(auth)
get_openstack_cloud(auth)
def get_operator_cloud(auth=None):
'''
Return an operator_cloud
'''
if auth is None:
auth = __salt__['config.option']('neutron', {})
if 'shade_opcloud' in __context__:
if __context__['shade_opcloud'].auth == auth:
return __context__['shade_opcloud']
__context__['shade_opcloud'] = shade.operator_cloud(**auth)
return __context__['shade_opcloud']
def get_openstack_cloud(auth=None):
'''
Return an openstack_cloud
'''
if auth is None:
auth = __salt__['config.option']('neutron', {})
if 'shade_oscloud' in __context__:
if __context__['shade_oscloud'].auth == auth:
return __context__['shade_oscloud']
__context__['shade_oscloud'] = shade.openstack_cloud(**auth)
return __context__['shade_oscloud']
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 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)
|
saltstack/salt | salt/modules/neutronng.py | security_group_create | python | 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) | 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 | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutronng.py#L392-L412 | [
"def _clean_kwargs(keep_name=False, **kwargs):\n '''\n Sanatize the the arguments for use with shade\n '''\n if 'name' in kwargs and not keep_name:\n kwargs['name_or_id'] = kwargs.pop('name')\n\n return __utils__['args.clean_kwargs'](**kwargs)\n",
"def get_operator_cloud(auth=None):\n '''\n Return an operator_cloud\n '''\n if auth is None:\n auth = __salt__['config.option']('neutron', {})\n if 'shade_opcloud' in __context__:\n if __context__['shade_opcloud'].auth == auth:\n return __context__['shade_opcloud']\n __context__['shade_opcloud'] = shade.operator_cloud(**auth)\n return __context__['shade_opcloud']\n"
] | # -*- coding: utf-8 -*-
'''
Neutron module for interacting with OpenStack Neutron
.. versionadded:: 2018.3.0
:depends:shade
Example configuration
.. code-block:: yaml
neutron:
cloud: default
.. code-block:: yaml
neutron:
auth:
username: admin
password: password123
user_domain_name: mydomain
project_name: myproject
project_domain_name: myproject
auth_url: https://example.org:5000/v3
identity_api_version: 3
'''
from __future__ import absolute_import, print_function, unicode_literals
HAS_SHADE = False
try:
import shade
HAS_SHADE = True
except ImportError:
pass
__virtualname__ = 'neutronng'
def __virtual__():
'''
Only load this module if shade python module is installed
'''
if HAS_SHADE:
return __virtualname__
return (False, 'The neutronng execution module failed to \
load: shade python module is not available')
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 _clean_kwargs(keep_name=False, **kwargs):
'''
Sanatize the the arguments for use with shade
'''
if 'name' in kwargs and not keep_name:
kwargs['name_or_id'] = kwargs.pop('name')
return __utils__['args.clean_kwargs'](**kwargs)
def setup_clouds(auth=None):
'''
Call functions to create Shade cloud objects in __context__ to take
advantage of Shade's in-memory caching across several states
'''
get_operator_cloud(auth)
get_openstack_cloud(auth)
def get_operator_cloud(auth=None):
'''
Return an operator_cloud
'''
if auth is None:
auth = __salt__['config.option']('neutron', {})
if 'shade_opcloud' in __context__:
if __context__['shade_opcloud'].auth == auth:
return __context__['shade_opcloud']
__context__['shade_opcloud'] = shade.operator_cloud(**auth)
return __context__['shade_opcloud']
def get_openstack_cloud(auth=None):
'''
Return an openstack_cloud
'''
if auth is None:
auth = __salt__['config.option']('neutron', {})
if 'shade_oscloud' in __context__:
if __context__['shade_oscloud'].auth == auth:
return __context__['shade_oscloud']
__context__['shade_oscloud'] = shade.openstack_cloud(**auth)
return __context__['shade_oscloud']
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_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)
|
saltstack/salt | salt/modules/neutronng.py | security_group_update | python | 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) | 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 | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutronng.py#L415-L441 | [
"def _clean_kwargs(keep_name=False, **kwargs):\n '''\n Sanatize the the arguments for use with shade\n '''\n if 'name' in kwargs and not keep_name:\n kwargs['name_or_id'] = kwargs.pop('name')\n\n return __utils__['args.clean_kwargs'](**kwargs)\n",
"def get_operator_cloud(auth=None):\n '''\n Return an operator_cloud\n '''\n if auth is None:\n auth = __salt__['config.option']('neutron', {})\n if 'shade_opcloud' in __context__:\n if __context__['shade_opcloud'].auth == auth:\n return __context__['shade_opcloud']\n __context__['shade_opcloud'] = shade.operator_cloud(**auth)\n return __context__['shade_opcloud']\n"
] | # -*- coding: utf-8 -*-
'''
Neutron module for interacting with OpenStack Neutron
.. versionadded:: 2018.3.0
:depends:shade
Example configuration
.. code-block:: yaml
neutron:
cloud: default
.. code-block:: yaml
neutron:
auth:
username: admin
password: password123
user_domain_name: mydomain
project_name: myproject
project_domain_name: myproject
auth_url: https://example.org:5000/v3
identity_api_version: 3
'''
from __future__ import absolute_import, print_function, unicode_literals
HAS_SHADE = False
try:
import shade
HAS_SHADE = True
except ImportError:
pass
__virtualname__ = 'neutronng'
def __virtual__():
'''
Only load this module if shade python module is installed
'''
if HAS_SHADE:
return __virtualname__
return (False, 'The neutronng execution module failed to \
load: shade python module is not available')
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 _clean_kwargs(keep_name=False, **kwargs):
'''
Sanatize the the arguments for use with shade
'''
if 'name' in kwargs and not keep_name:
kwargs['name_or_id'] = kwargs.pop('name')
return __utils__['args.clean_kwargs'](**kwargs)
def setup_clouds(auth=None):
'''
Call functions to create Shade cloud objects in __context__ to take
advantage of Shade's in-memory caching across several states
'''
get_operator_cloud(auth)
get_openstack_cloud(auth)
def get_operator_cloud(auth=None):
'''
Return an operator_cloud
'''
if auth is None:
auth = __salt__['config.option']('neutron', {})
if 'shade_opcloud' in __context__:
if __context__['shade_opcloud'].auth == auth:
return __context__['shade_opcloud']
__context__['shade_opcloud'] = shade.operator_cloud(**auth)
return __context__['shade_opcloud']
def get_openstack_cloud(auth=None):
'''
Return an openstack_cloud
'''
if auth is None:
auth = __salt__['config.option']('neutron', {})
if 'shade_oscloud' in __context__:
if __context__['shade_oscloud'].auth == auth:
return __context__['shade_oscloud']
__context__['shade_oscloud'] = shade.openstack_cloud(**auth)
return __context__['shade_oscloud']
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_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)
|
saltstack/salt | salt/modules/neutronng.py | security_group_delete | python | 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) | 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 | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutronng.py#L444-L460 | [
"def _clean_kwargs(keep_name=False, **kwargs):\n '''\n Sanatize the the arguments for use with shade\n '''\n if 'name' in kwargs and not keep_name:\n kwargs['name_or_id'] = kwargs.pop('name')\n\n return __utils__['args.clean_kwargs'](**kwargs)\n",
"def get_operator_cloud(auth=None):\n '''\n Return an operator_cloud\n '''\n if auth is None:\n auth = __salt__['config.option']('neutron', {})\n if 'shade_opcloud' in __context__:\n if __context__['shade_opcloud'].auth == auth:\n return __context__['shade_opcloud']\n __context__['shade_opcloud'] = shade.operator_cloud(**auth)\n return __context__['shade_opcloud']\n"
] | # -*- coding: utf-8 -*-
'''
Neutron module for interacting with OpenStack Neutron
.. versionadded:: 2018.3.0
:depends:shade
Example configuration
.. code-block:: yaml
neutron:
cloud: default
.. code-block:: yaml
neutron:
auth:
username: admin
password: password123
user_domain_name: mydomain
project_name: myproject
project_domain_name: myproject
auth_url: https://example.org:5000/v3
identity_api_version: 3
'''
from __future__ import absolute_import, print_function, unicode_literals
HAS_SHADE = False
try:
import shade
HAS_SHADE = True
except ImportError:
pass
__virtualname__ = 'neutronng'
def __virtual__():
'''
Only load this module if shade python module is installed
'''
if HAS_SHADE:
return __virtualname__
return (False, 'The neutronng execution module failed to \
load: shade python module is not available')
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 _clean_kwargs(keep_name=False, **kwargs):
'''
Sanatize the the arguments for use with shade
'''
if 'name' in kwargs and not keep_name:
kwargs['name_or_id'] = kwargs.pop('name')
return __utils__['args.clean_kwargs'](**kwargs)
def setup_clouds(auth=None):
'''
Call functions to create Shade cloud objects in __context__ to take
advantage of Shade's in-memory caching across several states
'''
get_operator_cloud(auth)
get_openstack_cloud(auth)
def get_operator_cloud(auth=None):
'''
Return an operator_cloud
'''
if auth is None:
auth = __salt__['config.option']('neutron', {})
if 'shade_opcloud' in __context__:
if __context__['shade_opcloud'].auth == auth:
return __context__['shade_opcloud']
__context__['shade_opcloud'] = shade.operator_cloud(**auth)
return __context__['shade_opcloud']
def get_openstack_cloud(auth=None):
'''
Return an openstack_cloud
'''
if auth is None:
auth = __salt__['config.option']('neutron', {})
if 'shade_oscloud' in __context__:
if __context__['shade_oscloud'].auth == auth:
return __context__['shade_oscloud']
__context__['shade_oscloud'] = shade.openstack_cloud(**auth)
return __context__['shade_oscloud']
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_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)
|
saltstack/salt | salt/modules/neutronng.py | security_group_get | python | 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) | 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"}' | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutronng.py#L463-L484 | [
"def _clean_kwargs(keep_name=False, **kwargs):\n '''\n Sanatize the the arguments for use with shade\n '''\n if 'name' in kwargs and not keep_name:\n kwargs['name_or_id'] = kwargs.pop('name')\n\n return __utils__['args.clean_kwargs'](**kwargs)\n",
"def get_operator_cloud(auth=None):\n '''\n Return an operator_cloud\n '''\n if auth is None:\n auth = __salt__['config.option']('neutron', {})\n if 'shade_opcloud' in __context__:\n if __context__['shade_opcloud'].auth == auth:\n return __context__['shade_opcloud']\n __context__['shade_opcloud'] = shade.operator_cloud(**auth)\n return __context__['shade_opcloud']\n"
] | # -*- coding: utf-8 -*-
'''
Neutron module for interacting with OpenStack Neutron
.. versionadded:: 2018.3.0
:depends:shade
Example configuration
.. code-block:: yaml
neutron:
cloud: default
.. code-block:: yaml
neutron:
auth:
username: admin
password: password123
user_domain_name: mydomain
project_name: myproject
project_domain_name: myproject
auth_url: https://example.org:5000/v3
identity_api_version: 3
'''
from __future__ import absolute_import, print_function, unicode_literals
HAS_SHADE = False
try:
import shade
HAS_SHADE = True
except ImportError:
pass
__virtualname__ = 'neutronng'
def __virtual__():
'''
Only load this module if shade python module is installed
'''
if HAS_SHADE:
return __virtualname__
return (False, 'The neutronng execution module failed to \
load: shade python module is not available')
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 _clean_kwargs(keep_name=False, **kwargs):
'''
Sanatize the the arguments for use with shade
'''
if 'name' in kwargs and not keep_name:
kwargs['name_or_id'] = kwargs.pop('name')
return __utils__['args.clean_kwargs'](**kwargs)
def setup_clouds(auth=None):
'''
Call functions to create Shade cloud objects in __context__ to take
advantage of Shade's in-memory caching across several states
'''
get_operator_cloud(auth)
get_openstack_cloud(auth)
def get_operator_cloud(auth=None):
'''
Return an operator_cloud
'''
if auth is None:
auth = __salt__['config.option']('neutron', {})
if 'shade_opcloud' in __context__:
if __context__['shade_opcloud'].auth == auth:
return __context__['shade_opcloud']
__context__['shade_opcloud'] = shade.operator_cloud(**auth)
return __context__['shade_opcloud']
def get_openstack_cloud(auth=None):
'''
Return an openstack_cloud
'''
if auth is None:
auth = __salt__['config.option']('neutron', {})
if 'shade_oscloud' in __context__:
if __context__['shade_oscloud'].auth == auth:
return __context__['shade_oscloud']
__context__['shade_oscloud'] = shade.openstack_cloud(**auth)
return __context__['shade_oscloud']
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_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)
|
saltstack/salt | salt/modules/neutronng.py | security_group_rule_create | python | 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) | 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 | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutronng.py#L487-L552 | [
"def _clean_kwargs(keep_name=False, **kwargs):\n '''\n Sanatize the the arguments for use with shade\n '''\n if 'name' in kwargs and not keep_name:\n kwargs['name_or_id'] = kwargs.pop('name')\n\n return __utils__['args.clean_kwargs'](**kwargs)\n",
"def get_operator_cloud(auth=None):\n '''\n Return an operator_cloud\n '''\n if auth is None:\n auth = __salt__['config.option']('neutron', {})\n if 'shade_opcloud' in __context__:\n if __context__['shade_opcloud'].auth == auth:\n return __context__['shade_opcloud']\n __context__['shade_opcloud'] = shade.operator_cloud(**auth)\n return __context__['shade_opcloud']\n"
] | # -*- coding: utf-8 -*-
'''
Neutron module for interacting with OpenStack Neutron
.. versionadded:: 2018.3.0
:depends:shade
Example configuration
.. code-block:: yaml
neutron:
cloud: default
.. code-block:: yaml
neutron:
auth:
username: admin
password: password123
user_domain_name: mydomain
project_name: myproject
project_domain_name: myproject
auth_url: https://example.org:5000/v3
identity_api_version: 3
'''
from __future__ import absolute_import, print_function, unicode_literals
HAS_SHADE = False
try:
import shade
HAS_SHADE = True
except ImportError:
pass
__virtualname__ = 'neutronng'
def __virtual__():
'''
Only load this module if shade python module is installed
'''
if HAS_SHADE:
return __virtualname__
return (False, 'The neutronng execution module failed to \
load: shade python module is not available')
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 _clean_kwargs(keep_name=False, **kwargs):
'''
Sanatize the the arguments for use with shade
'''
if 'name' in kwargs and not keep_name:
kwargs['name_or_id'] = kwargs.pop('name')
return __utils__['args.clean_kwargs'](**kwargs)
def setup_clouds(auth=None):
'''
Call functions to create Shade cloud objects in __context__ to take
advantage of Shade's in-memory caching across several states
'''
get_operator_cloud(auth)
get_openstack_cloud(auth)
def get_operator_cloud(auth=None):
'''
Return an operator_cloud
'''
if auth is None:
auth = __salt__['config.option']('neutron', {})
if 'shade_opcloud' in __context__:
if __context__['shade_opcloud'].auth == auth:
return __context__['shade_opcloud']
__context__['shade_opcloud'] = shade.operator_cloud(**auth)
return __context__['shade_opcloud']
def get_openstack_cloud(auth=None):
'''
Return an openstack_cloud
'''
if auth is None:
auth = __salt__['config.option']('neutron', {})
if 'shade_oscloud' in __context__:
if __context__['shade_oscloud'].auth == auth:
return __context__['shade_oscloud']
__context__['shade_oscloud'] = shade.openstack_cloud(**auth)
return __context__['shade_oscloud']
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_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)
|
saltstack/salt | salt/modules/neutronng.py | security_group_rule_delete | python | 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) | 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 | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutronng.py#L555-L571 | [
"def _clean_kwargs(keep_name=False, **kwargs):\n '''\n Sanatize the the arguments for use with shade\n '''\n if 'name' in kwargs and not keep_name:\n kwargs['name_or_id'] = kwargs.pop('name')\n\n return __utils__['args.clean_kwargs'](**kwargs)\n",
"def get_operator_cloud(auth=None):\n '''\n Return an operator_cloud\n '''\n if auth is None:\n auth = __salt__['config.option']('neutron', {})\n if 'shade_opcloud' in __context__:\n if __context__['shade_opcloud'].auth == auth:\n return __context__['shade_opcloud']\n __context__['shade_opcloud'] = shade.operator_cloud(**auth)\n return __context__['shade_opcloud']\n"
] | # -*- coding: utf-8 -*-
'''
Neutron module for interacting with OpenStack Neutron
.. versionadded:: 2018.3.0
:depends:shade
Example configuration
.. code-block:: yaml
neutron:
cloud: default
.. code-block:: yaml
neutron:
auth:
username: admin
password: password123
user_domain_name: mydomain
project_name: myproject
project_domain_name: myproject
auth_url: https://example.org:5000/v3
identity_api_version: 3
'''
from __future__ import absolute_import, print_function, unicode_literals
HAS_SHADE = False
try:
import shade
HAS_SHADE = True
except ImportError:
pass
__virtualname__ = 'neutronng'
def __virtual__():
'''
Only load this module if shade python module is installed
'''
if HAS_SHADE:
return __virtualname__
return (False, 'The neutronng execution module failed to \
load: shade python module is not available')
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 _clean_kwargs(keep_name=False, **kwargs):
'''
Sanatize the the arguments for use with shade
'''
if 'name' in kwargs and not keep_name:
kwargs['name_or_id'] = kwargs.pop('name')
return __utils__['args.clean_kwargs'](**kwargs)
def setup_clouds(auth=None):
'''
Call functions to create Shade cloud objects in __context__ to take
advantage of Shade's in-memory caching across several states
'''
get_operator_cloud(auth)
get_openstack_cloud(auth)
def get_operator_cloud(auth=None):
'''
Return an operator_cloud
'''
if auth is None:
auth = __salt__['config.option']('neutron', {})
if 'shade_opcloud' in __context__:
if __context__['shade_opcloud'].auth == auth:
return __context__['shade_opcloud']
__context__['shade_opcloud'] = shade.operator_cloud(**auth)
return __context__['shade_opcloud']
def get_openstack_cloud(auth=None):
'''
Return an openstack_cloud
'''
if auth is None:
auth = __salt__['config.option']('neutron', {})
if 'shade_oscloud' in __context__:
if __context__['shade_oscloud'].auth == auth:
return __context__['shade_oscloud']
__context__['shade_oscloud'] = shade.openstack_cloud(**auth)
return __context__['shade_oscloud']
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)
|
saltstack/salt | salt/cloud/clouds/aliyun.py | avail_locations | python | 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 | Return a dict of all available VM locations on the cloud provider with
relevant data | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/aliyun.py#L124-L144 | [
"def query(params=None):\n '''\n Make a web call to aliyun ECS REST API\n '''\n path = 'https://ecs-cn-hangzhou.aliyuncs.com'\n\n access_key_id = config.get_cloud_config_value(\n 'id', get_configured_provider(), __opts__, search_global=False\n )\n access_key_secret = config.get_cloud_config_value(\n 'key', get_configured_provider(), __opts__, search_global=False\n )\n\n timestamp = time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.gmtime())\n\n # public interface parameters\n parameters = {\n 'Format': 'JSON',\n 'Version': DEFAULT_ALIYUN_API_VERSION,\n 'AccessKeyId': access_key_id,\n 'SignatureVersion': '1.0',\n 'SignatureMethod': 'HMAC-SHA1',\n 'SignatureNonce': six.text_type(uuid.uuid1()),\n 'TimeStamp': timestamp,\n }\n\n # include action or function parameters\n if params:\n parameters.update(params)\n\n # Calculate the string for Signature\n signature = _compute_signature(parameters, access_key_secret)\n parameters['Signature'] = signature\n\n request = requests.get(path, params=parameters, verify=True)\n if request.status_code != 200:\n raise SaltCloudSystemExit(\n 'An error occurred while querying aliyun ECS. HTTP Code: {0} '\n 'Error: \\'{1}\\''.format(\n request.status_code,\n request.text\n )\n )\n\n log.debug(request.url)\n\n content = request.text\n\n result = salt.utils.json.loads(content)\n if 'Code' in result:\n raise SaltCloudSystemExit(\n pprint.pformat(result.get('Message', {}))\n )\n return result\n"
] | # -*- coding: utf-8 -*-
'''
AliYun ECS Cloud Module
=======================
.. versionadded:: 2014.7.0
The Aliyun cloud module is used to control access to the aliyun ECS.
http://www.aliyun.com/
Use of this module requires the ``id`` and ``key`` parameter to be set.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/aliyun.conf``:
.. code-block:: yaml
my-aliyun-config:
# aliyun Access Key ID
id: wFGEwgregeqw3435gDger
# aliyun Access Key Secret
key: GDE43t43REGTrkilg43934t34qT43t4dgegerGEgg
location: cn-qingdao
driver: aliyun
:depends: requests
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import pprint
import logging
import hmac
import uuid
import sys
import base64
from hashlib import sha1
# Import Salt libs
from salt.ext.six.moves.urllib.parse import quote as _quote # pylint: disable=import-error,no-name-in-module
# Import salt cloud libs
import salt.utils.cloud
import salt.utils.data
import salt.utils.json
import salt.config as config
from salt.exceptions import (
SaltCloudNotFound,
SaltCloudSystemExit,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout
)
from salt.utils.stringutils import to_bytes
# Import 3rd-party libs
from salt.ext import six
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# Get logging started
log = logging.getLogger(__name__)
ALIYUN_LOCATIONS = {
# 'us-west-2': 'ec2_us_west_oregon',
'cn-hangzhou': 'AliYun HangZhou Region',
'cn-beijing': 'AliYun BeiJing Region',
'cn-hongkong': 'AliYun HongKong Region',
'cn-qingdao': 'AliYun QingDao Region',
'cn-shanghai': 'AliYun ShangHai Region',
'cn-shenzhen': 'AliYun ShenZheng Region',
'ap-northeast-1': 'AliYun DongJing Region',
'ap-southeast-1': 'AliYun XinJiaPo Region',
'ap-southeast-2': 'AliYun XiNi Region',
'eu-central-1': 'EU FalaKeFu Region',
'me-east-1': 'ME DiBai Region',
'us-east-1': 'US FuJiNiYa Region',
'us-west-1': 'US GuiGu Region',
}
DEFAULT_LOCATION = 'cn-hangzhou'
DEFAULT_ALIYUN_API_VERSION = '2014-05-26'
__virtualname__ = 'aliyun'
# Only load in this module if the aliyun configurations are in place
def __virtual__():
'''
Check for aliyun configurations
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('id', 'key')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'requests': HAS_REQUESTS}
)
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 get_location(vm_=None):
'''
Return the aliyun region to use, in this order:
- CLI parameter
- VM parameter
- Cloud profile setting
'''
return __opts__.get(
'location',
config.get_cloud_config_value(
'location',
vm_ or get_configured_provider(),
__opts__,
default=DEFAULT_LOCATION,
search_global=False
)
)
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_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
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
)
)
def start(name, call=None):
'''
Start a node
CLI Examples:
.. code-block:: bash
salt-cloud -a start myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Starting node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {'Action': 'StartInstance',
'InstanceId': instanceId}
result = query(params)
return result
def stop(name, force=False, call=None):
'''
Stop a node
CLI Examples:
.. code-block:: bash
salt-cloud -a stop myinstance
salt-cloud -a stop myinstance force=True
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Stopping node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {
'Action': 'StopInstance',
'InstanceId': instanceId,
'ForceStop': six.text_type(force).lower()
}
result = query(params)
return result
def reboot(name, call=None):
'''
Reboot a node
CLI Examples:
.. code-block:: bash
salt-cloud -a reboot myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Rebooting node %s', name)
instance_id = _get_node(name)['InstanceId']
params = {'Action': 'RebootInstance',
'InstanceId': instance_id}
result = query(params)
return result
def create_node(kwargs):
'''
Convenience function to make the rest api call for node creation.
'''
if not isinstance(kwargs, dict):
kwargs = {}
# Required parameters
params = {
'Action': 'CreateInstance',
'InstanceType': kwargs.get('size_id', ''),
'RegionId': kwargs.get('region_id', DEFAULT_LOCATION),
'ImageId': kwargs.get('image_id', ''),
'SecurityGroupId': kwargs.get('securitygroup_id', ''),
'InstanceName': kwargs.get('name', ''),
}
# Optional parameters'
optional = [
'InstanceName', 'InternetChargeType',
'InternetMaxBandwidthIn', 'InternetMaxBandwidthOut',
'HostName', 'Password', 'SystemDisk.Category', 'VSwitchId'
# 'DataDisk.n.Size', 'DataDisk.n.Category', 'DataDisk.n.SnapshotId'
]
for item in optional:
if item in kwargs:
params.update({item: kwargs[item]})
# invoke web call
result = query(params)
return result['InstanceId']
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'aliyun',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
kwargs = {
'name': vm_['name'],
'size_id': get_size(vm_),
'image_id': get_image(vm_),
'region_id': __get_location(vm_),
'securitygroup_id': get_securitygroup(vm_),
}
if 'vswitch_id' in vm_:
kwargs['VSwitchId'] = vm_['vswitch_id']
if 'internet_chargetype' in vm_:
kwargs['InternetChargeType'] = vm_['internet_chargetype']
if 'internet_maxbandwidthin' in vm_:
kwargs['InternetMaxBandwidthIn'] = six.text_type(vm_['internet_maxbandwidthin'])
if 'internet_maxbandwidthout' in vm_:
kwargs['InternetMaxBandwidthOut'] = six.text_type(vm_['internet_maxbandwidthOut'])
if 'hostname' in vm_:
kwargs['HostName'] = vm_['hostname']
if 'password' in vm_:
kwargs['Password'] = vm_['password']
if 'instance_name' in vm_:
kwargs['InstanceName'] = vm_['instance_name']
if 'systemdisk_category' in vm_:
kwargs['SystemDisk.Category'] = vm_['systemdisk_category']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
ret = create_node(kwargs)
except Exception as exc:
log.error(
'Error creating %s on Aliyun ECS\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: %s',
vm_['name'], six.text_type(exc),
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
# repair ip address error and start vm
time.sleep(8)
params = {'Action': 'StartInstance',
'InstanceId': ret}
query(params)
def __query_node_data(vm_name):
data = show_instance(vm_name, call='action')
if not data:
# Trigger an error in the wait_for_ip function
return False
if data.get('PublicIpAddress', None) is not None:
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_['name'],),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
if data['public_ips']:
ssh_ip = data['public_ips'][0]
elif data['private_ips']:
ssh_ip = data['private_ips'][0]
else:
log.info('No available ip:cant connect to salt')
return False
log.debug('VM %s is now running', ssh_ip)
vm_['ssh_host'] = ssh_ip
# The instance is booted and accessible, let's Salt it!
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
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'],
transport=__opts__['transport']
)
return ret
def _compute_signature(parameters, access_key_secret):
'''
Generate aliyun request signature
'''
def percent_encode(line):
if not isinstance(line, six.string_types):
return line
s = line
if sys.stdin.encoding is None:
s = line.decode().encode('utf8')
else:
s = line.decode(sys.stdin.encoding).encode('utf8')
res = _quote(s, '')
res = res.replace('+', '%20')
res = res.replace('*', '%2A')
res = res.replace('%7E', '~')
return res
sortedParameters = sorted(list(parameters.items()), key=lambda items: items[0])
canonicalizedQueryString = ''
for k, v in sortedParameters:
canonicalizedQueryString += '&' + percent_encode(k) \
+ '=' + percent_encode(v)
# All aliyun API only support GET method
stringToSign = 'GET&%2F&' + percent_encode(canonicalizedQueryString[1:])
h = hmac.new(to_bytes(access_key_secret + "&"), stringToSign, sha1)
signature = base64.encodestring(h.digest()).strip()
return signature
def query(params=None):
'''
Make a web call to aliyun ECS REST API
'''
path = 'https://ecs-cn-hangzhou.aliyuncs.com'
access_key_id = config.get_cloud_config_value(
'id', get_configured_provider(), __opts__, search_global=False
)
access_key_secret = config.get_cloud_config_value(
'key', get_configured_provider(), __opts__, search_global=False
)
timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
# public interface parameters
parameters = {
'Format': 'JSON',
'Version': DEFAULT_ALIYUN_API_VERSION,
'AccessKeyId': access_key_id,
'SignatureVersion': '1.0',
'SignatureMethod': 'HMAC-SHA1',
'SignatureNonce': six.text_type(uuid.uuid1()),
'TimeStamp': timestamp,
}
# include action or function parameters
if params:
parameters.update(params)
# Calculate the string for Signature
signature = _compute_signature(parameters, access_key_secret)
parameters['Signature'] = signature
request = requests.get(path, params=parameters, verify=True)
if request.status_code != 200:
raise SaltCloudSystemExit(
'An error occurred while querying aliyun ECS. HTTP Code: {0} '
'Error: \'{1}\''.format(
request.status_code,
request.text
)
)
log.debug(request.url)
content = request.text
result = salt.utils.json.loads(content)
if 'Code' in result:
raise SaltCloudSystemExit(
pprint.pformat(result.get('Message', {}))
)
return result
def script(vm_):
'''
Return the script deployment object
'''
deploy_script = salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
return deploy_script
def show_disk(name, call=None):
'''
Show the disk details of the instance
CLI Examples:
.. code-block:: bash
salt-cloud -a show_disk aliyun myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_disks action must be called with -a or --action.'
)
ret = {}
params = {
'Action': 'DescribeInstanceDisks',
'InstanceId': name
}
items = query(params=params)
for disk in items['Disks']['Disk']:
ret[disk['DiskId']] = {}
for item in disk:
ret[disk['DiskId']][item] = six.text_type(disk[item])
return ret
def list_monitor_data(kwargs=None, call=None):
'''
Get monitor data of the instance. If instance name is
missing, will show all the instance monitor data on the region.
CLI Examples:
.. code-block:: bash
salt-cloud -f list_monitor_data aliyun
salt-cloud -f list_monitor_data aliyun name=AY14051311071990225bd
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_monitor_data must be called with -f or --function.'
)
if not isinstance(kwargs, dict):
kwargs = {}
ret = {}
params = {
'Action': 'GetMonitorData',
'RegionId': get_location()
}
if 'name' in kwargs:
params['InstanceId'] = kwargs['name']
items = query(params=params)
monitorData = items['MonitorData']
for data in monitorData['InstanceMonitorData']:
ret[data['InstanceId']] = {}
for item in data:
ret[data['InstanceId']][item] = six.text_type(data[item])
return ret
def show_instance(name, call=None):
'''
Show the details from aliyun instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
return _get_node(name)
def _get_node(name):
attempts = 5
while attempts >= 0:
try:
return list_nodes_full()[name]
except KeyError:
attempts -= 1
log.debug(
'Failed to get the data for node \'%s\'. Remaining '
'attempts: %s', name, attempts
)
# Just a little delay between attempts...
time.sleep(0.5)
raise SaltCloudNotFound(
'The specified instance {0} not found'.format(name)
)
def show_image(kwargs, call=None):
'''
Show the details from aliyun image
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_images function must be called with '
'-f or --function'
)
if not isinstance(kwargs, dict):
kwargs = {}
location = get_location()
if 'location' in kwargs:
location = kwargs['location']
params = {
'Action': 'DescribeImages',
'RegionId': location,
'ImageId': kwargs['image']
}
ret = {}
items = query(params=params)
# DescribeImages so far support input multi-image. And
# if not found certain image, the response will include
# blank image list other than 'not found' error message
if 'Code' in items or not items['Images']['Image']:
raise SaltCloudNotFound('The specified image could not be found.')
log.debug(
'Total %s image found in Region %s',
items['TotalCount'], location
)
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 destroy(name, call=None):
'''
Destroy a node.
CLI Example:
.. code-block:: bash
salt-cloud -a destroy myinstance
salt-cloud -d myinstance
'''
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']
)
instanceId = _get_node(name)['InstanceId']
# have to stop instance before del it
stop_params = {
'Action': 'StopInstance',
'InstanceId': instanceId
}
query(stop_params)
params = {
'Action': 'DeleteInstance',
'InstanceId': instanceId
}
node = query(params)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return node
|
saltstack/salt | salt/cloud/clouds/aliyun.py | avail_images | python | 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 | Return a list of the images that are on the provider | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/aliyun.py#L147-L179 | [
"def query(params=None):\n '''\n Make a web call to aliyun ECS REST API\n '''\n path = 'https://ecs-cn-hangzhou.aliyuncs.com'\n\n access_key_id = config.get_cloud_config_value(\n 'id', get_configured_provider(), __opts__, search_global=False\n )\n access_key_secret = config.get_cloud_config_value(\n 'key', get_configured_provider(), __opts__, search_global=False\n )\n\n timestamp = time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.gmtime())\n\n # public interface parameters\n parameters = {\n 'Format': 'JSON',\n 'Version': DEFAULT_ALIYUN_API_VERSION,\n 'AccessKeyId': access_key_id,\n 'SignatureVersion': '1.0',\n 'SignatureMethod': 'HMAC-SHA1',\n 'SignatureNonce': six.text_type(uuid.uuid1()),\n 'TimeStamp': timestamp,\n }\n\n # include action or function parameters\n if params:\n parameters.update(params)\n\n # Calculate the string for Signature\n signature = _compute_signature(parameters, access_key_secret)\n parameters['Signature'] = signature\n\n request = requests.get(path, params=parameters, verify=True)\n if request.status_code != 200:\n raise SaltCloudSystemExit(\n 'An error occurred while querying aliyun ECS. HTTP Code: {0} '\n 'Error: \\'{1}\\''.format(\n request.status_code,\n request.text\n )\n )\n\n log.debug(request.url)\n\n content = request.text\n\n result = salt.utils.json.loads(content)\n if 'Code' in result:\n raise SaltCloudSystemExit(\n pprint.pformat(result.get('Message', {}))\n )\n return result\n",
"def get_configured_provider():\n '''\n Return the first configured instance.\n '''\n return config.is_provider_configured(\n __opts__,\n __active_provider_name__ or __virtualname__,\n ('id', 'key')\n )\n"
] | # -*- coding: utf-8 -*-
'''
AliYun ECS Cloud Module
=======================
.. versionadded:: 2014.7.0
The Aliyun cloud module is used to control access to the aliyun ECS.
http://www.aliyun.com/
Use of this module requires the ``id`` and ``key`` parameter to be set.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/aliyun.conf``:
.. code-block:: yaml
my-aliyun-config:
# aliyun Access Key ID
id: wFGEwgregeqw3435gDger
# aliyun Access Key Secret
key: GDE43t43REGTrkilg43934t34qT43t4dgegerGEgg
location: cn-qingdao
driver: aliyun
:depends: requests
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import pprint
import logging
import hmac
import uuid
import sys
import base64
from hashlib import sha1
# Import Salt libs
from salt.ext.six.moves.urllib.parse import quote as _quote # pylint: disable=import-error,no-name-in-module
# Import salt cloud libs
import salt.utils.cloud
import salt.utils.data
import salt.utils.json
import salt.config as config
from salt.exceptions import (
SaltCloudNotFound,
SaltCloudSystemExit,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout
)
from salt.utils.stringutils import to_bytes
# Import 3rd-party libs
from salt.ext import six
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# Get logging started
log = logging.getLogger(__name__)
ALIYUN_LOCATIONS = {
# 'us-west-2': 'ec2_us_west_oregon',
'cn-hangzhou': 'AliYun HangZhou Region',
'cn-beijing': 'AliYun BeiJing Region',
'cn-hongkong': 'AliYun HongKong Region',
'cn-qingdao': 'AliYun QingDao Region',
'cn-shanghai': 'AliYun ShangHai Region',
'cn-shenzhen': 'AliYun ShenZheng Region',
'ap-northeast-1': 'AliYun DongJing Region',
'ap-southeast-1': 'AliYun XinJiaPo Region',
'ap-southeast-2': 'AliYun XiNi Region',
'eu-central-1': 'EU FalaKeFu Region',
'me-east-1': 'ME DiBai Region',
'us-east-1': 'US FuJiNiYa Region',
'us-west-1': 'US GuiGu Region',
}
DEFAULT_LOCATION = 'cn-hangzhou'
DEFAULT_ALIYUN_API_VERSION = '2014-05-26'
__virtualname__ = 'aliyun'
# Only load in this module if the aliyun configurations are in place
def __virtual__():
'''
Check for aliyun configurations
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('id', 'key')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'requests': HAS_REQUESTS}
)
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_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 get_location(vm_=None):
'''
Return the aliyun region to use, in this order:
- CLI parameter
- VM parameter
- Cloud profile setting
'''
return __opts__.get(
'location',
config.get_cloud_config_value(
'location',
vm_ or get_configured_provider(),
__opts__,
default=DEFAULT_LOCATION,
search_global=False
)
)
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_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
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
)
)
def start(name, call=None):
'''
Start a node
CLI Examples:
.. code-block:: bash
salt-cloud -a start myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Starting node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {'Action': 'StartInstance',
'InstanceId': instanceId}
result = query(params)
return result
def stop(name, force=False, call=None):
'''
Stop a node
CLI Examples:
.. code-block:: bash
salt-cloud -a stop myinstance
salt-cloud -a stop myinstance force=True
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Stopping node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {
'Action': 'StopInstance',
'InstanceId': instanceId,
'ForceStop': six.text_type(force).lower()
}
result = query(params)
return result
def reboot(name, call=None):
'''
Reboot a node
CLI Examples:
.. code-block:: bash
salt-cloud -a reboot myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Rebooting node %s', name)
instance_id = _get_node(name)['InstanceId']
params = {'Action': 'RebootInstance',
'InstanceId': instance_id}
result = query(params)
return result
def create_node(kwargs):
'''
Convenience function to make the rest api call for node creation.
'''
if not isinstance(kwargs, dict):
kwargs = {}
# Required parameters
params = {
'Action': 'CreateInstance',
'InstanceType': kwargs.get('size_id', ''),
'RegionId': kwargs.get('region_id', DEFAULT_LOCATION),
'ImageId': kwargs.get('image_id', ''),
'SecurityGroupId': kwargs.get('securitygroup_id', ''),
'InstanceName': kwargs.get('name', ''),
}
# Optional parameters'
optional = [
'InstanceName', 'InternetChargeType',
'InternetMaxBandwidthIn', 'InternetMaxBandwidthOut',
'HostName', 'Password', 'SystemDisk.Category', 'VSwitchId'
# 'DataDisk.n.Size', 'DataDisk.n.Category', 'DataDisk.n.SnapshotId'
]
for item in optional:
if item in kwargs:
params.update({item: kwargs[item]})
# invoke web call
result = query(params)
return result['InstanceId']
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'aliyun',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
kwargs = {
'name': vm_['name'],
'size_id': get_size(vm_),
'image_id': get_image(vm_),
'region_id': __get_location(vm_),
'securitygroup_id': get_securitygroup(vm_),
}
if 'vswitch_id' in vm_:
kwargs['VSwitchId'] = vm_['vswitch_id']
if 'internet_chargetype' in vm_:
kwargs['InternetChargeType'] = vm_['internet_chargetype']
if 'internet_maxbandwidthin' in vm_:
kwargs['InternetMaxBandwidthIn'] = six.text_type(vm_['internet_maxbandwidthin'])
if 'internet_maxbandwidthout' in vm_:
kwargs['InternetMaxBandwidthOut'] = six.text_type(vm_['internet_maxbandwidthOut'])
if 'hostname' in vm_:
kwargs['HostName'] = vm_['hostname']
if 'password' in vm_:
kwargs['Password'] = vm_['password']
if 'instance_name' in vm_:
kwargs['InstanceName'] = vm_['instance_name']
if 'systemdisk_category' in vm_:
kwargs['SystemDisk.Category'] = vm_['systemdisk_category']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
ret = create_node(kwargs)
except Exception as exc:
log.error(
'Error creating %s on Aliyun ECS\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: %s',
vm_['name'], six.text_type(exc),
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
# repair ip address error and start vm
time.sleep(8)
params = {'Action': 'StartInstance',
'InstanceId': ret}
query(params)
def __query_node_data(vm_name):
data = show_instance(vm_name, call='action')
if not data:
# Trigger an error in the wait_for_ip function
return False
if data.get('PublicIpAddress', None) is not None:
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_['name'],),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
if data['public_ips']:
ssh_ip = data['public_ips'][0]
elif data['private_ips']:
ssh_ip = data['private_ips'][0]
else:
log.info('No available ip:cant connect to salt')
return False
log.debug('VM %s is now running', ssh_ip)
vm_['ssh_host'] = ssh_ip
# The instance is booted and accessible, let's Salt it!
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
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'],
transport=__opts__['transport']
)
return ret
def _compute_signature(parameters, access_key_secret):
'''
Generate aliyun request signature
'''
def percent_encode(line):
if not isinstance(line, six.string_types):
return line
s = line
if sys.stdin.encoding is None:
s = line.decode().encode('utf8')
else:
s = line.decode(sys.stdin.encoding).encode('utf8')
res = _quote(s, '')
res = res.replace('+', '%20')
res = res.replace('*', '%2A')
res = res.replace('%7E', '~')
return res
sortedParameters = sorted(list(parameters.items()), key=lambda items: items[0])
canonicalizedQueryString = ''
for k, v in sortedParameters:
canonicalizedQueryString += '&' + percent_encode(k) \
+ '=' + percent_encode(v)
# All aliyun API only support GET method
stringToSign = 'GET&%2F&' + percent_encode(canonicalizedQueryString[1:])
h = hmac.new(to_bytes(access_key_secret + "&"), stringToSign, sha1)
signature = base64.encodestring(h.digest()).strip()
return signature
def query(params=None):
'''
Make a web call to aliyun ECS REST API
'''
path = 'https://ecs-cn-hangzhou.aliyuncs.com'
access_key_id = config.get_cloud_config_value(
'id', get_configured_provider(), __opts__, search_global=False
)
access_key_secret = config.get_cloud_config_value(
'key', get_configured_provider(), __opts__, search_global=False
)
timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
# public interface parameters
parameters = {
'Format': 'JSON',
'Version': DEFAULT_ALIYUN_API_VERSION,
'AccessKeyId': access_key_id,
'SignatureVersion': '1.0',
'SignatureMethod': 'HMAC-SHA1',
'SignatureNonce': six.text_type(uuid.uuid1()),
'TimeStamp': timestamp,
}
# include action or function parameters
if params:
parameters.update(params)
# Calculate the string for Signature
signature = _compute_signature(parameters, access_key_secret)
parameters['Signature'] = signature
request = requests.get(path, params=parameters, verify=True)
if request.status_code != 200:
raise SaltCloudSystemExit(
'An error occurred while querying aliyun ECS. HTTP Code: {0} '
'Error: \'{1}\''.format(
request.status_code,
request.text
)
)
log.debug(request.url)
content = request.text
result = salt.utils.json.loads(content)
if 'Code' in result:
raise SaltCloudSystemExit(
pprint.pformat(result.get('Message', {}))
)
return result
def script(vm_):
'''
Return the script deployment object
'''
deploy_script = salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
return deploy_script
def show_disk(name, call=None):
'''
Show the disk details of the instance
CLI Examples:
.. code-block:: bash
salt-cloud -a show_disk aliyun myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_disks action must be called with -a or --action.'
)
ret = {}
params = {
'Action': 'DescribeInstanceDisks',
'InstanceId': name
}
items = query(params=params)
for disk in items['Disks']['Disk']:
ret[disk['DiskId']] = {}
for item in disk:
ret[disk['DiskId']][item] = six.text_type(disk[item])
return ret
def list_monitor_data(kwargs=None, call=None):
'''
Get monitor data of the instance. If instance name is
missing, will show all the instance monitor data on the region.
CLI Examples:
.. code-block:: bash
salt-cloud -f list_monitor_data aliyun
salt-cloud -f list_monitor_data aliyun name=AY14051311071990225bd
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_monitor_data must be called with -f or --function.'
)
if not isinstance(kwargs, dict):
kwargs = {}
ret = {}
params = {
'Action': 'GetMonitorData',
'RegionId': get_location()
}
if 'name' in kwargs:
params['InstanceId'] = kwargs['name']
items = query(params=params)
monitorData = items['MonitorData']
for data in monitorData['InstanceMonitorData']:
ret[data['InstanceId']] = {}
for item in data:
ret[data['InstanceId']][item] = six.text_type(data[item])
return ret
def show_instance(name, call=None):
'''
Show the details from aliyun instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
return _get_node(name)
def _get_node(name):
attempts = 5
while attempts >= 0:
try:
return list_nodes_full()[name]
except KeyError:
attempts -= 1
log.debug(
'Failed to get the data for node \'%s\'. Remaining '
'attempts: %s', name, attempts
)
# Just a little delay between attempts...
time.sleep(0.5)
raise SaltCloudNotFound(
'The specified instance {0} not found'.format(name)
)
def show_image(kwargs, call=None):
'''
Show the details from aliyun image
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_images function must be called with '
'-f or --function'
)
if not isinstance(kwargs, dict):
kwargs = {}
location = get_location()
if 'location' in kwargs:
location = kwargs['location']
params = {
'Action': 'DescribeImages',
'RegionId': location,
'ImageId': kwargs['image']
}
ret = {}
items = query(params=params)
# DescribeImages so far support input multi-image. And
# if not found certain image, the response will include
# blank image list other than 'not found' error message
if 'Code' in items or not items['Images']['Image']:
raise SaltCloudNotFound('The specified image could not be found.')
log.debug(
'Total %s image found in Region %s',
items['TotalCount'], location
)
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 destroy(name, call=None):
'''
Destroy a node.
CLI Example:
.. code-block:: bash
salt-cloud -a destroy myinstance
salt-cloud -d myinstance
'''
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']
)
instanceId = _get_node(name)['InstanceId']
# have to stop instance before del it
stop_params = {
'Action': 'StopInstance',
'InstanceId': instanceId
}
query(stop_params)
params = {
'Action': 'DeleteInstance',
'InstanceId': instanceId
}
node = query(params)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return node
|
saltstack/salt | salt/cloud/clouds/aliyun.py | avail_sizes | python | 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 | Return a list of the image sizes that are on the provider | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/aliyun.py#L182-L201 | [
"def query(params=None):\n '''\n Make a web call to aliyun ECS REST API\n '''\n path = 'https://ecs-cn-hangzhou.aliyuncs.com'\n\n access_key_id = config.get_cloud_config_value(\n 'id', get_configured_provider(), __opts__, search_global=False\n )\n access_key_secret = config.get_cloud_config_value(\n 'key', get_configured_provider(), __opts__, search_global=False\n )\n\n timestamp = time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.gmtime())\n\n # public interface parameters\n parameters = {\n 'Format': 'JSON',\n 'Version': DEFAULT_ALIYUN_API_VERSION,\n 'AccessKeyId': access_key_id,\n 'SignatureVersion': '1.0',\n 'SignatureMethod': 'HMAC-SHA1',\n 'SignatureNonce': six.text_type(uuid.uuid1()),\n 'TimeStamp': timestamp,\n }\n\n # include action or function parameters\n if params:\n parameters.update(params)\n\n # Calculate the string for Signature\n signature = _compute_signature(parameters, access_key_secret)\n parameters['Signature'] = signature\n\n request = requests.get(path, params=parameters, verify=True)\n if request.status_code != 200:\n raise SaltCloudSystemExit(\n 'An error occurred while querying aliyun ECS. HTTP Code: {0} '\n 'Error: \\'{1}\\''.format(\n request.status_code,\n request.text\n )\n )\n\n log.debug(request.url)\n\n content = request.text\n\n result = salt.utils.json.loads(content)\n if 'Code' in result:\n raise SaltCloudSystemExit(\n pprint.pformat(result.get('Message', {}))\n )\n return result\n"
] | # -*- coding: utf-8 -*-
'''
AliYun ECS Cloud Module
=======================
.. versionadded:: 2014.7.0
The Aliyun cloud module is used to control access to the aliyun ECS.
http://www.aliyun.com/
Use of this module requires the ``id`` and ``key`` parameter to be set.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/aliyun.conf``:
.. code-block:: yaml
my-aliyun-config:
# aliyun Access Key ID
id: wFGEwgregeqw3435gDger
# aliyun Access Key Secret
key: GDE43t43REGTrkilg43934t34qT43t4dgegerGEgg
location: cn-qingdao
driver: aliyun
:depends: requests
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import pprint
import logging
import hmac
import uuid
import sys
import base64
from hashlib import sha1
# Import Salt libs
from salt.ext.six.moves.urllib.parse import quote as _quote # pylint: disable=import-error,no-name-in-module
# Import salt cloud libs
import salt.utils.cloud
import salt.utils.data
import salt.utils.json
import salt.config as config
from salt.exceptions import (
SaltCloudNotFound,
SaltCloudSystemExit,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout
)
from salt.utils.stringutils import to_bytes
# Import 3rd-party libs
from salt.ext import six
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# Get logging started
log = logging.getLogger(__name__)
ALIYUN_LOCATIONS = {
# 'us-west-2': 'ec2_us_west_oregon',
'cn-hangzhou': 'AliYun HangZhou Region',
'cn-beijing': 'AliYun BeiJing Region',
'cn-hongkong': 'AliYun HongKong Region',
'cn-qingdao': 'AliYun QingDao Region',
'cn-shanghai': 'AliYun ShangHai Region',
'cn-shenzhen': 'AliYun ShenZheng Region',
'ap-northeast-1': 'AliYun DongJing Region',
'ap-southeast-1': 'AliYun XinJiaPo Region',
'ap-southeast-2': 'AliYun XiNi Region',
'eu-central-1': 'EU FalaKeFu Region',
'me-east-1': 'ME DiBai Region',
'us-east-1': 'US FuJiNiYa Region',
'us-west-1': 'US GuiGu Region',
}
DEFAULT_LOCATION = 'cn-hangzhou'
DEFAULT_ALIYUN_API_VERSION = '2014-05-26'
__virtualname__ = 'aliyun'
# Only load in this module if the aliyun configurations are in place
def __virtual__():
'''
Check for aliyun configurations
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('id', 'key')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'requests': HAS_REQUESTS}
)
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 get_location(vm_=None):
'''
Return the aliyun region to use, in this order:
- CLI parameter
- VM parameter
- Cloud profile setting
'''
return __opts__.get(
'location',
config.get_cloud_config_value(
'location',
vm_ or get_configured_provider(),
__opts__,
default=DEFAULT_LOCATION,
search_global=False
)
)
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_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
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
)
)
def start(name, call=None):
'''
Start a node
CLI Examples:
.. code-block:: bash
salt-cloud -a start myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Starting node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {'Action': 'StartInstance',
'InstanceId': instanceId}
result = query(params)
return result
def stop(name, force=False, call=None):
'''
Stop a node
CLI Examples:
.. code-block:: bash
salt-cloud -a stop myinstance
salt-cloud -a stop myinstance force=True
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Stopping node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {
'Action': 'StopInstance',
'InstanceId': instanceId,
'ForceStop': six.text_type(force).lower()
}
result = query(params)
return result
def reboot(name, call=None):
'''
Reboot a node
CLI Examples:
.. code-block:: bash
salt-cloud -a reboot myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Rebooting node %s', name)
instance_id = _get_node(name)['InstanceId']
params = {'Action': 'RebootInstance',
'InstanceId': instance_id}
result = query(params)
return result
def create_node(kwargs):
'''
Convenience function to make the rest api call for node creation.
'''
if not isinstance(kwargs, dict):
kwargs = {}
# Required parameters
params = {
'Action': 'CreateInstance',
'InstanceType': kwargs.get('size_id', ''),
'RegionId': kwargs.get('region_id', DEFAULT_LOCATION),
'ImageId': kwargs.get('image_id', ''),
'SecurityGroupId': kwargs.get('securitygroup_id', ''),
'InstanceName': kwargs.get('name', ''),
}
# Optional parameters'
optional = [
'InstanceName', 'InternetChargeType',
'InternetMaxBandwidthIn', 'InternetMaxBandwidthOut',
'HostName', 'Password', 'SystemDisk.Category', 'VSwitchId'
# 'DataDisk.n.Size', 'DataDisk.n.Category', 'DataDisk.n.SnapshotId'
]
for item in optional:
if item in kwargs:
params.update({item: kwargs[item]})
# invoke web call
result = query(params)
return result['InstanceId']
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'aliyun',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
kwargs = {
'name': vm_['name'],
'size_id': get_size(vm_),
'image_id': get_image(vm_),
'region_id': __get_location(vm_),
'securitygroup_id': get_securitygroup(vm_),
}
if 'vswitch_id' in vm_:
kwargs['VSwitchId'] = vm_['vswitch_id']
if 'internet_chargetype' in vm_:
kwargs['InternetChargeType'] = vm_['internet_chargetype']
if 'internet_maxbandwidthin' in vm_:
kwargs['InternetMaxBandwidthIn'] = six.text_type(vm_['internet_maxbandwidthin'])
if 'internet_maxbandwidthout' in vm_:
kwargs['InternetMaxBandwidthOut'] = six.text_type(vm_['internet_maxbandwidthOut'])
if 'hostname' in vm_:
kwargs['HostName'] = vm_['hostname']
if 'password' in vm_:
kwargs['Password'] = vm_['password']
if 'instance_name' in vm_:
kwargs['InstanceName'] = vm_['instance_name']
if 'systemdisk_category' in vm_:
kwargs['SystemDisk.Category'] = vm_['systemdisk_category']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
ret = create_node(kwargs)
except Exception as exc:
log.error(
'Error creating %s on Aliyun ECS\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: %s',
vm_['name'], six.text_type(exc),
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
# repair ip address error and start vm
time.sleep(8)
params = {'Action': 'StartInstance',
'InstanceId': ret}
query(params)
def __query_node_data(vm_name):
data = show_instance(vm_name, call='action')
if not data:
# Trigger an error in the wait_for_ip function
return False
if data.get('PublicIpAddress', None) is not None:
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_['name'],),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
if data['public_ips']:
ssh_ip = data['public_ips'][0]
elif data['private_ips']:
ssh_ip = data['private_ips'][0]
else:
log.info('No available ip:cant connect to salt')
return False
log.debug('VM %s is now running', ssh_ip)
vm_['ssh_host'] = ssh_ip
# The instance is booted and accessible, let's Salt it!
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
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'],
transport=__opts__['transport']
)
return ret
def _compute_signature(parameters, access_key_secret):
'''
Generate aliyun request signature
'''
def percent_encode(line):
if not isinstance(line, six.string_types):
return line
s = line
if sys.stdin.encoding is None:
s = line.decode().encode('utf8')
else:
s = line.decode(sys.stdin.encoding).encode('utf8')
res = _quote(s, '')
res = res.replace('+', '%20')
res = res.replace('*', '%2A')
res = res.replace('%7E', '~')
return res
sortedParameters = sorted(list(parameters.items()), key=lambda items: items[0])
canonicalizedQueryString = ''
for k, v in sortedParameters:
canonicalizedQueryString += '&' + percent_encode(k) \
+ '=' + percent_encode(v)
# All aliyun API only support GET method
stringToSign = 'GET&%2F&' + percent_encode(canonicalizedQueryString[1:])
h = hmac.new(to_bytes(access_key_secret + "&"), stringToSign, sha1)
signature = base64.encodestring(h.digest()).strip()
return signature
def query(params=None):
'''
Make a web call to aliyun ECS REST API
'''
path = 'https://ecs-cn-hangzhou.aliyuncs.com'
access_key_id = config.get_cloud_config_value(
'id', get_configured_provider(), __opts__, search_global=False
)
access_key_secret = config.get_cloud_config_value(
'key', get_configured_provider(), __opts__, search_global=False
)
timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
# public interface parameters
parameters = {
'Format': 'JSON',
'Version': DEFAULT_ALIYUN_API_VERSION,
'AccessKeyId': access_key_id,
'SignatureVersion': '1.0',
'SignatureMethod': 'HMAC-SHA1',
'SignatureNonce': six.text_type(uuid.uuid1()),
'TimeStamp': timestamp,
}
# include action or function parameters
if params:
parameters.update(params)
# Calculate the string for Signature
signature = _compute_signature(parameters, access_key_secret)
parameters['Signature'] = signature
request = requests.get(path, params=parameters, verify=True)
if request.status_code != 200:
raise SaltCloudSystemExit(
'An error occurred while querying aliyun ECS. HTTP Code: {0} '
'Error: \'{1}\''.format(
request.status_code,
request.text
)
)
log.debug(request.url)
content = request.text
result = salt.utils.json.loads(content)
if 'Code' in result:
raise SaltCloudSystemExit(
pprint.pformat(result.get('Message', {}))
)
return result
def script(vm_):
'''
Return the script deployment object
'''
deploy_script = salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
return deploy_script
def show_disk(name, call=None):
'''
Show the disk details of the instance
CLI Examples:
.. code-block:: bash
salt-cloud -a show_disk aliyun myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_disks action must be called with -a or --action.'
)
ret = {}
params = {
'Action': 'DescribeInstanceDisks',
'InstanceId': name
}
items = query(params=params)
for disk in items['Disks']['Disk']:
ret[disk['DiskId']] = {}
for item in disk:
ret[disk['DiskId']][item] = six.text_type(disk[item])
return ret
def list_monitor_data(kwargs=None, call=None):
'''
Get monitor data of the instance. If instance name is
missing, will show all the instance monitor data on the region.
CLI Examples:
.. code-block:: bash
salt-cloud -f list_monitor_data aliyun
salt-cloud -f list_monitor_data aliyun name=AY14051311071990225bd
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_monitor_data must be called with -f or --function.'
)
if not isinstance(kwargs, dict):
kwargs = {}
ret = {}
params = {
'Action': 'GetMonitorData',
'RegionId': get_location()
}
if 'name' in kwargs:
params['InstanceId'] = kwargs['name']
items = query(params=params)
monitorData = items['MonitorData']
for data in monitorData['InstanceMonitorData']:
ret[data['InstanceId']] = {}
for item in data:
ret[data['InstanceId']][item] = six.text_type(data[item])
return ret
def show_instance(name, call=None):
'''
Show the details from aliyun instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
return _get_node(name)
def _get_node(name):
attempts = 5
while attempts >= 0:
try:
return list_nodes_full()[name]
except KeyError:
attempts -= 1
log.debug(
'Failed to get the data for node \'%s\'. Remaining '
'attempts: %s', name, attempts
)
# Just a little delay between attempts...
time.sleep(0.5)
raise SaltCloudNotFound(
'The specified instance {0} not found'.format(name)
)
def show_image(kwargs, call=None):
'''
Show the details from aliyun image
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_images function must be called with '
'-f or --function'
)
if not isinstance(kwargs, dict):
kwargs = {}
location = get_location()
if 'location' in kwargs:
location = kwargs['location']
params = {
'Action': 'DescribeImages',
'RegionId': location,
'ImageId': kwargs['image']
}
ret = {}
items = query(params=params)
# DescribeImages so far support input multi-image. And
# if not found certain image, the response will include
# blank image list other than 'not found' error message
if 'Code' in items or not items['Images']['Image']:
raise SaltCloudNotFound('The specified image could not be found.')
log.debug(
'Total %s image found in Region %s',
items['TotalCount'], location
)
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 destroy(name, call=None):
'''
Destroy a node.
CLI Example:
.. code-block:: bash
salt-cloud -a destroy myinstance
salt-cloud -d myinstance
'''
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']
)
instanceId = _get_node(name)['InstanceId']
# have to stop instance before del it
stop_params = {
'Action': 'StopInstance',
'InstanceId': instanceId
}
query(stop_params)
params = {
'Action': 'DeleteInstance',
'InstanceId': instanceId
}
node = query(params)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return node
|
saltstack/salt | salt/cloud/clouds/aliyun.py | list_availability_zones | python | 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 | List all availability zones in the current region | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/aliyun.py#L223-L238 | [
"def query(params=None):\n '''\n Make a web call to aliyun ECS REST API\n '''\n path = 'https://ecs-cn-hangzhou.aliyuncs.com'\n\n access_key_id = config.get_cloud_config_value(\n 'id', get_configured_provider(), __opts__, search_global=False\n )\n access_key_secret = config.get_cloud_config_value(\n 'key', get_configured_provider(), __opts__, search_global=False\n )\n\n timestamp = time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.gmtime())\n\n # public interface parameters\n parameters = {\n 'Format': 'JSON',\n 'Version': DEFAULT_ALIYUN_API_VERSION,\n 'AccessKeyId': access_key_id,\n 'SignatureVersion': '1.0',\n 'SignatureMethod': 'HMAC-SHA1',\n 'SignatureNonce': six.text_type(uuid.uuid1()),\n 'TimeStamp': timestamp,\n }\n\n # include action or function parameters\n if params:\n parameters.update(params)\n\n # Calculate the string for Signature\n signature = _compute_signature(parameters, access_key_secret)\n parameters['Signature'] = signature\n\n request = requests.get(path, params=parameters, verify=True)\n if request.status_code != 200:\n raise SaltCloudSystemExit(\n 'An error occurred while querying aliyun ECS. HTTP Code: {0} '\n 'Error: \\'{1}\\''.format(\n request.status_code,\n request.text\n )\n )\n\n log.debug(request.url)\n\n content = request.text\n\n result = salt.utils.json.loads(content)\n if 'Code' in result:\n raise SaltCloudSystemExit(\n pprint.pformat(result.get('Message', {}))\n )\n return result\n",
"def get_location(vm_=None):\n '''\n Return the aliyun region to use, in this order:\n - CLI parameter\n - VM parameter\n - Cloud profile setting\n '''\n return __opts__.get(\n 'location',\n config.get_cloud_config_value(\n 'location',\n vm_ or get_configured_provider(),\n __opts__,\n default=DEFAULT_LOCATION,\n search_global=False\n )\n )\n"
] | # -*- coding: utf-8 -*-
'''
AliYun ECS Cloud Module
=======================
.. versionadded:: 2014.7.0
The Aliyun cloud module is used to control access to the aliyun ECS.
http://www.aliyun.com/
Use of this module requires the ``id`` and ``key`` parameter to be set.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/aliyun.conf``:
.. code-block:: yaml
my-aliyun-config:
# aliyun Access Key ID
id: wFGEwgregeqw3435gDger
# aliyun Access Key Secret
key: GDE43t43REGTrkilg43934t34qT43t4dgegerGEgg
location: cn-qingdao
driver: aliyun
:depends: requests
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import pprint
import logging
import hmac
import uuid
import sys
import base64
from hashlib import sha1
# Import Salt libs
from salt.ext.six.moves.urllib.parse import quote as _quote # pylint: disable=import-error,no-name-in-module
# Import salt cloud libs
import salt.utils.cloud
import salt.utils.data
import salt.utils.json
import salt.config as config
from salt.exceptions import (
SaltCloudNotFound,
SaltCloudSystemExit,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout
)
from salt.utils.stringutils import to_bytes
# Import 3rd-party libs
from salt.ext import six
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# Get logging started
log = logging.getLogger(__name__)
ALIYUN_LOCATIONS = {
# 'us-west-2': 'ec2_us_west_oregon',
'cn-hangzhou': 'AliYun HangZhou Region',
'cn-beijing': 'AliYun BeiJing Region',
'cn-hongkong': 'AliYun HongKong Region',
'cn-qingdao': 'AliYun QingDao Region',
'cn-shanghai': 'AliYun ShangHai Region',
'cn-shenzhen': 'AliYun ShenZheng Region',
'ap-northeast-1': 'AliYun DongJing Region',
'ap-southeast-1': 'AliYun XinJiaPo Region',
'ap-southeast-2': 'AliYun XiNi Region',
'eu-central-1': 'EU FalaKeFu Region',
'me-east-1': 'ME DiBai Region',
'us-east-1': 'US FuJiNiYa Region',
'us-west-1': 'US GuiGu Region',
}
DEFAULT_LOCATION = 'cn-hangzhou'
DEFAULT_ALIYUN_API_VERSION = '2014-05-26'
__virtualname__ = 'aliyun'
# Only load in this module if the aliyun configurations are in place
def __virtual__():
'''
Check for aliyun configurations
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('id', 'key')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'requests': HAS_REQUESTS}
)
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 get_location(vm_=None):
'''
Return the aliyun region to use, in this order:
- CLI parameter
- VM parameter
- Cloud profile setting
'''
return __opts__.get(
'location',
config.get_cloud_config_value(
'location',
vm_ or get_configured_provider(),
__opts__,
default=DEFAULT_LOCATION,
search_global=False
)
)
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_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
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
)
)
def start(name, call=None):
'''
Start a node
CLI Examples:
.. code-block:: bash
salt-cloud -a start myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Starting node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {'Action': 'StartInstance',
'InstanceId': instanceId}
result = query(params)
return result
def stop(name, force=False, call=None):
'''
Stop a node
CLI Examples:
.. code-block:: bash
salt-cloud -a stop myinstance
salt-cloud -a stop myinstance force=True
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Stopping node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {
'Action': 'StopInstance',
'InstanceId': instanceId,
'ForceStop': six.text_type(force).lower()
}
result = query(params)
return result
def reboot(name, call=None):
'''
Reboot a node
CLI Examples:
.. code-block:: bash
salt-cloud -a reboot myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Rebooting node %s', name)
instance_id = _get_node(name)['InstanceId']
params = {'Action': 'RebootInstance',
'InstanceId': instance_id}
result = query(params)
return result
def create_node(kwargs):
'''
Convenience function to make the rest api call for node creation.
'''
if not isinstance(kwargs, dict):
kwargs = {}
# Required parameters
params = {
'Action': 'CreateInstance',
'InstanceType': kwargs.get('size_id', ''),
'RegionId': kwargs.get('region_id', DEFAULT_LOCATION),
'ImageId': kwargs.get('image_id', ''),
'SecurityGroupId': kwargs.get('securitygroup_id', ''),
'InstanceName': kwargs.get('name', ''),
}
# Optional parameters'
optional = [
'InstanceName', 'InternetChargeType',
'InternetMaxBandwidthIn', 'InternetMaxBandwidthOut',
'HostName', 'Password', 'SystemDisk.Category', 'VSwitchId'
# 'DataDisk.n.Size', 'DataDisk.n.Category', 'DataDisk.n.SnapshotId'
]
for item in optional:
if item in kwargs:
params.update({item: kwargs[item]})
# invoke web call
result = query(params)
return result['InstanceId']
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'aliyun',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
kwargs = {
'name': vm_['name'],
'size_id': get_size(vm_),
'image_id': get_image(vm_),
'region_id': __get_location(vm_),
'securitygroup_id': get_securitygroup(vm_),
}
if 'vswitch_id' in vm_:
kwargs['VSwitchId'] = vm_['vswitch_id']
if 'internet_chargetype' in vm_:
kwargs['InternetChargeType'] = vm_['internet_chargetype']
if 'internet_maxbandwidthin' in vm_:
kwargs['InternetMaxBandwidthIn'] = six.text_type(vm_['internet_maxbandwidthin'])
if 'internet_maxbandwidthout' in vm_:
kwargs['InternetMaxBandwidthOut'] = six.text_type(vm_['internet_maxbandwidthOut'])
if 'hostname' in vm_:
kwargs['HostName'] = vm_['hostname']
if 'password' in vm_:
kwargs['Password'] = vm_['password']
if 'instance_name' in vm_:
kwargs['InstanceName'] = vm_['instance_name']
if 'systemdisk_category' in vm_:
kwargs['SystemDisk.Category'] = vm_['systemdisk_category']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
ret = create_node(kwargs)
except Exception as exc:
log.error(
'Error creating %s on Aliyun ECS\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: %s',
vm_['name'], six.text_type(exc),
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
# repair ip address error and start vm
time.sleep(8)
params = {'Action': 'StartInstance',
'InstanceId': ret}
query(params)
def __query_node_data(vm_name):
data = show_instance(vm_name, call='action')
if not data:
# Trigger an error in the wait_for_ip function
return False
if data.get('PublicIpAddress', None) is not None:
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_['name'],),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
if data['public_ips']:
ssh_ip = data['public_ips'][0]
elif data['private_ips']:
ssh_ip = data['private_ips'][0]
else:
log.info('No available ip:cant connect to salt')
return False
log.debug('VM %s is now running', ssh_ip)
vm_['ssh_host'] = ssh_ip
# The instance is booted and accessible, let's Salt it!
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
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'],
transport=__opts__['transport']
)
return ret
def _compute_signature(parameters, access_key_secret):
'''
Generate aliyun request signature
'''
def percent_encode(line):
if not isinstance(line, six.string_types):
return line
s = line
if sys.stdin.encoding is None:
s = line.decode().encode('utf8')
else:
s = line.decode(sys.stdin.encoding).encode('utf8')
res = _quote(s, '')
res = res.replace('+', '%20')
res = res.replace('*', '%2A')
res = res.replace('%7E', '~')
return res
sortedParameters = sorted(list(parameters.items()), key=lambda items: items[0])
canonicalizedQueryString = ''
for k, v in sortedParameters:
canonicalizedQueryString += '&' + percent_encode(k) \
+ '=' + percent_encode(v)
# All aliyun API only support GET method
stringToSign = 'GET&%2F&' + percent_encode(canonicalizedQueryString[1:])
h = hmac.new(to_bytes(access_key_secret + "&"), stringToSign, sha1)
signature = base64.encodestring(h.digest()).strip()
return signature
def query(params=None):
'''
Make a web call to aliyun ECS REST API
'''
path = 'https://ecs-cn-hangzhou.aliyuncs.com'
access_key_id = config.get_cloud_config_value(
'id', get_configured_provider(), __opts__, search_global=False
)
access_key_secret = config.get_cloud_config_value(
'key', get_configured_provider(), __opts__, search_global=False
)
timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
# public interface parameters
parameters = {
'Format': 'JSON',
'Version': DEFAULT_ALIYUN_API_VERSION,
'AccessKeyId': access_key_id,
'SignatureVersion': '1.0',
'SignatureMethod': 'HMAC-SHA1',
'SignatureNonce': six.text_type(uuid.uuid1()),
'TimeStamp': timestamp,
}
# include action or function parameters
if params:
parameters.update(params)
# Calculate the string for Signature
signature = _compute_signature(parameters, access_key_secret)
parameters['Signature'] = signature
request = requests.get(path, params=parameters, verify=True)
if request.status_code != 200:
raise SaltCloudSystemExit(
'An error occurred while querying aliyun ECS. HTTP Code: {0} '
'Error: \'{1}\''.format(
request.status_code,
request.text
)
)
log.debug(request.url)
content = request.text
result = salt.utils.json.loads(content)
if 'Code' in result:
raise SaltCloudSystemExit(
pprint.pformat(result.get('Message', {}))
)
return result
def script(vm_):
'''
Return the script deployment object
'''
deploy_script = salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
return deploy_script
def show_disk(name, call=None):
'''
Show the disk details of the instance
CLI Examples:
.. code-block:: bash
salt-cloud -a show_disk aliyun myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_disks action must be called with -a or --action.'
)
ret = {}
params = {
'Action': 'DescribeInstanceDisks',
'InstanceId': name
}
items = query(params=params)
for disk in items['Disks']['Disk']:
ret[disk['DiskId']] = {}
for item in disk:
ret[disk['DiskId']][item] = six.text_type(disk[item])
return ret
def list_monitor_data(kwargs=None, call=None):
'''
Get monitor data of the instance. If instance name is
missing, will show all the instance monitor data on the region.
CLI Examples:
.. code-block:: bash
salt-cloud -f list_monitor_data aliyun
salt-cloud -f list_monitor_data aliyun name=AY14051311071990225bd
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_monitor_data must be called with -f or --function.'
)
if not isinstance(kwargs, dict):
kwargs = {}
ret = {}
params = {
'Action': 'GetMonitorData',
'RegionId': get_location()
}
if 'name' in kwargs:
params['InstanceId'] = kwargs['name']
items = query(params=params)
monitorData = items['MonitorData']
for data in monitorData['InstanceMonitorData']:
ret[data['InstanceId']] = {}
for item in data:
ret[data['InstanceId']][item] = six.text_type(data[item])
return ret
def show_instance(name, call=None):
'''
Show the details from aliyun instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
return _get_node(name)
def _get_node(name):
attempts = 5
while attempts >= 0:
try:
return list_nodes_full()[name]
except KeyError:
attempts -= 1
log.debug(
'Failed to get the data for node \'%s\'. Remaining '
'attempts: %s', name, attempts
)
# Just a little delay between attempts...
time.sleep(0.5)
raise SaltCloudNotFound(
'The specified instance {0} not found'.format(name)
)
def show_image(kwargs, call=None):
'''
Show the details from aliyun image
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_images function must be called with '
'-f or --function'
)
if not isinstance(kwargs, dict):
kwargs = {}
location = get_location()
if 'location' in kwargs:
location = kwargs['location']
params = {
'Action': 'DescribeImages',
'RegionId': location,
'ImageId': kwargs['image']
}
ret = {}
items = query(params=params)
# DescribeImages so far support input multi-image. And
# if not found certain image, the response will include
# blank image list other than 'not found' error message
if 'Code' in items or not items['Images']['Image']:
raise SaltCloudNotFound('The specified image could not be found.')
log.debug(
'Total %s image found in Region %s',
items['TotalCount'], location
)
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 destroy(name, call=None):
'''
Destroy a node.
CLI Example:
.. code-block:: bash
salt-cloud -a destroy myinstance
salt-cloud -d myinstance
'''
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']
)
instanceId = _get_node(name)['InstanceId']
# have to stop instance before del it
stop_params = {
'Action': 'StopInstance',
'InstanceId': instanceId
}
query(stop_params)
params = {
'Action': 'DeleteInstance',
'InstanceId': instanceId
}
node = query(params)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return node
|
saltstack/salt | salt/cloud/clouds/aliyun.py | list_nodes_min | python | 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 | 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. | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/aliyun.py#L241-L272 | [
"def query(params=None):\n '''\n Make a web call to aliyun ECS REST API\n '''\n path = 'https://ecs-cn-hangzhou.aliyuncs.com'\n\n access_key_id = config.get_cloud_config_value(\n 'id', get_configured_provider(), __opts__, search_global=False\n )\n access_key_secret = config.get_cloud_config_value(\n 'key', get_configured_provider(), __opts__, search_global=False\n )\n\n timestamp = time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.gmtime())\n\n # public interface parameters\n parameters = {\n 'Format': 'JSON',\n 'Version': DEFAULT_ALIYUN_API_VERSION,\n 'AccessKeyId': access_key_id,\n 'SignatureVersion': '1.0',\n 'SignatureMethod': 'HMAC-SHA1',\n 'SignatureNonce': six.text_type(uuid.uuid1()),\n 'TimeStamp': timestamp,\n }\n\n # include action or function parameters\n if params:\n parameters.update(params)\n\n # Calculate the string for Signature\n signature = _compute_signature(parameters, access_key_secret)\n parameters['Signature'] = signature\n\n request = requests.get(path, params=parameters, verify=True)\n if request.status_code != 200:\n raise SaltCloudSystemExit(\n 'An error occurred while querying aliyun ECS. HTTP Code: {0} '\n 'Error: \\'{1}\\''.format(\n request.status_code,\n request.text\n )\n )\n\n log.debug(request.url)\n\n content = request.text\n\n result = salt.utils.json.loads(content)\n if 'Code' in result:\n raise SaltCloudSystemExit(\n pprint.pformat(result.get('Message', {}))\n )\n return result\n",
"def get_location(vm_=None):\n '''\n Return the aliyun region to use, in this order:\n - CLI parameter\n - VM parameter\n - Cloud profile setting\n '''\n return __opts__.get(\n 'location',\n config.get_cloud_config_value(\n 'location',\n vm_ or get_configured_provider(),\n __opts__,\n default=DEFAULT_LOCATION,\n search_global=False\n )\n )\n"
] | # -*- coding: utf-8 -*-
'''
AliYun ECS Cloud Module
=======================
.. versionadded:: 2014.7.0
The Aliyun cloud module is used to control access to the aliyun ECS.
http://www.aliyun.com/
Use of this module requires the ``id`` and ``key`` parameter to be set.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/aliyun.conf``:
.. code-block:: yaml
my-aliyun-config:
# aliyun Access Key ID
id: wFGEwgregeqw3435gDger
# aliyun Access Key Secret
key: GDE43t43REGTrkilg43934t34qT43t4dgegerGEgg
location: cn-qingdao
driver: aliyun
:depends: requests
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import pprint
import logging
import hmac
import uuid
import sys
import base64
from hashlib import sha1
# Import Salt libs
from salt.ext.six.moves.urllib.parse import quote as _quote # pylint: disable=import-error,no-name-in-module
# Import salt cloud libs
import salt.utils.cloud
import salt.utils.data
import salt.utils.json
import salt.config as config
from salt.exceptions import (
SaltCloudNotFound,
SaltCloudSystemExit,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout
)
from salt.utils.stringutils import to_bytes
# Import 3rd-party libs
from salt.ext import six
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# Get logging started
log = logging.getLogger(__name__)
ALIYUN_LOCATIONS = {
# 'us-west-2': 'ec2_us_west_oregon',
'cn-hangzhou': 'AliYun HangZhou Region',
'cn-beijing': 'AliYun BeiJing Region',
'cn-hongkong': 'AliYun HongKong Region',
'cn-qingdao': 'AliYun QingDao Region',
'cn-shanghai': 'AliYun ShangHai Region',
'cn-shenzhen': 'AliYun ShenZheng Region',
'ap-northeast-1': 'AliYun DongJing Region',
'ap-southeast-1': 'AliYun XinJiaPo Region',
'ap-southeast-2': 'AliYun XiNi Region',
'eu-central-1': 'EU FalaKeFu Region',
'me-east-1': 'ME DiBai Region',
'us-east-1': 'US FuJiNiYa Region',
'us-west-1': 'US GuiGu Region',
}
DEFAULT_LOCATION = 'cn-hangzhou'
DEFAULT_ALIYUN_API_VERSION = '2014-05-26'
__virtualname__ = 'aliyun'
# Only load in this module if the aliyun configurations are in place
def __virtual__():
'''
Check for aliyun configurations
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('id', 'key')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'requests': HAS_REQUESTS}
)
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 get_location(vm_=None):
'''
Return the aliyun region to use, in this order:
- CLI parameter
- VM parameter
- Cloud profile setting
'''
return __opts__.get(
'location',
config.get_cloud_config_value(
'location',
vm_ or get_configured_provider(),
__opts__,
default=DEFAULT_LOCATION,
search_global=False
)
)
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(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_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
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
)
)
def start(name, call=None):
'''
Start a node
CLI Examples:
.. code-block:: bash
salt-cloud -a start myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Starting node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {'Action': 'StartInstance',
'InstanceId': instanceId}
result = query(params)
return result
def stop(name, force=False, call=None):
'''
Stop a node
CLI Examples:
.. code-block:: bash
salt-cloud -a stop myinstance
salt-cloud -a stop myinstance force=True
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Stopping node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {
'Action': 'StopInstance',
'InstanceId': instanceId,
'ForceStop': six.text_type(force).lower()
}
result = query(params)
return result
def reboot(name, call=None):
'''
Reboot a node
CLI Examples:
.. code-block:: bash
salt-cloud -a reboot myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Rebooting node %s', name)
instance_id = _get_node(name)['InstanceId']
params = {'Action': 'RebootInstance',
'InstanceId': instance_id}
result = query(params)
return result
def create_node(kwargs):
'''
Convenience function to make the rest api call for node creation.
'''
if not isinstance(kwargs, dict):
kwargs = {}
# Required parameters
params = {
'Action': 'CreateInstance',
'InstanceType': kwargs.get('size_id', ''),
'RegionId': kwargs.get('region_id', DEFAULT_LOCATION),
'ImageId': kwargs.get('image_id', ''),
'SecurityGroupId': kwargs.get('securitygroup_id', ''),
'InstanceName': kwargs.get('name', ''),
}
# Optional parameters'
optional = [
'InstanceName', 'InternetChargeType',
'InternetMaxBandwidthIn', 'InternetMaxBandwidthOut',
'HostName', 'Password', 'SystemDisk.Category', 'VSwitchId'
# 'DataDisk.n.Size', 'DataDisk.n.Category', 'DataDisk.n.SnapshotId'
]
for item in optional:
if item in kwargs:
params.update({item: kwargs[item]})
# invoke web call
result = query(params)
return result['InstanceId']
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'aliyun',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
kwargs = {
'name': vm_['name'],
'size_id': get_size(vm_),
'image_id': get_image(vm_),
'region_id': __get_location(vm_),
'securitygroup_id': get_securitygroup(vm_),
}
if 'vswitch_id' in vm_:
kwargs['VSwitchId'] = vm_['vswitch_id']
if 'internet_chargetype' in vm_:
kwargs['InternetChargeType'] = vm_['internet_chargetype']
if 'internet_maxbandwidthin' in vm_:
kwargs['InternetMaxBandwidthIn'] = six.text_type(vm_['internet_maxbandwidthin'])
if 'internet_maxbandwidthout' in vm_:
kwargs['InternetMaxBandwidthOut'] = six.text_type(vm_['internet_maxbandwidthOut'])
if 'hostname' in vm_:
kwargs['HostName'] = vm_['hostname']
if 'password' in vm_:
kwargs['Password'] = vm_['password']
if 'instance_name' in vm_:
kwargs['InstanceName'] = vm_['instance_name']
if 'systemdisk_category' in vm_:
kwargs['SystemDisk.Category'] = vm_['systemdisk_category']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
ret = create_node(kwargs)
except Exception as exc:
log.error(
'Error creating %s on Aliyun ECS\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: %s',
vm_['name'], six.text_type(exc),
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
# repair ip address error and start vm
time.sleep(8)
params = {'Action': 'StartInstance',
'InstanceId': ret}
query(params)
def __query_node_data(vm_name):
data = show_instance(vm_name, call='action')
if not data:
# Trigger an error in the wait_for_ip function
return False
if data.get('PublicIpAddress', None) is not None:
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_['name'],),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
if data['public_ips']:
ssh_ip = data['public_ips'][0]
elif data['private_ips']:
ssh_ip = data['private_ips'][0]
else:
log.info('No available ip:cant connect to salt')
return False
log.debug('VM %s is now running', ssh_ip)
vm_['ssh_host'] = ssh_ip
# The instance is booted and accessible, let's Salt it!
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
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'],
transport=__opts__['transport']
)
return ret
def _compute_signature(parameters, access_key_secret):
'''
Generate aliyun request signature
'''
def percent_encode(line):
if not isinstance(line, six.string_types):
return line
s = line
if sys.stdin.encoding is None:
s = line.decode().encode('utf8')
else:
s = line.decode(sys.stdin.encoding).encode('utf8')
res = _quote(s, '')
res = res.replace('+', '%20')
res = res.replace('*', '%2A')
res = res.replace('%7E', '~')
return res
sortedParameters = sorted(list(parameters.items()), key=lambda items: items[0])
canonicalizedQueryString = ''
for k, v in sortedParameters:
canonicalizedQueryString += '&' + percent_encode(k) \
+ '=' + percent_encode(v)
# All aliyun API only support GET method
stringToSign = 'GET&%2F&' + percent_encode(canonicalizedQueryString[1:])
h = hmac.new(to_bytes(access_key_secret + "&"), stringToSign, sha1)
signature = base64.encodestring(h.digest()).strip()
return signature
def query(params=None):
'''
Make a web call to aliyun ECS REST API
'''
path = 'https://ecs-cn-hangzhou.aliyuncs.com'
access_key_id = config.get_cloud_config_value(
'id', get_configured_provider(), __opts__, search_global=False
)
access_key_secret = config.get_cloud_config_value(
'key', get_configured_provider(), __opts__, search_global=False
)
timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
# public interface parameters
parameters = {
'Format': 'JSON',
'Version': DEFAULT_ALIYUN_API_VERSION,
'AccessKeyId': access_key_id,
'SignatureVersion': '1.0',
'SignatureMethod': 'HMAC-SHA1',
'SignatureNonce': six.text_type(uuid.uuid1()),
'TimeStamp': timestamp,
}
# include action or function parameters
if params:
parameters.update(params)
# Calculate the string for Signature
signature = _compute_signature(parameters, access_key_secret)
parameters['Signature'] = signature
request = requests.get(path, params=parameters, verify=True)
if request.status_code != 200:
raise SaltCloudSystemExit(
'An error occurred while querying aliyun ECS. HTTP Code: {0} '
'Error: \'{1}\''.format(
request.status_code,
request.text
)
)
log.debug(request.url)
content = request.text
result = salt.utils.json.loads(content)
if 'Code' in result:
raise SaltCloudSystemExit(
pprint.pformat(result.get('Message', {}))
)
return result
def script(vm_):
'''
Return the script deployment object
'''
deploy_script = salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
return deploy_script
def show_disk(name, call=None):
'''
Show the disk details of the instance
CLI Examples:
.. code-block:: bash
salt-cloud -a show_disk aliyun myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_disks action must be called with -a or --action.'
)
ret = {}
params = {
'Action': 'DescribeInstanceDisks',
'InstanceId': name
}
items = query(params=params)
for disk in items['Disks']['Disk']:
ret[disk['DiskId']] = {}
for item in disk:
ret[disk['DiskId']][item] = six.text_type(disk[item])
return ret
def list_monitor_data(kwargs=None, call=None):
'''
Get monitor data of the instance. If instance name is
missing, will show all the instance monitor data on the region.
CLI Examples:
.. code-block:: bash
salt-cloud -f list_monitor_data aliyun
salt-cloud -f list_monitor_data aliyun name=AY14051311071990225bd
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_monitor_data must be called with -f or --function.'
)
if not isinstance(kwargs, dict):
kwargs = {}
ret = {}
params = {
'Action': 'GetMonitorData',
'RegionId': get_location()
}
if 'name' in kwargs:
params['InstanceId'] = kwargs['name']
items = query(params=params)
monitorData = items['MonitorData']
for data in monitorData['InstanceMonitorData']:
ret[data['InstanceId']] = {}
for item in data:
ret[data['InstanceId']][item] = six.text_type(data[item])
return ret
def show_instance(name, call=None):
'''
Show the details from aliyun instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
return _get_node(name)
def _get_node(name):
attempts = 5
while attempts >= 0:
try:
return list_nodes_full()[name]
except KeyError:
attempts -= 1
log.debug(
'Failed to get the data for node \'%s\'. Remaining '
'attempts: %s', name, attempts
)
# Just a little delay between attempts...
time.sleep(0.5)
raise SaltCloudNotFound(
'The specified instance {0} not found'.format(name)
)
def show_image(kwargs, call=None):
'''
Show the details from aliyun image
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_images function must be called with '
'-f or --function'
)
if not isinstance(kwargs, dict):
kwargs = {}
location = get_location()
if 'location' in kwargs:
location = kwargs['location']
params = {
'Action': 'DescribeImages',
'RegionId': location,
'ImageId': kwargs['image']
}
ret = {}
items = query(params=params)
# DescribeImages so far support input multi-image. And
# if not found certain image, the response will include
# blank image list other than 'not found' error message
if 'Code' in items or not items['Images']['Image']:
raise SaltCloudNotFound('The specified image could not be found.')
log.debug(
'Total %s image found in Region %s',
items['TotalCount'], location
)
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 destroy(name, call=None):
'''
Destroy a node.
CLI Example:
.. code-block:: bash
salt-cloud -a destroy myinstance
salt-cloud -d myinstance
'''
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']
)
instanceId = _get_node(name)['InstanceId']
# have to stop instance before del it
stop_params = {
'Action': 'StopInstance',
'InstanceId': instanceId
}
query(stop_params)
params = {
'Action': 'DeleteInstance',
'InstanceId': instanceId
}
node = query(params)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return node
|
saltstack/salt | salt/cloud/clouds/aliyun.py | list_nodes | python | 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 | Return a list of the VMs that are on the provider | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/aliyun.py#L275-L296 | [
"def list_nodes_full(call=None):\n '''\n Return a list of the VMs that are on the provider\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The list_nodes_full function must be called with -f '\n 'or --function.'\n )\n\n ret = {}\n location = get_location()\n params = {\n 'Action': 'DescribeInstanceStatus',\n 'RegionId': location,\n 'PageSize': '50'\n }\n result = query(params=params)\n\n log.debug(\n 'Total %s instance found in Region %s',\n result['TotalCount'], location\n )\n if 'Code' in result or result['TotalCount'] == 0:\n return ret\n\n # aliyun max 100 top instance in api\n result_instancestatus = result['InstanceStatuses']['InstanceStatus']\n if result['TotalCount'] > 50:\n params['PageNumber'] = '2'\n result = query(params=params)\n result_instancestatus.update(result['InstanceStatuses']['InstanceStatus'])\n\n for node in result_instancestatus:\n\n instanceId = node.get('InstanceId', '')\n\n params = {\n 'Action': 'DescribeInstanceAttribute',\n 'InstanceId': instanceId\n }\n items = query(params=params)\n if 'Code' in items:\n log.warning('Query instance:%s attribute failed', instanceId)\n continue\n\n name = items['InstanceName']\n ret[name] = {\n 'id': items['InstanceId'],\n 'name': name,\n 'image': items['ImageId'],\n 'size': 'TODO',\n 'state': items['Status']\n }\n for item in items:\n value = items[item]\n if value is not None:\n value = six.text_type(value)\n if item == \"PublicIpAddress\":\n ret[name]['public_ips'] = items[item]['IpAddress']\n if item == \"InnerIpAddress\" and 'private_ips' not in ret[name]:\n ret[name]['private_ips'] = items[item]['IpAddress']\n if item == 'VpcAttributes':\n vpc_ips = items[item]['PrivateIpAddress']['IpAddress']\n if vpc_ips:\n ret[name]['private_ips'] = vpc_ips\n ret[name][item] = value\n\n provider = __active_provider_name__ or 'aliyun'\n if ':' in provider:\n comps = provider.split(':')\n provider = comps[0]\n\n __opts__['update_cachedir'] = True\n __utils__['cloud.cache_node_list'](ret, provider, __opts__)\n\n return ret\n"
] | # -*- coding: utf-8 -*-
'''
AliYun ECS Cloud Module
=======================
.. versionadded:: 2014.7.0
The Aliyun cloud module is used to control access to the aliyun ECS.
http://www.aliyun.com/
Use of this module requires the ``id`` and ``key`` parameter to be set.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/aliyun.conf``:
.. code-block:: yaml
my-aliyun-config:
# aliyun Access Key ID
id: wFGEwgregeqw3435gDger
# aliyun Access Key Secret
key: GDE43t43REGTrkilg43934t34qT43t4dgegerGEgg
location: cn-qingdao
driver: aliyun
:depends: requests
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import pprint
import logging
import hmac
import uuid
import sys
import base64
from hashlib import sha1
# Import Salt libs
from salt.ext.six.moves.urllib.parse import quote as _quote # pylint: disable=import-error,no-name-in-module
# Import salt cloud libs
import salt.utils.cloud
import salt.utils.data
import salt.utils.json
import salt.config as config
from salt.exceptions import (
SaltCloudNotFound,
SaltCloudSystemExit,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout
)
from salt.utils.stringutils import to_bytes
# Import 3rd-party libs
from salt.ext import six
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# Get logging started
log = logging.getLogger(__name__)
ALIYUN_LOCATIONS = {
# 'us-west-2': 'ec2_us_west_oregon',
'cn-hangzhou': 'AliYun HangZhou Region',
'cn-beijing': 'AliYun BeiJing Region',
'cn-hongkong': 'AliYun HongKong Region',
'cn-qingdao': 'AliYun QingDao Region',
'cn-shanghai': 'AliYun ShangHai Region',
'cn-shenzhen': 'AliYun ShenZheng Region',
'ap-northeast-1': 'AliYun DongJing Region',
'ap-southeast-1': 'AliYun XinJiaPo Region',
'ap-southeast-2': 'AliYun XiNi Region',
'eu-central-1': 'EU FalaKeFu Region',
'me-east-1': 'ME DiBai Region',
'us-east-1': 'US FuJiNiYa Region',
'us-west-1': 'US GuiGu Region',
}
DEFAULT_LOCATION = 'cn-hangzhou'
DEFAULT_ALIYUN_API_VERSION = '2014-05-26'
__virtualname__ = 'aliyun'
# Only load in this module if the aliyun configurations are in place
def __virtual__():
'''
Check for aliyun configurations
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('id', 'key')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'requests': HAS_REQUESTS}
)
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 get_location(vm_=None):
'''
Return the aliyun region to use, in this order:
- CLI parameter
- VM parameter
- Cloud profile setting
'''
return __opts__.get(
'location',
config.get_cloud_config_value(
'location',
vm_ or get_configured_provider(),
__opts__,
default=DEFAULT_LOCATION,
search_global=False
)
)
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_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_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
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
)
)
def start(name, call=None):
'''
Start a node
CLI Examples:
.. code-block:: bash
salt-cloud -a start myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Starting node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {'Action': 'StartInstance',
'InstanceId': instanceId}
result = query(params)
return result
def stop(name, force=False, call=None):
'''
Stop a node
CLI Examples:
.. code-block:: bash
salt-cloud -a stop myinstance
salt-cloud -a stop myinstance force=True
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Stopping node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {
'Action': 'StopInstance',
'InstanceId': instanceId,
'ForceStop': six.text_type(force).lower()
}
result = query(params)
return result
def reboot(name, call=None):
'''
Reboot a node
CLI Examples:
.. code-block:: bash
salt-cloud -a reboot myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Rebooting node %s', name)
instance_id = _get_node(name)['InstanceId']
params = {'Action': 'RebootInstance',
'InstanceId': instance_id}
result = query(params)
return result
def create_node(kwargs):
'''
Convenience function to make the rest api call for node creation.
'''
if not isinstance(kwargs, dict):
kwargs = {}
# Required parameters
params = {
'Action': 'CreateInstance',
'InstanceType': kwargs.get('size_id', ''),
'RegionId': kwargs.get('region_id', DEFAULT_LOCATION),
'ImageId': kwargs.get('image_id', ''),
'SecurityGroupId': kwargs.get('securitygroup_id', ''),
'InstanceName': kwargs.get('name', ''),
}
# Optional parameters'
optional = [
'InstanceName', 'InternetChargeType',
'InternetMaxBandwidthIn', 'InternetMaxBandwidthOut',
'HostName', 'Password', 'SystemDisk.Category', 'VSwitchId'
# 'DataDisk.n.Size', 'DataDisk.n.Category', 'DataDisk.n.SnapshotId'
]
for item in optional:
if item in kwargs:
params.update({item: kwargs[item]})
# invoke web call
result = query(params)
return result['InstanceId']
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'aliyun',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
kwargs = {
'name': vm_['name'],
'size_id': get_size(vm_),
'image_id': get_image(vm_),
'region_id': __get_location(vm_),
'securitygroup_id': get_securitygroup(vm_),
}
if 'vswitch_id' in vm_:
kwargs['VSwitchId'] = vm_['vswitch_id']
if 'internet_chargetype' in vm_:
kwargs['InternetChargeType'] = vm_['internet_chargetype']
if 'internet_maxbandwidthin' in vm_:
kwargs['InternetMaxBandwidthIn'] = six.text_type(vm_['internet_maxbandwidthin'])
if 'internet_maxbandwidthout' in vm_:
kwargs['InternetMaxBandwidthOut'] = six.text_type(vm_['internet_maxbandwidthOut'])
if 'hostname' in vm_:
kwargs['HostName'] = vm_['hostname']
if 'password' in vm_:
kwargs['Password'] = vm_['password']
if 'instance_name' in vm_:
kwargs['InstanceName'] = vm_['instance_name']
if 'systemdisk_category' in vm_:
kwargs['SystemDisk.Category'] = vm_['systemdisk_category']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
ret = create_node(kwargs)
except Exception as exc:
log.error(
'Error creating %s on Aliyun ECS\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: %s',
vm_['name'], six.text_type(exc),
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
# repair ip address error and start vm
time.sleep(8)
params = {'Action': 'StartInstance',
'InstanceId': ret}
query(params)
def __query_node_data(vm_name):
data = show_instance(vm_name, call='action')
if not data:
# Trigger an error in the wait_for_ip function
return False
if data.get('PublicIpAddress', None) is not None:
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_['name'],),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
if data['public_ips']:
ssh_ip = data['public_ips'][0]
elif data['private_ips']:
ssh_ip = data['private_ips'][0]
else:
log.info('No available ip:cant connect to salt')
return False
log.debug('VM %s is now running', ssh_ip)
vm_['ssh_host'] = ssh_ip
# The instance is booted and accessible, let's Salt it!
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
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'],
transport=__opts__['transport']
)
return ret
def _compute_signature(parameters, access_key_secret):
'''
Generate aliyun request signature
'''
def percent_encode(line):
if not isinstance(line, six.string_types):
return line
s = line
if sys.stdin.encoding is None:
s = line.decode().encode('utf8')
else:
s = line.decode(sys.stdin.encoding).encode('utf8')
res = _quote(s, '')
res = res.replace('+', '%20')
res = res.replace('*', '%2A')
res = res.replace('%7E', '~')
return res
sortedParameters = sorted(list(parameters.items()), key=lambda items: items[0])
canonicalizedQueryString = ''
for k, v in sortedParameters:
canonicalizedQueryString += '&' + percent_encode(k) \
+ '=' + percent_encode(v)
# All aliyun API only support GET method
stringToSign = 'GET&%2F&' + percent_encode(canonicalizedQueryString[1:])
h = hmac.new(to_bytes(access_key_secret + "&"), stringToSign, sha1)
signature = base64.encodestring(h.digest()).strip()
return signature
def query(params=None):
'''
Make a web call to aliyun ECS REST API
'''
path = 'https://ecs-cn-hangzhou.aliyuncs.com'
access_key_id = config.get_cloud_config_value(
'id', get_configured_provider(), __opts__, search_global=False
)
access_key_secret = config.get_cloud_config_value(
'key', get_configured_provider(), __opts__, search_global=False
)
timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
# public interface parameters
parameters = {
'Format': 'JSON',
'Version': DEFAULT_ALIYUN_API_VERSION,
'AccessKeyId': access_key_id,
'SignatureVersion': '1.0',
'SignatureMethod': 'HMAC-SHA1',
'SignatureNonce': six.text_type(uuid.uuid1()),
'TimeStamp': timestamp,
}
# include action or function parameters
if params:
parameters.update(params)
# Calculate the string for Signature
signature = _compute_signature(parameters, access_key_secret)
parameters['Signature'] = signature
request = requests.get(path, params=parameters, verify=True)
if request.status_code != 200:
raise SaltCloudSystemExit(
'An error occurred while querying aliyun ECS. HTTP Code: {0} '
'Error: \'{1}\''.format(
request.status_code,
request.text
)
)
log.debug(request.url)
content = request.text
result = salt.utils.json.loads(content)
if 'Code' in result:
raise SaltCloudSystemExit(
pprint.pformat(result.get('Message', {}))
)
return result
def script(vm_):
'''
Return the script deployment object
'''
deploy_script = salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
return deploy_script
def show_disk(name, call=None):
'''
Show the disk details of the instance
CLI Examples:
.. code-block:: bash
salt-cloud -a show_disk aliyun myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_disks action must be called with -a or --action.'
)
ret = {}
params = {
'Action': 'DescribeInstanceDisks',
'InstanceId': name
}
items = query(params=params)
for disk in items['Disks']['Disk']:
ret[disk['DiskId']] = {}
for item in disk:
ret[disk['DiskId']][item] = six.text_type(disk[item])
return ret
def list_monitor_data(kwargs=None, call=None):
'''
Get monitor data of the instance. If instance name is
missing, will show all the instance monitor data on the region.
CLI Examples:
.. code-block:: bash
salt-cloud -f list_monitor_data aliyun
salt-cloud -f list_monitor_data aliyun name=AY14051311071990225bd
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_monitor_data must be called with -f or --function.'
)
if not isinstance(kwargs, dict):
kwargs = {}
ret = {}
params = {
'Action': 'GetMonitorData',
'RegionId': get_location()
}
if 'name' in kwargs:
params['InstanceId'] = kwargs['name']
items = query(params=params)
monitorData = items['MonitorData']
for data in monitorData['InstanceMonitorData']:
ret[data['InstanceId']] = {}
for item in data:
ret[data['InstanceId']][item] = six.text_type(data[item])
return ret
def show_instance(name, call=None):
'''
Show the details from aliyun instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
return _get_node(name)
def _get_node(name):
attempts = 5
while attempts >= 0:
try:
return list_nodes_full()[name]
except KeyError:
attempts -= 1
log.debug(
'Failed to get the data for node \'%s\'. Remaining '
'attempts: %s', name, attempts
)
# Just a little delay between attempts...
time.sleep(0.5)
raise SaltCloudNotFound(
'The specified instance {0} not found'.format(name)
)
def show_image(kwargs, call=None):
'''
Show the details from aliyun image
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_images function must be called with '
'-f or --function'
)
if not isinstance(kwargs, dict):
kwargs = {}
location = get_location()
if 'location' in kwargs:
location = kwargs['location']
params = {
'Action': 'DescribeImages',
'RegionId': location,
'ImageId': kwargs['image']
}
ret = {}
items = query(params=params)
# DescribeImages so far support input multi-image. And
# if not found certain image, the response will include
# blank image list other than 'not found' error message
if 'Code' in items or not items['Images']['Image']:
raise SaltCloudNotFound('The specified image could not be found.')
log.debug(
'Total %s image found in Region %s',
items['TotalCount'], location
)
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 destroy(name, call=None):
'''
Destroy a node.
CLI Example:
.. code-block:: bash
salt-cloud -a destroy myinstance
salt-cloud -d myinstance
'''
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']
)
instanceId = _get_node(name)['InstanceId']
# have to stop instance before del it
stop_params = {
'Action': 'StopInstance',
'InstanceId': instanceId
}
query(stop_params)
params = {
'Action': 'DeleteInstance',
'InstanceId': instanceId
}
node = query(params)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return node
|
saltstack/salt | salt/cloud/clouds/aliyun.py | list_nodes_full | python | 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 | Return a list of the VMs that are on the provider | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/aliyun.py#L299-L375 | [
"def query(params=None):\n '''\n Make a web call to aliyun ECS REST API\n '''\n path = 'https://ecs-cn-hangzhou.aliyuncs.com'\n\n access_key_id = config.get_cloud_config_value(\n 'id', get_configured_provider(), __opts__, search_global=False\n )\n access_key_secret = config.get_cloud_config_value(\n 'key', get_configured_provider(), __opts__, search_global=False\n )\n\n timestamp = time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.gmtime())\n\n # public interface parameters\n parameters = {\n 'Format': 'JSON',\n 'Version': DEFAULT_ALIYUN_API_VERSION,\n 'AccessKeyId': access_key_id,\n 'SignatureVersion': '1.0',\n 'SignatureMethod': 'HMAC-SHA1',\n 'SignatureNonce': six.text_type(uuid.uuid1()),\n 'TimeStamp': timestamp,\n }\n\n # include action or function parameters\n if params:\n parameters.update(params)\n\n # Calculate the string for Signature\n signature = _compute_signature(parameters, access_key_secret)\n parameters['Signature'] = signature\n\n request = requests.get(path, params=parameters, verify=True)\n if request.status_code != 200:\n raise SaltCloudSystemExit(\n 'An error occurred while querying aliyun ECS. HTTP Code: {0} '\n 'Error: \\'{1}\\''.format(\n request.status_code,\n request.text\n )\n )\n\n log.debug(request.url)\n\n content = request.text\n\n result = salt.utils.json.loads(content)\n if 'Code' in result:\n raise SaltCloudSystemExit(\n pprint.pformat(result.get('Message', {}))\n )\n return result\n",
"def get_location(vm_=None):\n '''\n Return the aliyun region to use, in this order:\n - CLI parameter\n - VM parameter\n - Cloud profile setting\n '''\n return __opts__.get(\n 'location',\n config.get_cloud_config_value(\n 'location',\n vm_ or get_configured_provider(),\n __opts__,\n default=DEFAULT_LOCATION,\n search_global=False\n )\n )\n"
] | # -*- coding: utf-8 -*-
'''
AliYun ECS Cloud Module
=======================
.. versionadded:: 2014.7.0
The Aliyun cloud module is used to control access to the aliyun ECS.
http://www.aliyun.com/
Use of this module requires the ``id`` and ``key`` parameter to be set.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/aliyun.conf``:
.. code-block:: yaml
my-aliyun-config:
# aliyun Access Key ID
id: wFGEwgregeqw3435gDger
# aliyun Access Key Secret
key: GDE43t43REGTrkilg43934t34qT43t4dgegerGEgg
location: cn-qingdao
driver: aliyun
:depends: requests
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import pprint
import logging
import hmac
import uuid
import sys
import base64
from hashlib import sha1
# Import Salt libs
from salt.ext.six.moves.urllib.parse import quote as _quote # pylint: disable=import-error,no-name-in-module
# Import salt cloud libs
import salt.utils.cloud
import salt.utils.data
import salt.utils.json
import salt.config as config
from salt.exceptions import (
SaltCloudNotFound,
SaltCloudSystemExit,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout
)
from salt.utils.stringutils import to_bytes
# Import 3rd-party libs
from salt.ext import six
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# Get logging started
log = logging.getLogger(__name__)
ALIYUN_LOCATIONS = {
# 'us-west-2': 'ec2_us_west_oregon',
'cn-hangzhou': 'AliYun HangZhou Region',
'cn-beijing': 'AliYun BeiJing Region',
'cn-hongkong': 'AliYun HongKong Region',
'cn-qingdao': 'AliYun QingDao Region',
'cn-shanghai': 'AliYun ShangHai Region',
'cn-shenzhen': 'AliYun ShenZheng Region',
'ap-northeast-1': 'AliYun DongJing Region',
'ap-southeast-1': 'AliYun XinJiaPo Region',
'ap-southeast-2': 'AliYun XiNi Region',
'eu-central-1': 'EU FalaKeFu Region',
'me-east-1': 'ME DiBai Region',
'us-east-1': 'US FuJiNiYa Region',
'us-west-1': 'US GuiGu Region',
}
DEFAULT_LOCATION = 'cn-hangzhou'
DEFAULT_ALIYUN_API_VERSION = '2014-05-26'
__virtualname__ = 'aliyun'
# Only load in this module if the aliyun configurations are in place
def __virtual__():
'''
Check for aliyun configurations
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('id', 'key')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'requests': HAS_REQUESTS}
)
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 get_location(vm_=None):
'''
Return the aliyun region to use, in this order:
- CLI parameter
- VM parameter
- Cloud profile setting
'''
return __opts__.get(
'location',
config.get_cloud_config_value(
'location',
vm_ or get_configured_provider(),
__opts__,
default=DEFAULT_LOCATION,
search_global=False
)
)
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_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
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
)
)
def start(name, call=None):
'''
Start a node
CLI Examples:
.. code-block:: bash
salt-cloud -a start myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Starting node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {'Action': 'StartInstance',
'InstanceId': instanceId}
result = query(params)
return result
def stop(name, force=False, call=None):
'''
Stop a node
CLI Examples:
.. code-block:: bash
salt-cloud -a stop myinstance
salt-cloud -a stop myinstance force=True
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Stopping node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {
'Action': 'StopInstance',
'InstanceId': instanceId,
'ForceStop': six.text_type(force).lower()
}
result = query(params)
return result
def reboot(name, call=None):
'''
Reboot a node
CLI Examples:
.. code-block:: bash
salt-cloud -a reboot myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Rebooting node %s', name)
instance_id = _get_node(name)['InstanceId']
params = {'Action': 'RebootInstance',
'InstanceId': instance_id}
result = query(params)
return result
def create_node(kwargs):
'''
Convenience function to make the rest api call for node creation.
'''
if not isinstance(kwargs, dict):
kwargs = {}
# Required parameters
params = {
'Action': 'CreateInstance',
'InstanceType': kwargs.get('size_id', ''),
'RegionId': kwargs.get('region_id', DEFAULT_LOCATION),
'ImageId': kwargs.get('image_id', ''),
'SecurityGroupId': kwargs.get('securitygroup_id', ''),
'InstanceName': kwargs.get('name', ''),
}
# Optional parameters'
optional = [
'InstanceName', 'InternetChargeType',
'InternetMaxBandwidthIn', 'InternetMaxBandwidthOut',
'HostName', 'Password', 'SystemDisk.Category', 'VSwitchId'
# 'DataDisk.n.Size', 'DataDisk.n.Category', 'DataDisk.n.SnapshotId'
]
for item in optional:
if item in kwargs:
params.update({item: kwargs[item]})
# invoke web call
result = query(params)
return result['InstanceId']
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'aliyun',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
kwargs = {
'name': vm_['name'],
'size_id': get_size(vm_),
'image_id': get_image(vm_),
'region_id': __get_location(vm_),
'securitygroup_id': get_securitygroup(vm_),
}
if 'vswitch_id' in vm_:
kwargs['VSwitchId'] = vm_['vswitch_id']
if 'internet_chargetype' in vm_:
kwargs['InternetChargeType'] = vm_['internet_chargetype']
if 'internet_maxbandwidthin' in vm_:
kwargs['InternetMaxBandwidthIn'] = six.text_type(vm_['internet_maxbandwidthin'])
if 'internet_maxbandwidthout' in vm_:
kwargs['InternetMaxBandwidthOut'] = six.text_type(vm_['internet_maxbandwidthOut'])
if 'hostname' in vm_:
kwargs['HostName'] = vm_['hostname']
if 'password' in vm_:
kwargs['Password'] = vm_['password']
if 'instance_name' in vm_:
kwargs['InstanceName'] = vm_['instance_name']
if 'systemdisk_category' in vm_:
kwargs['SystemDisk.Category'] = vm_['systemdisk_category']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
ret = create_node(kwargs)
except Exception as exc:
log.error(
'Error creating %s on Aliyun ECS\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: %s',
vm_['name'], six.text_type(exc),
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
# repair ip address error and start vm
time.sleep(8)
params = {'Action': 'StartInstance',
'InstanceId': ret}
query(params)
def __query_node_data(vm_name):
data = show_instance(vm_name, call='action')
if not data:
# Trigger an error in the wait_for_ip function
return False
if data.get('PublicIpAddress', None) is not None:
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_['name'],),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
if data['public_ips']:
ssh_ip = data['public_ips'][0]
elif data['private_ips']:
ssh_ip = data['private_ips'][0]
else:
log.info('No available ip:cant connect to salt')
return False
log.debug('VM %s is now running', ssh_ip)
vm_['ssh_host'] = ssh_ip
# The instance is booted and accessible, let's Salt it!
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
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'],
transport=__opts__['transport']
)
return ret
def _compute_signature(parameters, access_key_secret):
'''
Generate aliyun request signature
'''
def percent_encode(line):
if not isinstance(line, six.string_types):
return line
s = line
if sys.stdin.encoding is None:
s = line.decode().encode('utf8')
else:
s = line.decode(sys.stdin.encoding).encode('utf8')
res = _quote(s, '')
res = res.replace('+', '%20')
res = res.replace('*', '%2A')
res = res.replace('%7E', '~')
return res
sortedParameters = sorted(list(parameters.items()), key=lambda items: items[0])
canonicalizedQueryString = ''
for k, v in sortedParameters:
canonicalizedQueryString += '&' + percent_encode(k) \
+ '=' + percent_encode(v)
# All aliyun API only support GET method
stringToSign = 'GET&%2F&' + percent_encode(canonicalizedQueryString[1:])
h = hmac.new(to_bytes(access_key_secret + "&"), stringToSign, sha1)
signature = base64.encodestring(h.digest()).strip()
return signature
def query(params=None):
'''
Make a web call to aliyun ECS REST API
'''
path = 'https://ecs-cn-hangzhou.aliyuncs.com'
access_key_id = config.get_cloud_config_value(
'id', get_configured_provider(), __opts__, search_global=False
)
access_key_secret = config.get_cloud_config_value(
'key', get_configured_provider(), __opts__, search_global=False
)
timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
# public interface parameters
parameters = {
'Format': 'JSON',
'Version': DEFAULT_ALIYUN_API_VERSION,
'AccessKeyId': access_key_id,
'SignatureVersion': '1.0',
'SignatureMethod': 'HMAC-SHA1',
'SignatureNonce': six.text_type(uuid.uuid1()),
'TimeStamp': timestamp,
}
# include action or function parameters
if params:
parameters.update(params)
# Calculate the string for Signature
signature = _compute_signature(parameters, access_key_secret)
parameters['Signature'] = signature
request = requests.get(path, params=parameters, verify=True)
if request.status_code != 200:
raise SaltCloudSystemExit(
'An error occurred while querying aliyun ECS. HTTP Code: {0} '
'Error: \'{1}\''.format(
request.status_code,
request.text
)
)
log.debug(request.url)
content = request.text
result = salt.utils.json.loads(content)
if 'Code' in result:
raise SaltCloudSystemExit(
pprint.pformat(result.get('Message', {}))
)
return result
def script(vm_):
'''
Return the script deployment object
'''
deploy_script = salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
return deploy_script
def show_disk(name, call=None):
'''
Show the disk details of the instance
CLI Examples:
.. code-block:: bash
salt-cloud -a show_disk aliyun myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_disks action must be called with -a or --action.'
)
ret = {}
params = {
'Action': 'DescribeInstanceDisks',
'InstanceId': name
}
items = query(params=params)
for disk in items['Disks']['Disk']:
ret[disk['DiskId']] = {}
for item in disk:
ret[disk['DiskId']][item] = six.text_type(disk[item])
return ret
def list_monitor_data(kwargs=None, call=None):
'''
Get monitor data of the instance. If instance name is
missing, will show all the instance monitor data on the region.
CLI Examples:
.. code-block:: bash
salt-cloud -f list_monitor_data aliyun
salt-cloud -f list_monitor_data aliyun name=AY14051311071990225bd
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_monitor_data must be called with -f or --function.'
)
if not isinstance(kwargs, dict):
kwargs = {}
ret = {}
params = {
'Action': 'GetMonitorData',
'RegionId': get_location()
}
if 'name' in kwargs:
params['InstanceId'] = kwargs['name']
items = query(params=params)
monitorData = items['MonitorData']
for data in monitorData['InstanceMonitorData']:
ret[data['InstanceId']] = {}
for item in data:
ret[data['InstanceId']][item] = six.text_type(data[item])
return ret
def show_instance(name, call=None):
'''
Show the details from aliyun instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
return _get_node(name)
def _get_node(name):
attempts = 5
while attempts >= 0:
try:
return list_nodes_full()[name]
except KeyError:
attempts -= 1
log.debug(
'Failed to get the data for node \'%s\'. Remaining '
'attempts: %s', name, attempts
)
# Just a little delay between attempts...
time.sleep(0.5)
raise SaltCloudNotFound(
'The specified instance {0} not found'.format(name)
)
def show_image(kwargs, call=None):
'''
Show the details from aliyun image
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_images function must be called with '
'-f or --function'
)
if not isinstance(kwargs, dict):
kwargs = {}
location = get_location()
if 'location' in kwargs:
location = kwargs['location']
params = {
'Action': 'DescribeImages',
'RegionId': location,
'ImageId': kwargs['image']
}
ret = {}
items = query(params=params)
# DescribeImages so far support input multi-image. And
# if not found certain image, the response will include
# blank image list other than 'not found' error message
if 'Code' in items or not items['Images']['Image']:
raise SaltCloudNotFound('The specified image could not be found.')
log.debug(
'Total %s image found in Region %s',
items['TotalCount'], location
)
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 destroy(name, call=None):
'''
Destroy a node.
CLI Example:
.. code-block:: bash
salt-cloud -a destroy myinstance
salt-cloud -d myinstance
'''
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']
)
instanceId = _get_node(name)['InstanceId']
# have to stop instance before del it
stop_params = {
'Action': 'StopInstance',
'InstanceId': instanceId
}
query(stop_params)
params = {
'Action': 'DeleteInstance',
'InstanceId': instanceId
}
node = query(params)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return node
|
saltstack/salt | salt/cloud/clouds/aliyun.py | list_securitygroup | python | 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 | Return a list of security group | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/aliyun.py#L387-L412 | [
"def query(params=None):\n '''\n Make a web call to aliyun ECS REST API\n '''\n path = 'https://ecs-cn-hangzhou.aliyuncs.com'\n\n access_key_id = config.get_cloud_config_value(\n 'id', get_configured_provider(), __opts__, search_global=False\n )\n access_key_secret = config.get_cloud_config_value(\n 'key', get_configured_provider(), __opts__, search_global=False\n )\n\n timestamp = time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.gmtime())\n\n # public interface parameters\n parameters = {\n 'Format': 'JSON',\n 'Version': DEFAULT_ALIYUN_API_VERSION,\n 'AccessKeyId': access_key_id,\n 'SignatureVersion': '1.0',\n 'SignatureMethod': 'HMAC-SHA1',\n 'SignatureNonce': six.text_type(uuid.uuid1()),\n 'TimeStamp': timestamp,\n }\n\n # include action or function parameters\n if params:\n parameters.update(params)\n\n # Calculate the string for Signature\n signature = _compute_signature(parameters, access_key_secret)\n parameters['Signature'] = signature\n\n request = requests.get(path, params=parameters, verify=True)\n if request.status_code != 200:\n raise SaltCloudSystemExit(\n 'An error occurred while querying aliyun ECS. HTTP Code: {0} '\n 'Error: \\'{1}\\''.format(\n request.status_code,\n request.text\n )\n )\n\n log.debug(request.url)\n\n content = request.text\n\n result = salt.utils.json.loads(content)\n if 'Code' in result:\n raise SaltCloudSystemExit(\n pprint.pformat(result.get('Message', {}))\n )\n return result\n",
"def get_location(vm_=None):\n '''\n Return the aliyun region to use, in this order:\n - CLI parameter\n - VM parameter\n - Cloud profile setting\n '''\n return __opts__.get(\n 'location',\n config.get_cloud_config_value(\n 'location',\n vm_ or get_configured_provider(),\n __opts__,\n default=DEFAULT_LOCATION,\n search_global=False\n )\n )\n"
] | # -*- coding: utf-8 -*-
'''
AliYun ECS Cloud Module
=======================
.. versionadded:: 2014.7.0
The Aliyun cloud module is used to control access to the aliyun ECS.
http://www.aliyun.com/
Use of this module requires the ``id`` and ``key`` parameter to be set.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/aliyun.conf``:
.. code-block:: yaml
my-aliyun-config:
# aliyun Access Key ID
id: wFGEwgregeqw3435gDger
# aliyun Access Key Secret
key: GDE43t43REGTrkilg43934t34qT43t4dgegerGEgg
location: cn-qingdao
driver: aliyun
:depends: requests
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import pprint
import logging
import hmac
import uuid
import sys
import base64
from hashlib import sha1
# Import Salt libs
from salt.ext.six.moves.urllib.parse import quote as _quote # pylint: disable=import-error,no-name-in-module
# Import salt cloud libs
import salt.utils.cloud
import salt.utils.data
import salt.utils.json
import salt.config as config
from salt.exceptions import (
SaltCloudNotFound,
SaltCloudSystemExit,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout
)
from salt.utils.stringutils import to_bytes
# Import 3rd-party libs
from salt.ext import six
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# Get logging started
log = logging.getLogger(__name__)
ALIYUN_LOCATIONS = {
# 'us-west-2': 'ec2_us_west_oregon',
'cn-hangzhou': 'AliYun HangZhou Region',
'cn-beijing': 'AliYun BeiJing Region',
'cn-hongkong': 'AliYun HongKong Region',
'cn-qingdao': 'AliYun QingDao Region',
'cn-shanghai': 'AliYun ShangHai Region',
'cn-shenzhen': 'AliYun ShenZheng Region',
'ap-northeast-1': 'AliYun DongJing Region',
'ap-southeast-1': 'AliYun XinJiaPo Region',
'ap-southeast-2': 'AliYun XiNi Region',
'eu-central-1': 'EU FalaKeFu Region',
'me-east-1': 'ME DiBai Region',
'us-east-1': 'US FuJiNiYa Region',
'us-west-1': 'US GuiGu Region',
}
DEFAULT_LOCATION = 'cn-hangzhou'
DEFAULT_ALIYUN_API_VERSION = '2014-05-26'
__virtualname__ = 'aliyun'
# Only load in this module if the aliyun configurations are in place
def __virtual__():
'''
Check for aliyun configurations
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('id', 'key')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'requests': HAS_REQUESTS}
)
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 get_location(vm_=None):
'''
Return the aliyun region to use, in this order:
- CLI parameter
- VM parameter
- Cloud profile setting
'''
return __opts__.get(
'location',
config.get_cloud_config_value(
'location',
vm_ or get_configured_provider(),
__opts__,
default=DEFAULT_LOCATION,
search_global=False
)
)
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_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
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
)
)
def start(name, call=None):
'''
Start a node
CLI Examples:
.. code-block:: bash
salt-cloud -a start myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Starting node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {'Action': 'StartInstance',
'InstanceId': instanceId}
result = query(params)
return result
def stop(name, force=False, call=None):
'''
Stop a node
CLI Examples:
.. code-block:: bash
salt-cloud -a stop myinstance
salt-cloud -a stop myinstance force=True
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Stopping node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {
'Action': 'StopInstance',
'InstanceId': instanceId,
'ForceStop': six.text_type(force).lower()
}
result = query(params)
return result
def reboot(name, call=None):
'''
Reboot a node
CLI Examples:
.. code-block:: bash
salt-cloud -a reboot myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Rebooting node %s', name)
instance_id = _get_node(name)['InstanceId']
params = {'Action': 'RebootInstance',
'InstanceId': instance_id}
result = query(params)
return result
def create_node(kwargs):
'''
Convenience function to make the rest api call for node creation.
'''
if not isinstance(kwargs, dict):
kwargs = {}
# Required parameters
params = {
'Action': 'CreateInstance',
'InstanceType': kwargs.get('size_id', ''),
'RegionId': kwargs.get('region_id', DEFAULT_LOCATION),
'ImageId': kwargs.get('image_id', ''),
'SecurityGroupId': kwargs.get('securitygroup_id', ''),
'InstanceName': kwargs.get('name', ''),
}
# Optional parameters'
optional = [
'InstanceName', 'InternetChargeType',
'InternetMaxBandwidthIn', 'InternetMaxBandwidthOut',
'HostName', 'Password', 'SystemDisk.Category', 'VSwitchId'
# 'DataDisk.n.Size', 'DataDisk.n.Category', 'DataDisk.n.SnapshotId'
]
for item in optional:
if item in kwargs:
params.update({item: kwargs[item]})
# invoke web call
result = query(params)
return result['InstanceId']
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'aliyun',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
kwargs = {
'name': vm_['name'],
'size_id': get_size(vm_),
'image_id': get_image(vm_),
'region_id': __get_location(vm_),
'securitygroup_id': get_securitygroup(vm_),
}
if 'vswitch_id' in vm_:
kwargs['VSwitchId'] = vm_['vswitch_id']
if 'internet_chargetype' in vm_:
kwargs['InternetChargeType'] = vm_['internet_chargetype']
if 'internet_maxbandwidthin' in vm_:
kwargs['InternetMaxBandwidthIn'] = six.text_type(vm_['internet_maxbandwidthin'])
if 'internet_maxbandwidthout' in vm_:
kwargs['InternetMaxBandwidthOut'] = six.text_type(vm_['internet_maxbandwidthOut'])
if 'hostname' in vm_:
kwargs['HostName'] = vm_['hostname']
if 'password' in vm_:
kwargs['Password'] = vm_['password']
if 'instance_name' in vm_:
kwargs['InstanceName'] = vm_['instance_name']
if 'systemdisk_category' in vm_:
kwargs['SystemDisk.Category'] = vm_['systemdisk_category']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
ret = create_node(kwargs)
except Exception as exc:
log.error(
'Error creating %s on Aliyun ECS\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: %s',
vm_['name'], six.text_type(exc),
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
# repair ip address error and start vm
time.sleep(8)
params = {'Action': 'StartInstance',
'InstanceId': ret}
query(params)
def __query_node_data(vm_name):
data = show_instance(vm_name, call='action')
if not data:
# Trigger an error in the wait_for_ip function
return False
if data.get('PublicIpAddress', None) is not None:
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_['name'],),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
if data['public_ips']:
ssh_ip = data['public_ips'][0]
elif data['private_ips']:
ssh_ip = data['private_ips'][0]
else:
log.info('No available ip:cant connect to salt')
return False
log.debug('VM %s is now running', ssh_ip)
vm_['ssh_host'] = ssh_ip
# The instance is booted and accessible, let's Salt it!
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
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'],
transport=__opts__['transport']
)
return ret
def _compute_signature(parameters, access_key_secret):
'''
Generate aliyun request signature
'''
def percent_encode(line):
if not isinstance(line, six.string_types):
return line
s = line
if sys.stdin.encoding is None:
s = line.decode().encode('utf8')
else:
s = line.decode(sys.stdin.encoding).encode('utf8')
res = _quote(s, '')
res = res.replace('+', '%20')
res = res.replace('*', '%2A')
res = res.replace('%7E', '~')
return res
sortedParameters = sorted(list(parameters.items()), key=lambda items: items[0])
canonicalizedQueryString = ''
for k, v in sortedParameters:
canonicalizedQueryString += '&' + percent_encode(k) \
+ '=' + percent_encode(v)
# All aliyun API only support GET method
stringToSign = 'GET&%2F&' + percent_encode(canonicalizedQueryString[1:])
h = hmac.new(to_bytes(access_key_secret + "&"), stringToSign, sha1)
signature = base64.encodestring(h.digest()).strip()
return signature
def query(params=None):
'''
Make a web call to aliyun ECS REST API
'''
path = 'https://ecs-cn-hangzhou.aliyuncs.com'
access_key_id = config.get_cloud_config_value(
'id', get_configured_provider(), __opts__, search_global=False
)
access_key_secret = config.get_cloud_config_value(
'key', get_configured_provider(), __opts__, search_global=False
)
timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
# public interface parameters
parameters = {
'Format': 'JSON',
'Version': DEFAULT_ALIYUN_API_VERSION,
'AccessKeyId': access_key_id,
'SignatureVersion': '1.0',
'SignatureMethod': 'HMAC-SHA1',
'SignatureNonce': six.text_type(uuid.uuid1()),
'TimeStamp': timestamp,
}
# include action or function parameters
if params:
parameters.update(params)
# Calculate the string for Signature
signature = _compute_signature(parameters, access_key_secret)
parameters['Signature'] = signature
request = requests.get(path, params=parameters, verify=True)
if request.status_code != 200:
raise SaltCloudSystemExit(
'An error occurred while querying aliyun ECS. HTTP Code: {0} '
'Error: \'{1}\''.format(
request.status_code,
request.text
)
)
log.debug(request.url)
content = request.text
result = salt.utils.json.loads(content)
if 'Code' in result:
raise SaltCloudSystemExit(
pprint.pformat(result.get('Message', {}))
)
return result
def script(vm_):
'''
Return the script deployment object
'''
deploy_script = salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
return deploy_script
def show_disk(name, call=None):
'''
Show the disk details of the instance
CLI Examples:
.. code-block:: bash
salt-cloud -a show_disk aliyun myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_disks action must be called with -a or --action.'
)
ret = {}
params = {
'Action': 'DescribeInstanceDisks',
'InstanceId': name
}
items = query(params=params)
for disk in items['Disks']['Disk']:
ret[disk['DiskId']] = {}
for item in disk:
ret[disk['DiskId']][item] = six.text_type(disk[item])
return ret
def list_monitor_data(kwargs=None, call=None):
'''
Get monitor data of the instance. If instance name is
missing, will show all the instance monitor data on the region.
CLI Examples:
.. code-block:: bash
salt-cloud -f list_monitor_data aliyun
salt-cloud -f list_monitor_data aliyun name=AY14051311071990225bd
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_monitor_data must be called with -f or --function.'
)
if not isinstance(kwargs, dict):
kwargs = {}
ret = {}
params = {
'Action': 'GetMonitorData',
'RegionId': get_location()
}
if 'name' in kwargs:
params['InstanceId'] = kwargs['name']
items = query(params=params)
monitorData = items['MonitorData']
for data in monitorData['InstanceMonitorData']:
ret[data['InstanceId']] = {}
for item in data:
ret[data['InstanceId']][item] = six.text_type(data[item])
return ret
def show_instance(name, call=None):
'''
Show the details from aliyun instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
return _get_node(name)
def _get_node(name):
attempts = 5
while attempts >= 0:
try:
return list_nodes_full()[name]
except KeyError:
attempts -= 1
log.debug(
'Failed to get the data for node \'%s\'. Remaining '
'attempts: %s', name, attempts
)
# Just a little delay between attempts...
time.sleep(0.5)
raise SaltCloudNotFound(
'The specified instance {0} not found'.format(name)
)
def show_image(kwargs, call=None):
'''
Show the details from aliyun image
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_images function must be called with '
'-f or --function'
)
if not isinstance(kwargs, dict):
kwargs = {}
location = get_location()
if 'location' in kwargs:
location = kwargs['location']
params = {
'Action': 'DescribeImages',
'RegionId': location,
'ImageId': kwargs['image']
}
ret = {}
items = query(params=params)
# DescribeImages so far support input multi-image. And
# if not found certain image, the response will include
# blank image list other than 'not found' error message
if 'Code' in items or not items['Images']['Image']:
raise SaltCloudNotFound('The specified image could not be found.')
log.debug(
'Total %s image found in Region %s',
items['TotalCount'], location
)
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 destroy(name, call=None):
'''
Destroy a node.
CLI Example:
.. code-block:: bash
salt-cloud -a destroy myinstance
salt-cloud -d myinstance
'''
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']
)
instanceId = _get_node(name)['InstanceId']
# have to stop instance before del it
stop_params = {
'Action': 'StopInstance',
'InstanceId': instanceId
}
query(stop_params)
params = {
'Action': 'DeleteInstance',
'InstanceId': instanceId
}
node = query(params)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return node
|
saltstack/salt | salt/cloud/clouds/aliyun.py | get_image | python | 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)
) | Return the image object to use | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/aliyun.py#L415-L431 | [
"def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):\n '''\n Search and return a setting in a known order:\n\n 1. In the virtual machine's configuration\n 2. In the virtual machine's profile configuration\n 3. In the virtual machine's provider configuration\n 4. In the salt cloud configuration if global searching is enabled\n 5. Return the provided default\n '''\n\n # As a last resort, return the default\n value = default\n\n if search_global is True and opts.get(name, None) is not None:\n # The setting name exists in the cloud(global) configuration\n value = deepcopy(opts[name])\n\n if vm_ and name:\n # Let's get the value from the profile, if present\n if 'profile' in vm_ and vm_['profile'] is not None:\n if name in opts['profiles'][vm_['profile']]:\n if isinstance(value, dict):\n value.update(opts['profiles'][vm_['profile']][name].copy())\n else:\n value = deepcopy(opts['profiles'][vm_['profile']][name])\n\n # Let's get the value from the provider, if present.\n if ':' in vm_['driver']:\n # The provider is defined as <provider-alias>:<driver-name>\n alias, driver = vm_['driver'].split(':')\n if alias in opts['providers'] and \\\n driver in opts['providers'][alias]:\n details = opts['providers'][alias][driver]\n if name in details:\n if isinstance(value, dict):\n value.update(details[name].copy())\n else:\n value = deepcopy(details[name])\n elif len(opts['providers'].get(vm_['driver'], ())) > 1:\n # The provider is NOT defined as <provider-alias>:<driver-name>\n # and there's more than one entry under the alias.\n # WARN the user!!!!\n log.error(\n \"The '%s' cloud provider definition has more than one \"\n 'entry. Your VM configuration should be specifying the '\n \"provider as 'driver: %s:<driver-engine>'. Since \"\n \"it's not, we're returning the first definition which \"\n 'might not be what you intended.',\n vm_['driver'], vm_['driver']\n )\n\n if vm_['driver'] in opts['providers']:\n # There's only one driver defined for this provider. This is safe.\n alias_defs = opts['providers'].get(vm_['driver'])\n provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]\n if name in provider_driver_defs:\n # The setting name exists in the VM's provider configuration.\n # Return it!\n if isinstance(value, dict):\n value.update(provider_driver_defs[name].copy())\n else:\n value = deepcopy(provider_driver_defs[name])\n\n if name and vm_ and name in vm_:\n # The setting name exists in VM configuration.\n if isinstance(vm_[name], types.GeneratorType):\n value = next(vm_[name], '')\n else:\n if isinstance(value, dict) and isinstance(vm_[name], dict):\n value.update(vm_[name].copy())\n else:\n value = deepcopy(vm_[name])\n\n return value\n",
"def avail_images(kwargs=None, call=None):\n '''\n Return a list of the images that are on the provider\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The avail_images function must be called with '\n '-f or --function, or with the --list-images option'\n )\n\n if not isinstance(kwargs, dict):\n kwargs = {}\n\n provider = get_configured_provider()\n location = provider.get('location', DEFAULT_LOCATION)\n\n if 'location' in kwargs:\n location = kwargs['location']\n\n params = {\n 'Action': 'DescribeImages',\n 'RegionId': location,\n 'PageSize': '100',\n }\n items = query(params=params)\n\n ret = {}\n for image in items['Images']['Image']:\n ret[image['ImageId']] = {}\n for item in image:\n ret[image['ImageId']][item] = six.text_type(image[item])\n\n return ret\n"
] | # -*- coding: utf-8 -*-
'''
AliYun ECS Cloud Module
=======================
.. versionadded:: 2014.7.0
The Aliyun cloud module is used to control access to the aliyun ECS.
http://www.aliyun.com/
Use of this module requires the ``id`` and ``key`` parameter to be set.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/aliyun.conf``:
.. code-block:: yaml
my-aliyun-config:
# aliyun Access Key ID
id: wFGEwgregeqw3435gDger
# aliyun Access Key Secret
key: GDE43t43REGTrkilg43934t34qT43t4dgegerGEgg
location: cn-qingdao
driver: aliyun
:depends: requests
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import pprint
import logging
import hmac
import uuid
import sys
import base64
from hashlib import sha1
# Import Salt libs
from salt.ext.six.moves.urllib.parse import quote as _quote # pylint: disable=import-error,no-name-in-module
# Import salt cloud libs
import salt.utils.cloud
import salt.utils.data
import salt.utils.json
import salt.config as config
from salt.exceptions import (
SaltCloudNotFound,
SaltCloudSystemExit,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout
)
from salt.utils.stringutils import to_bytes
# Import 3rd-party libs
from salt.ext import six
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# Get logging started
log = logging.getLogger(__name__)
ALIYUN_LOCATIONS = {
# 'us-west-2': 'ec2_us_west_oregon',
'cn-hangzhou': 'AliYun HangZhou Region',
'cn-beijing': 'AliYun BeiJing Region',
'cn-hongkong': 'AliYun HongKong Region',
'cn-qingdao': 'AliYun QingDao Region',
'cn-shanghai': 'AliYun ShangHai Region',
'cn-shenzhen': 'AliYun ShenZheng Region',
'ap-northeast-1': 'AliYun DongJing Region',
'ap-southeast-1': 'AliYun XinJiaPo Region',
'ap-southeast-2': 'AliYun XiNi Region',
'eu-central-1': 'EU FalaKeFu Region',
'me-east-1': 'ME DiBai Region',
'us-east-1': 'US FuJiNiYa Region',
'us-west-1': 'US GuiGu Region',
}
DEFAULT_LOCATION = 'cn-hangzhou'
DEFAULT_ALIYUN_API_VERSION = '2014-05-26'
__virtualname__ = 'aliyun'
# Only load in this module if the aliyun configurations are in place
def __virtual__():
'''
Check for aliyun configurations
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('id', 'key')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'requests': HAS_REQUESTS}
)
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 get_location(vm_=None):
'''
Return the aliyun region to use, in this order:
- CLI parameter
- VM parameter
- Cloud profile setting
'''
return __opts__.get(
'location',
config.get_cloud_config_value(
'location',
vm_ or get_configured_provider(),
__opts__,
default=DEFAULT_LOCATION,
search_global=False
)
)
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_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
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_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
)
)
def start(name, call=None):
'''
Start a node
CLI Examples:
.. code-block:: bash
salt-cloud -a start myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Starting node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {'Action': 'StartInstance',
'InstanceId': instanceId}
result = query(params)
return result
def stop(name, force=False, call=None):
'''
Stop a node
CLI Examples:
.. code-block:: bash
salt-cloud -a stop myinstance
salt-cloud -a stop myinstance force=True
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Stopping node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {
'Action': 'StopInstance',
'InstanceId': instanceId,
'ForceStop': six.text_type(force).lower()
}
result = query(params)
return result
def reboot(name, call=None):
'''
Reboot a node
CLI Examples:
.. code-block:: bash
salt-cloud -a reboot myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Rebooting node %s', name)
instance_id = _get_node(name)['InstanceId']
params = {'Action': 'RebootInstance',
'InstanceId': instance_id}
result = query(params)
return result
def create_node(kwargs):
'''
Convenience function to make the rest api call for node creation.
'''
if not isinstance(kwargs, dict):
kwargs = {}
# Required parameters
params = {
'Action': 'CreateInstance',
'InstanceType': kwargs.get('size_id', ''),
'RegionId': kwargs.get('region_id', DEFAULT_LOCATION),
'ImageId': kwargs.get('image_id', ''),
'SecurityGroupId': kwargs.get('securitygroup_id', ''),
'InstanceName': kwargs.get('name', ''),
}
# Optional parameters'
optional = [
'InstanceName', 'InternetChargeType',
'InternetMaxBandwidthIn', 'InternetMaxBandwidthOut',
'HostName', 'Password', 'SystemDisk.Category', 'VSwitchId'
# 'DataDisk.n.Size', 'DataDisk.n.Category', 'DataDisk.n.SnapshotId'
]
for item in optional:
if item in kwargs:
params.update({item: kwargs[item]})
# invoke web call
result = query(params)
return result['InstanceId']
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'aliyun',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
kwargs = {
'name': vm_['name'],
'size_id': get_size(vm_),
'image_id': get_image(vm_),
'region_id': __get_location(vm_),
'securitygroup_id': get_securitygroup(vm_),
}
if 'vswitch_id' in vm_:
kwargs['VSwitchId'] = vm_['vswitch_id']
if 'internet_chargetype' in vm_:
kwargs['InternetChargeType'] = vm_['internet_chargetype']
if 'internet_maxbandwidthin' in vm_:
kwargs['InternetMaxBandwidthIn'] = six.text_type(vm_['internet_maxbandwidthin'])
if 'internet_maxbandwidthout' in vm_:
kwargs['InternetMaxBandwidthOut'] = six.text_type(vm_['internet_maxbandwidthOut'])
if 'hostname' in vm_:
kwargs['HostName'] = vm_['hostname']
if 'password' in vm_:
kwargs['Password'] = vm_['password']
if 'instance_name' in vm_:
kwargs['InstanceName'] = vm_['instance_name']
if 'systemdisk_category' in vm_:
kwargs['SystemDisk.Category'] = vm_['systemdisk_category']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
ret = create_node(kwargs)
except Exception as exc:
log.error(
'Error creating %s on Aliyun ECS\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: %s',
vm_['name'], six.text_type(exc),
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
# repair ip address error and start vm
time.sleep(8)
params = {'Action': 'StartInstance',
'InstanceId': ret}
query(params)
def __query_node_data(vm_name):
data = show_instance(vm_name, call='action')
if not data:
# Trigger an error in the wait_for_ip function
return False
if data.get('PublicIpAddress', None) is not None:
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_['name'],),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
if data['public_ips']:
ssh_ip = data['public_ips'][0]
elif data['private_ips']:
ssh_ip = data['private_ips'][0]
else:
log.info('No available ip:cant connect to salt')
return False
log.debug('VM %s is now running', ssh_ip)
vm_['ssh_host'] = ssh_ip
# The instance is booted and accessible, let's Salt it!
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
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'],
transport=__opts__['transport']
)
return ret
def _compute_signature(parameters, access_key_secret):
'''
Generate aliyun request signature
'''
def percent_encode(line):
if not isinstance(line, six.string_types):
return line
s = line
if sys.stdin.encoding is None:
s = line.decode().encode('utf8')
else:
s = line.decode(sys.stdin.encoding).encode('utf8')
res = _quote(s, '')
res = res.replace('+', '%20')
res = res.replace('*', '%2A')
res = res.replace('%7E', '~')
return res
sortedParameters = sorted(list(parameters.items()), key=lambda items: items[0])
canonicalizedQueryString = ''
for k, v in sortedParameters:
canonicalizedQueryString += '&' + percent_encode(k) \
+ '=' + percent_encode(v)
# All aliyun API only support GET method
stringToSign = 'GET&%2F&' + percent_encode(canonicalizedQueryString[1:])
h = hmac.new(to_bytes(access_key_secret + "&"), stringToSign, sha1)
signature = base64.encodestring(h.digest()).strip()
return signature
def query(params=None):
'''
Make a web call to aliyun ECS REST API
'''
path = 'https://ecs-cn-hangzhou.aliyuncs.com'
access_key_id = config.get_cloud_config_value(
'id', get_configured_provider(), __opts__, search_global=False
)
access_key_secret = config.get_cloud_config_value(
'key', get_configured_provider(), __opts__, search_global=False
)
timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
# public interface parameters
parameters = {
'Format': 'JSON',
'Version': DEFAULT_ALIYUN_API_VERSION,
'AccessKeyId': access_key_id,
'SignatureVersion': '1.0',
'SignatureMethod': 'HMAC-SHA1',
'SignatureNonce': six.text_type(uuid.uuid1()),
'TimeStamp': timestamp,
}
# include action or function parameters
if params:
parameters.update(params)
# Calculate the string for Signature
signature = _compute_signature(parameters, access_key_secret)
parameters['Signature'] = signature
request = requests.get(path, params=parameters, verify=True)
if request.status_code != 200:
raise SaltCloudSystemExit(
'An error occurred while querying aliyun ECS. HTTP Code: {0} '
'Error: \'{1}\''.format(
request.status_code,
request.text
)
)
log.debug(request.url)
content = request.text
result = salt.utils.json.loads(content)
if 'Code' in result:
raise SaltCloudSystemExit(
pprint.pformat(result.get('Message', {}))
)
return result
def script(vm_):
'''
Return the script deployment object
'''
deploy_script = salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
return deploy_script
def show_disk(name, call=None):
'''
Show the disk details of the instance
CLI Examples:
.. code-block:: bash
salt-cloud -a show_disk aliyun myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_disks action must be called with -a or --action.'
)
ret = {}
params = {
'Action': 'DescribeInstanceDisks',
'InstanceId': name
}
items = query(params=params)
for disk in items['Disks']['Disk']:
ret[disk['DiskId']] = {}
for item in disk:
ret[disk['DiskId']][item] = six.text_type(disk[item])
return ret
def list_monitor_data(kwargs=None, call=None):
'''
Get monitor data of the instance. If instance name is
missing, will show all the instance monitor data on the region.
CLI Examples:
.. code-block:: bash
salt-cloud -f list_monitor_data aliyun
salt-cloud -f list_monitor_data aliyun name=AY14051311071990225bd
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_monitor_data must be called with -f or --function.'
)
if not isinstance(kwargs, dict):
kwargs = {}
ret = {}
params = {
'Action': 'GetMonitorData',
'RegionId': get_location()
}
if 'name' in kwargs:
params['InstanceId'] = kwargs['name']
items = query(params=params)
monitorData = items['MonitorData']
for data in monitorData['InstanceMonitorData']:
ret[data['InstanceId']] = {}
for item in data:
ret[data['InstanceId']][item] = six.text_type(data[item])
return ret
def show_instance(name, call=None):
'''
Show the details from aliyun instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
return _get_node(name)
def _get_node(name):
attempts = 5
while attempts >= 0:
try:
return list_nodes_full()[name]
except KeyError:
attempts -= 1
log.debug(
'Failed to get the data for node \'%s\'. Remaining '
'attempts: %s', name, attempts
)
# Just a little delay between attempts...
time.sleep(0.5)
raise SaltCloudNotFound(
'The specified instance {0} not found'.format(name)
)
def show_image(kwargs, call=None):
'''
Show the details from aliyun image
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_images function must be called with '
'-f or --function'
)
if not isinstance(kwargs, dict):
kwargs = {}
location = get_location()
if 'location' in kwargs:
location = kwargs['location']
params = {
'Action': 'DescribeImages',
'RegionId': location,
'ImageId': kwargs['image']
}
ret = {}
items = query(params=params)
# DescribeImages so far support input multi-image. And
# if not found certain image, the response will include
# blank image list other than 'not found' error message
if 'Code' in items or not items['Images']['Image']:
raise SaltCloudNotFound('The specified image could not be found.')
log.debug(
'Total %s image found in Region %s',
items['TotalCount'], location
)
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 destroy(name, call=None):
'''
Destroy a node.
CLI Example:
.. code-block:: bash
salt-cloud -a destroy myinstance
salt-cloud -d myinstance
'''
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']
)
instanceId = _get_node(name)['InstanceId']
# have to stop instance before del it
stop_params = {
'Action': 'StopInstance',
'InstanceId': instanceId
}
query(stop_params)
params = {
'Action': 'DeleteInstance',
'InstanceId': instanceId
}
node = query(params)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return node
|
saltstack/salt | salt/cloud/clouds/aliyun.py | get_securitygroup | python | 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)
) | Return the security group | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/aliyun.py#L434-L451 | [
"def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):\n '''\n Search and return a setting in a known order:\n\n 1. In the virtual machine's configuration\n 2. In the virtual machine's profile configuration\n 3. In the virtual machine's provider configuration\n 4. In the salt cloud configuration if global searching is enabled\n 5. Return the provided default\n '''\n\n # As a last resort, return the default\n value = default\n\n if search_global is True and opts.get(name, None) is not None:\n # The setting name exists in the cloud(global) configuration\n value = deepcopy(opts[name])\n\n if vm_ and name:\n # Let's get the value from the profile, if present\n if 'profile' in vm_ and vm_['profile'] is not None:\n if name in opts['profiles'][vm_['profile']]:\n if isinstance(value, dict):\n value.update(opts['profiles'][vm_['profile']][name].copy())\n else:\n value = deepcopy(opts['profiles'][vm_['profile']][name])\n\n # Let's get the value from the provider, if present.\n if ':' in vm_['driver']:\n # The provider is defined as <provider-alias>:<driver-name>\n alias, driver = vm_['driver'].split(':')\n if alias in opts['providers'] and \\\n driver in opts['providers'][alias]:\n details = opts['providers'][alias][driver]\n if name in details:\n if isinstance(value, dict):\n value.update(details[name].copy())\n else:\n value = deepcopy(details[name])\n elif len(opts['providers'].get(vm_['driver'], ())) > 1:\n # The provider is NOT defined as <provider-alias>:<driver-name>\n # and there's more than one entry under the alias.\n # WARN the user!!!!\n log.error(\n \"The '%s' cloud provider definition has more than one \"\n 'entry. Your VM configuration should be specifying the '\n \"provider as 'driver: %s:<driver-engine>'. Since \"\n \"it's not, we're returning the first definition which \"\n 'might not be what you intended.',\n vm_['driver'], vm_['driver']\n )\n\n if vm_['driver'] in opts['providers']:\n # There's only one driver defined for this provider. This is safe.\n alias_defs = opts['providers'].get(vm_['driver'])\n provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]\n if name in provider_driver_defs:\n # The setting name exists in the VM's provider configuration.\n # Return it!\n if isinstance(value, dict):\n value.update(provider_driver_defs[name].copy())\n else:\n value = deepcopy(provider_driver_defs[name])\n\n if name and vm_ and name in vm_:\n # The setting name exists in VM configuration.\n if isinstance(vm_[name], types.GeneratorType):\n value = next(vm_[name], '')\n else:\n if isinstance(value, dict) and isinstance(vm_[name], dict):\n value.update(vm_[name].copy())\n else:\n value = deepcopy(vm_[name])\n\n return value\n",
"def list_securitygroup(call=None):\n '''\n Return a list of security group\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The list_nodes function must be called with -f or --function.'\n )\n\n params = {\n 'Action': 'DescribeSecurityGroups',\n 'RegionId': get_location(),\n 'PageSize': '50',\n }\n\n result = query(params)\n if 'Code' in result:\n return {}\n\n ret = {}\n for sg in result['SecurityGroups']['SecurityGroup']:\n ret[sg['SecurityGroupId']] = {}\n for item in sg:\n ret[sg['SecurityGroupId']][item] = sg[item]\n\n return ret\n"
] | # -*- coding: utf-8 -*-
'''
AliYun ECS Cloud Module
=======================
.. versionadded:: 2014.7.0
The Aliyun cloud module is used to control access to the aliyun ECS.
http://www.aliyun.com/
Use of this module requires the ``id`` and ``key`` parameter to be set.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/aliyun.conf``:
.. code-block:: yaml
my-aliyun-config:
# aliyun Access Key ID
id: wFGEwgregeqw3435gDger
# aliyun Access Key Secret
key: GDE43t43REGTrkilg43934t34qT43t4dgegerGEgg
location: cn-qingdao
driver: aliyun
:depends: requests
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import pprint
import logging
import hmac
import uuid
import sys
import base64
from hashlib import sha1
# Import Salt libs
from salt.ext.six.moves.urllib.parse import quote as _quote # pylint: disable=import-error,no-name-in-module
# Import salt cloud libs
import salt.utils.cloud
import salt.utils.data
import salt.utils.json
import salt.config as config
from salt.exceptions import (
SaltCloudNotFound,
SaltCloudSystemExit,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout
)
from salt.utils.stringutils import to_bytes
# Import 3rd-party libs
from salt.ext import six
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# Get logging started
log = logging.getLogger(__name__)
ALIYUN_LOCATIONS = {
# 'us-west-2': 'ec2_us_west_oregon',
'cn-hangzhou': 'AliYun HangZhou Region',
'cn-beijing': 'AliYun BeiJing Region',
'cn-hongkong': 'AliYun HongKong Region',
'cn-qingdao': 'AliYun QingDao Region',
'cn-shanghai': 'AliYun ShangHai Region',
'cn-shenzhen': 'AliYun ShenZheng Region',
'ap-northeast-1': 'AliYun DongJing Region',
'ap-southeast-1': 'AliYun XinJiaPo Region',
'ap-southeast-2': 'AliYun XiNi Region',
'eu-central-1': 'EU FalaKeFu Region',
'me-east-1': 'ME DiBai Region',
'us-east-1': 'US FuJiNiYa Region',
'us-west-1': 'US GuiGu Region',
}
DEFAULT_LOCATION = 'cn-hangzhou'
DEFAULT_ALIYUN_API_VERSION = '2014-05-26'
__virtualname__ = 'aliyun'
# Only load in this module if the aliyun configurations are in place
def __virtual__():
'''
Check for aliyun configurations
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('id', 'key')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'requests': HAS_REQUESTS}
)
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 get_location(vm_=None):
'''
Return the aliyun region to use, in this order:
- CLI parameter
- VM parameter
- Cloud profile setting
'''
return __opts__.get(
'location',
config.get_cloud_config_value(
'location',
vm_ or get_configured_provider(),
__opts__,
default=DEFAULT_LOCATION,
search_global=False
)
)
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_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
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_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
)
)
def start(name, call=None):
'''
Start a node
CLI Examples:
.. code-block:: bash
salt-cloud -a start myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Starting node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {'Action': 'StartInstance',
'InstanceId': instanceId}
result = query(params)
return result
def stop(name, force=False, call=None):
'''
Stop a node
CLI Examples:
.. code-block:: bash
salt-cloud -a stop myinstance
salt-cloud -a stop myinstance force=True
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Stopping node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {
'Action': 'StopInstance',
'InstanceId': instanceId,
'ForceStop': six.text_type(force).lower()
}
result = query(params)
return result
def reboot(name, call=None):
'''
Reboot a node
CLI Examples:
.. code-block:: bash
salt-cloud -a reboot myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Rebooting node %s', name)
instance_id = _get_node(name)['InstanceId']
params = {'Action': 'RebootInstance',
'InstanceId': instance_id}
result = query(params)
return result
def create_node(kwargs):
'''
Convenience function to make the rest api call for node creation.
'''
if not isinstance(kwargs, dict):
kwargs = {}
# Required parameters
params = {
'Action': 'CreateInstance',
'InstanceType': kwargs.get('size_id', ''),
'RegionId': kwargs.get('region_id', DEFAULT_LOCATION),
'ImageId': kwargs.get('image_id', ''),
'SecurityGroupId': kwargs.get('securitygroup_id', ''),
'InstanceName': kwargs.get('name', ''),
}
# Optional parameters'
optional = [
'InstanceName', 'InternetChargeType',
'InternetMaxBandwidthIn', 'InternetMaxBandwidthOut',
'HostName', 'Password', 'SystemDisk.Category', 'VSwitchId'
# 'DataDisk.n.Size', 'DataDisk.n.Category', 'DataDisk.n.SnapshotId'
]
for item in optional:
if item in kwargs:
params.update({item: kwargs[item]})
# invoke web call
result = query(params)
return result['InstanceId']
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'aliyun',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
kwargs = {
'name': vm_['name'],
'size_id': get_size(vm_),
'image_id': get_image(vm_),
'region_id': __get_location(vm_),
'securitygroup_id': get_securitygroup(vm_),
}
if 'vswitch_id' in vm_:
kwargs['VSwitchId'] = vm_['vswitch_id']
if 'internet_chargetype' in vm_:
kwargs['InternetChargeType'] = vm_['internet_chargetype']
if 'internet_maxbandwidthin' in vm_:
kwargs['InternetMaxBandwidthIn'] = six.text_type(vm_['internet_maxbandwidthin'])
if 'internet_maxbandwidthout' in vm_:
kwargs['InternetMaxBandwidthOut'] = six.text_type(vm_['internet_maxbandwidthOut'])
if 'hostname' in vm_:
kwargs['HostName'] = vm_['hostname']
if 'password' in vm_:
kwargs['Password'] = vm_['password']
if 'instance_name' in vm_:
kwargs['InstanceName'] = vm_['instance_name']
if 'systemdisk_category' in vm_:
kwargs['SystemDisk.Category'] = vm_['systemdisk_category']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
ret = create_node(kwargs)
except Exception as exc:
log.error(
'Error creating %s on Aliyun ECS\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: %s',
vm_['name'], six.text_type(exc),
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
# repair ip address error and start vm
time.sleep(8)
params = {'Action': 'StartInstance',
'InstanceId': ret}
query(params)
def __query_node_data(vm_name):
data = show_instance(vm_name, call='action')
if not data:
# Trigger an error in the wait_for_ip function
return False
if data.get('PublicIpAddress', None) is not None:
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_['name'],),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
if data['public_ips']:
ssh_ip = data['public_ips'][0]
elif data['private_ips']:
ssh_ip = data['private_ips'][0]
else:
log.info('No available ip:cant connect to salt')
return False
log.debug('VM %s is now running', ssh_ip)
vm_['ssh_host'] = ssh_ip
# The instance is booted and accessible, let's Salt it!
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
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'],
transport=__opts__['transport']
)
return ret
def _compute_signature(parameters, access_key_secret):
'''
Generate aliyun request signature
'''
def percent_encode(line):
if not isinstance(line, six.string_types):
return line
s = line
if sys.stdin.encoding is None:
s = line.decode().encode('utf8')
else:
s = line.decode(sys.stdin.encoding).encode('utf8')
res = _quote(s, '')
res = res.replace('+', '%20')
res = res.replace('*', '%2A')
res = res.replace('%7E', '~')
return res
sortedParameters = sorted(list(parameters.items()), key=lambda items: items[0])
canonicalizedQueryString = ''
for k, v in sortedParameters:
canonicalizedQueryString += '&' + percent_encode(k) \
+ '=' + percent_encode(v)
# All aliyun API only support GET method
stringToSign = 'GET&%2F&' + percent_encode(canonicalizedQueryString[1:])
h = hmac.new(to_bytes(access_key_secret + "&"), stringToSign, sha1)
signature = base64.encodestring(h.digest()).strip()
return signature
def query(params=None):
'''
Make a web call to aliyun ECS REST API
'''
path = 'https://ecs-cn-hangzhou.aliyuncs.com'
access_key_id = config.get_cloud_config_value(
'id', get_configured_provider(), __opts__, search_global=False
)
access_key_secret = config.get_cloud_config_value(
'key', get_configured_provider(), __opts__, search_global=False
)
timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
# public interface parameters
parameters = {
'Format': 'JSON',
'Version': DEFAULT_ALIYUN_API_VERSION,
'AccessKeyId': access_key_id,
'SignatureVersion': '1.0',
'SignatureMethod': 'HMAC-SHA1',
'SignatureNonce': six.text_type(uuid.uuid1()),
'TimeStamp': timestamp,
}
# include action or function parameters
if params:
parameters.update(params)
# Calculate the string for Signature
signature = _compute_signature(parameters, access_key_secret)
parameters['Signature'] = signature
request = requests.get(path, params=parameters, verify=True)
if request.status_code != 200:
raise SaltCloudSystemExit(
'An error occurred while querying aliyun ECS. HTTP Code: {0} '
'Error: \'{1}\''.format(
request.status_code,
request.text
)
)
log.debug(request.url)
content = request.text
result = salt.utils.json.loads(content)
if 'Code' in result:
raise SaltCloudSystemExit(
pprint.pformat(result.get('Message', {}))
)
return result
def script(vm_):
'''
Return the script deployment object
'''
deploy_script = salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
return deploy_script
def show_disk(name, call=None):
'''
Show the disk details of the instance
CLI Examples:
.. code-block:: bash
salt-cloud -a show_disk aliyun myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_disks action must be called with -a or --action.'
)
ret = {}
params = {
'Action': 'DescribeInstanceDisks',
'InstanceId': name
}
items = query(params=params)
for disk in items['Disks']['Disk']:
ret[disk['DiskId']] = {}
for item in disk:
ret[disk['DiskId']][item] = six.text_type(disk[item])
return ret
def list_monitor_data(kwargs=None, call=None):
'''
Get monitor data of the instance. If instance name is
missing, will show all the instance monitor data on the region.
CLI Examples:
.. code-block:: bash
salt-cloud -f list_monitor_data aliyun
salt-cloud -f list_monitor_data aliyun name=AY14051311071990225bd
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_monitor_data must be called with -f or --function.'
)
if not isinstance(kwargs, dict):
kwargs = {}
ret = {}
params = {
'Action': 'GetMonitorData',
'RegionId': get_location()
}
if 'name' in kwargs:
params['InstanceId'] = kwargs['name']
items = query(params=params)
monitorData = items['MonitorData']
for data in monitorData['InstanceMonitorData']:
ret[data['InstanceId']] = {}
for item in data:
ret[data['InstanceId']][item] = six.text_type(data[item])
return ret
def show_instance(name, call=None):
'''
Show the details from aliyun instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
return _get_node(name)
def _get_node(name):
attempts = 5
while attempts >= 0:
try:
return list_nodes_full()[name]
except KeyError:
attempts -= 1
log.debug(
'Failed to get the data for node \'%s\'. Remaining '
'attempts: %s', name, attempts
)
# Just a little delay between attempts...
time.sleep(0.5)
raise SaltCloudNotFound(
'The specified instance {0} not found'.format(name)
)
def show_image(kwargs, call=None):
'''
Show the details from aliyun image
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_images function must be called with '
'-f or --function'
)
if not isinstance(kwargs, dict):
kwargs = {}
location = get_location()
if 'location' in kwargs:
location = kwargs['location']
params = {
'Action': 'DescribeImages',
'RegionId': location,
'ImageId': kwargs['image']
}
ret = {}
items = query(params=params)
# DescribeImages so far support input multi-image. And
# if not found certain image, the response will include
# blank image list other than 'not found' error message
if 'Code' in items or not items['Images']['Image']:
raise SaltCloudNotFound('The specified image could not be found.')
log.debug(
'Total %s image found in Region %s',
items['TotalCount'], location
)
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 destroy(name, call=None):
'''
Destroy a node.
CLI Example:
.. code-block:: bash
salt-cloud -a destroy myinstance
salt-cloud -d myinstance
'''
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']
)
instanceId = _get_node(name)['InstanceId']
# have to stop instance before del it
stop_params = {
'Action': 'StopInstance',
'InstanceId': instanceId
}
query(stop_params)
params = {
'Action': 'DeleteInstance',
'InstanceId': instanceId
}
node = query(params)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return node
|
saltstack/salt | salt/cloud/clouds/aliyun.py | get_size | python | 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)
) | Return the VM's size. Used by create_node(). | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/aliyun.py#L454-L471 | [
"def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):\n '''\n Search and return a setting in a known order:\n\n 1. In the virtual machine's configuration\n 2. In the virtual machine's profile configuration\n 3. In the virtual machine's provider configuration\n 4. In the salt cloud configuration if global searching is enabled\n 5. Return the provided default\n '''\n\n # As a last resort, return the default\n value = default\n\n if search_global is True and opts.get(name, None) is not None:\n # The setting name exists in the cloud(global) configuration\n value = deepcopy(opts[name])\n\n if vm_ and name:\n # Let's get the value from the profile, if present\n if 'profile' in vm_ and vm_['profile'] is not None:\n if name in opts['profiles'][vm_['profile']]:\n if isinstance(value, dict):\n value.update(opts['profiles'][vm_['profile']][name].copy())\n else:\n value = deepcopy(opts['profiles'][vm_['profile']][name])\n\n # Let's get the value from the provider, if present.\n if ':' in vm_['driver']:\n # The provider is defined as <provider-alias>:<driver-name>\n alias, driver = vm_['driver'].split(':')\n if alias in opts['providers'] and \\\n driver in opts['providers'][alias]:\n details = opts['providers'][alias][driver]\n if name in details:\n if isinstance(value, dict):\n value.update(details[name].copy())\n else:\n value = deepcopy(details[name])\n elif len(opts['providers'].get(vm_['driver'], ())) > 1:\n # The provider is NOT defined as <provider-alias>:<driver-name>\n # and there's more than one entry under the alias.\n # WARN the user!!!!\n log.error(\n \"The '%s' cloud provider definition has more than one \"\n 'entry. Your VM configuration should be specifying the '\n \"provider as 'driver: %s:<driver-engine>'. Since \"\n \"it's not, we're returning the first definition which \"\n 'might not be what you intended.',\n vm_['driver'], vm_['driver']\n )\n\n if vm_['driver'] in opts['providers']:\n # There's only one driver defined for this provider. This is safe.\n alias_defs = opts['providers'].get(vm_['driver'])\n provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]\n if name in provider_driver_defs:\n # The setting name exists in the VM's provider configuration.\n # Return it!\n if isinstance(value, dict):\n value.update(provider_driver_defs[name].copy())\n else:\n value = deepcopy(provider_driver_defs[name])\n\n if name and vm_ and name in vm_:\n # The setting name exists in VM configuration.\n if isinstance(vm_[name], types.GeneratorType):\n value = next(vm_[name], '')\n else:\n if isinstance(value, dict) and isinstance(vm_[name], dict):\n value.update(vm_[name].copy())\n else:\n value = deepcopy(vm_[name])\n\n return value\n",
"def avail_sizes(call=None):\n '''\n Return a list of the image sizes that are on the provider\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The avail_sizes function must be called with '\n '-f or --function, or with the --list-sizes option'\n )\n\n params = {'Action': 'DescribeInstanceTypes'}\n items = query(params=params)\n\n ret = {}\n for image in items['InstanceTypes']['InstanceType']:\n ret[image['InstanceTypeId']] = {}\n for item in image:\n ret[image['InstanceTypeId']][item] = six.text_type(image[item])\n\n return ret\n"
] | # -*- coding: utf-8 -*-
'''
AliYun ECS Cloud Module
=======================
.. versionadded:: 2014.7.0
The Aliyun cloud module is used to control access to the aliyun ECS.
http://www.aliyun.com/
Use of this module requires the ``id`` and ``key`` parameter to be set.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/aliyun.conf``:
.. code-block:: yaml
my-aliyun-config:
# aliyun Access Key ID
id: wFGEwgregeqw3435gDger
# aliyun Access Key Secret
key: GDE43t43REGTrkilg43934t34qT43t4dgegerGEgg
location: cn-qingdao
driver: aliyun
:depends: requests
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import pprint
import logging
import hmac
import uuid
import sys
import base64
from hashlib import sha1
# Import Salt libs
from salt.ext.six.moves.urllib.parse import quote as _quote # pylint: disable=import-error,no-name-in-module
# Import salt cloud libs
import salt.utils.cloud
import salt.utils.data
import salt.utils.json
import salt.config as config
from salt.exceptions import (
SaltCloudNotFound,
SaltCloudSystemExit,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout
)
from salt.utils.stringutils import to_bytes
# Import 3rd-party libs
from salt.ext import six
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# Get logging started
log = logging.getLogger(__name__)
ALIYUN_LOCATIONS = {
# 'us-west-2': 'ec2_us_west_oregon',
'cn-hangzhou': 'AliYun HangZhou Region',
'cn-beijing': 'AliYun BeiJing Region',
'cn-hongkong': 'AliYun HongKong Region',
'cn-qingdao': 'AliYun QingDao Region',
'cn-shanghai': 'AliYun ShangHai Region',
'cn-shenzhen': 'AliYun ShenZheng Region',
'ap-northeast-1': 'AliYun DongJing Region',
'ap-southeast-1': 'AliYun XinJiaPo Region',
'ap-southeast-2': 'AliYun XiNi Region',
'eu-central-1': 'EU FalaKeFu Region',
'me-east-1': 'ME DiBai Region',
'us-east-1': 'US FuJiNiYa Region',
'us-west-1': 'US GuiGu Region',
}
DEFAULT_LOCATION = 'cn-hangzhou'
DEFAULT_ALIYUN_API_VERSION = '2014-05-26'
__virtualname__ = 'aliyun'
# Only load in this module if the aliyun configurations are in place
def __virtual__():
'''
Check for aliyun configurations
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('id', 'key')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'requests': HAS_REQUESTS}
)
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 get_location(vm_=None):
'''
Return the aliyun region to use, in this order:
- CLI parameter
- VM parameter
- Cloud profile setting
'''
return __opts__.get(
'location',
config.get_cloud_config_value(
'location',
vm_ or get_configured_provider(),
__opts__,
default=DEFAULT_LOCATION,
search_global=False
)
)
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_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
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_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
)
)
def start(name, call=None):
'''
Start a node
CLI Examples:
.. code-block:: bash
salt-cloud -a start myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Starting node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {'Action': 'StartInstance',
'InstanceId': instanceId}
result = query(params)
return result
def stop(name, force=False, call=None):
'''
Stop a node
CLI Examples:
.. code-block:: bash
salt-cloud -a stop myinstance
salt-cloud -a stop myinstance force=True
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Stopping node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {
'Action': 'StopInstance',
'InstanceId': instanceId,
'ForceStop': six.text_type(force).lower()
}
result = query(params)
return result
def reboot(name, call=None):
'''
Reboot a node
CLI Examples:
.. code-block:: bash
salt-cloud -a reboot myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Rebooting node %s', name)
instance_id = _get_node(name)['InstanceId']
params = {'Action': 'RebootInstance',
'InstanceId': instance_id}
result = query(params)
return result
def create_node(kwargs):
'''
Convenience function to make the rest api call for node creation.
'''
if not isinstance(kwargs, dict):
kwargs = {}
# Required parameters
params = {
'Action': 'CreateInstance',
'InstanceType': kwargs.get('size_id', ''),
'RegionId': kwargs.get('region_id', DEFAULT_LOCATION),
'ImageId': kwargs.get('image_id', ''),
'SecurityGroupId': kwargs.get('securitygroup_id', ''),
'InstanceName': kwargs.get('name', ''),
}
# Optional parameters'
optional = [
'InstanceName', 'InternetChargeType',
'InternetMaxBandwidthIn', 'InternetMaxBandwidthOut',
'HostName', 'Password', 'SystemDisk.Category', 'VSwitchId'
# 'DataDisk.n.Size', 'DataDisk.n.Category', 'DataDisk.n.SnapshotId'
]
for item in optional:
if item in kwargs:
params.update({item: kwargs[item]})
# invoke web call
result = query(params)
return result['InstanceId']
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'aliyun',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
kwargs = {
'name': vm_['name'],
'size_id': get_size(vm_),
'image_id': get_image(vm_),
'region_id': __get_location(vm_),
'securitygroup_id': get_securitygroup(vm_),
}
if 'vswitch_id' in vm_:
kwargs['VSwitchId'] = vm_['vswitch_id']
if 'internet_chargetype' in vm_:
kwargs['InternetChargeType'] = vm_['internet_chargetype']
if 'internet_maxbandwidthin' in vm_:
kwargs['InternetMaxBandwidthIn'] = six.text_type(vm_['internet_maxbandwidthin'])
if 'internet_maxbandwidthout' in vm_:
kwargs['InternetMaxBandwidthOut'] = six.text_type(vm_['internet_maxbandwidthOut'])
if 'hostname' in vm_:
kwargs['HostName'] = vm_['hostname']
if 'password' in vm_:
kwargs['Password'] = vm_['password']
if 'instance_name' in vm_:
kwargs['InstanceName'] = vm_['instance_name']
if 'systemdisk_category' in vm_:
kwargs['SystemDisk.Category'] = vm_['systemdisk_category']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
ret = create_node(kwargs)
except Exception as exc:
log.error(
'Error creating %s on Aliyun ECS\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: %s',
vm_['name'], six.text_type(exc),
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
# repair ip address error and start vm
time.sleep(8)
params = {'Action': 'StartInstance',
'InstanceId': ret}
query(params)
def __query_node_data(vm_name):
data = show_instance(vm_name, call='action')
if not data:
# Trigger an error in the wait_for_ip function
return False
if data.get('PublicIpAddress', None) is not None:
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_['name'],),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
if data['public_ips']:
ssh_ip = data['public_ips'][0]
elif data['private_ips']:
ssh_ip = data['private_ips'][0]
else:
log.info('No available ip:cant connect to salt')
return False
log.debug('VM %s is now running', ssh_ip)
vm_['ssh_host'] = ssh_ip
# The instance is booted and accessible, let's Salt it!
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
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'],
transport=__opts__['transport']
)
return ret
def _compute_signature(parameters, access_key_secret):
'''
Generate aliyun request signature
'''
def percent_encode(line):
if not isinstance(line, six.string_types):
return line
s = line
if sys.stdin.encoding is None:
s = line.decode().encode('utf8')
else:
s = line.decode(sys.stdin.encoding).encode('utf8')
res = _quote(s, '')
res = res.replace('+', '%20')
res = res.replace('*', '%2A')
res = res.replace('%7E', '~')
return res
sortedParameters = sorted(list(parameters.items()), key=lambda items: items[0])
canonicalizedQueryString = ''
for k, v in sortedParameters:
canonicalizedQueryString += '&' + percent_encode(k) \
+ '=' + percent_encode(v)
# All aliyun API only support GET method
stringToSign = 'GET&%2F&' + percent_encode(canonicalizedQueryString[1:])
h = hmac.new(to_bytes(access_key_secret + "&"), stringToSign, sha1)
signature = base64.encodestring(h.digest()).strip()
return signature
def query(params=None):
'''
Make a web call to aliyun ECS REST API
'''
path = 'https://ecs-cn-hangzhou.aliyuncs.com'
access_key_id = config.get_cloud_config_value(
'id', get_configured_provider(), __opts__, search_global=False
)
access_key_secret = config.get_cloud_config_value(
'key', get_configured_provider(), __opts__, search_global=False
)
timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
# public interface parameters
parameters = {
'Format': 'JSON',
'Version': DEFAULT_ALIYUN_API_VERSION,
'AccessKeyId': access_key_id,
'SignatureVersion': '1.0',
'SignatureMethod': 'HMAC-SHA1',
'SignatureNonce': six.text_type(uuid.uuid1()),
'TimeStamp': timestamp,
}
# include action or function parameters
if params:
parameters.update(params)
# Calculate the string for Signature
signature = _compute_signature(parameters, access_key_secret)
parameters['Signature'] = signature
request = requests.get(path, params=parameters, verify=True)
if request.status_code != 200:
raise SaltCloudSystemExit(
'An error occurred while querying aliyun ECS. HTTP Code: {0} '
'Error: \'{1}\''.format(
request.status_code,
request.text
)
)
log.debug(request.url)
content = request.text
result = salt.utils.json.loads(content)
if 'Code' in result:
raise SaltCloudSystemExit(
pprint.pformat(result.get('Message', {}))
)
return result
def script(vm_):
'''
Return the script deployment object
'''
deploy_script = salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
return deploy_script
def show_disk(name, call=None):
'''
Show the disk details of the instance
CLI Examples:
.. code-block:: bash
salt-cloud -a show_disk aliyun myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_disks action must be called with -a or --action.'
)
ret = {}
params = {
'Action': 'DescribeInstanceDisks',
'InstanceId': name
}
items = query(params=params)
for disk in items['Disks']['Disk']:
ret[disk['DiskId']] = {}
for item in disk:
ret[disk['DiskId']][item] = six.text_type(disk[item])
return ret
def list_monitor_data(kwargs=None, call=None):
'''
Get monitor data of the instance. If instance name is
missing, will show all the instance monitor data on the region.
CLI Examples:
.. code-block:: bash
salt-cloud -f list_monitor_data aliyun
salt-cloud -f list_monitor_data aliyun name=AY14051311071990225bd
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_monitor_data must be called with -f or --function.'
)
if not isinstance(kwargs, dict):
kwargs = {}
ret = {}
params = {
'Action': 'GetMonitorData',
'RegionId': get_location()
}
if 'name' in kwargs:
params['InstanceId'] = kwargs['name']
items = query(params=params)
monitorData = items['MonitorData']
for data in monitorData['InstanceMonitorData']:
ret[data['InstanceId']] = {}
for item in data:
ret[data['InstanceId']][item] = six.text_type(data[item])
return ret
def show_instance(name, call=None):
'''
Show the details from aliyun instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
return _get_node(name)
def _get_node(name):
attempts = 5
while attempts >= 0:
try:
return list_nodes_full()[name]
except KeyError:
attempts -= 1
log.debug(
'Failed to get the data for node \'%s\'. Remaining '
'attempts: %s', name, attempts
)
# Just a little delay between attempts...
time.sleep(0.5)
raise SaltCloudNotFound(
'The specified instance {0} not found'.format(name)
)
def show_image(kwargs, call=None):
'''
Show the details from aliyun image
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_images function must be called with '
'-f or --function'
)
if not isinstance(kwargs, dict):
kwargs = {}
location = get_location()
if 'location' in kwargs:
location = kwargs['location']
params = {
'Action': 'DescribeImages',
'RegionId': location,
'ImageId': kwargs['image']
}
ret = {}
items = query(params=params)
# DescribeImages so far support input multi-image. And
# if not found certain image, the response will include
# blank image list other than 'not found' error message
if 'Code' in items or not items['Images']['Image']:
raise SaltCloudNotFound('The specified image could not be found.')
log.debug(
'Total %s image found in Region %s',
items['TotalCount'], location
)
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 destroy(name, call=None):
'''
Destroy a node.
CLI Example:
.. code-block:: bash
salt-cloud -a destroy myinstance
salt-cloud -d myinstance
'''
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']
)
instanceId = _get_node(name)['InstanceId']
# have to stop instance before del it
stop_params = {
'Action': 'StopInstance',
'InstanceId': instanceId
}
query(stop_params)
params = {
'Action': 'DeleteInstance',
'InstanceId': instanceId
}
node = query(params)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return node
|
saltstack/salt | salt/cloud/clouds/aliyun.py | __get_location | python | 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
)
) | Return the VM's location | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/aliyun.py#L474-L492 | null | # -*- coding: utf-8 -*-
'''
AliYun ECS Cloud Module
=======================
.. versionadded:: 2014.7.0
The Aliyun cloud module is used to control access to the aliyun ECS.
http://www.aliyun.com/
Use of this module requires the ``id`` and ``key`` parameter to be set.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/aliyun.conf``:
.. code-block:: yaml
my-aliyun-config:
# aliyun Access Key ID
id: wFGEwgregeqw3435gDger
# aliyun Access Key Secret
key: GDE43t43REGTrkilg43934t34qT43t4dgegerGEgg
location: cn-qingdao
driver: aliyun
:depends: requests
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import pprint
import logging
import hmac
import uuid
import sys
import base64
from hashlib import sha1
# Import Salt libs
from salt.ext.six.moves.urllib.parse import quote as _quote # pylint: disable=import-error,no-name-in-module
# Import salt cloud libs
import salt.utils.cloud
import salt.utils.data
import salt.utils.json
import salt.config as config
from salt.exceptions import (
SaltCloudNotFound,
SaltCloudSystemExit,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout
)
from salt.utils.stringutils import to_bytes
# Import 3rd-party libs
from salt.ext import six
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# Get logging started
log = logging.getLogger(__name__)
ALIYUN_LOCATIONS = {
# 'us-west-2': 'ec2_us_west_oregon',
'cn-hangzhou': 'AliYun HangZhou Region',
'cn-beijing': 'AliYun BeiJing Region',
'cn-hongkong': 'AliYun HongKong Region',
'cn-qingdao': 'AliYun QingDao Region',
'cn-shanghai': 'AliYun ShangHai Region',
'cn-shenzhen': 'AliYun ShenZheng Region',
'ap-northeast-1': 'AliYun DongJing Region',
'ap-southeast-1': 'AliYun XinJiaPo Region',
'ap-southeast-2': 'AliYun XiNi Region',
'eu-central-1': 'EU FalaKeFu Region',
'me-east-1': 'ME DiBai Region',
'us-east-1': 'US FuJiNiYa Region',
'us-west-1': 'US GuiGu Region',
}
DEFAULT_LOCATION = 'cn-hangzhou'
DEFAULT_ALIYUN_API_VERSION = '2014-05-26'
__virtualname__ = 'aliyun'
# Only load in this module if the aliyun configurations are in place
def __virtual__():
'''
Check for aliyun configurations
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('id', 'key')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'requests': HAS_REQUESTS}
)
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 get_location(vm_=None):
'''
Return the aliyun region to use, in this order:
- CLI parameter
- VM parameter
- Cloud profile setting
'''
return __opts__.get(
'location',
config.get_cloud_config_value(
'location',
vm_ or get_configured_provider(),
__opts__,
default=DEFAULT_LOCATION,
search_global=False
)
)
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_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
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 start(name, call=None):
'''
Start a node
CLI Examples:
.. code-block:: bash
salt-cloud -a start myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Starting node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {'Action': 'StartInstance',
'InstanceId': instanceId}
result = query(params)
return result
def stop(name, force=False, call=None):
'''
Stop a node
CLI Examples:
.. code-block:: bash
salt-cloud -a stop myinstance
salt-cloud -a stop myinstance force=True
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Stopping node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {
'Action': 'StopInstance',
'InstanceId': instanceId,
'ForceStop': six.text_type(force).lower()
}
result = query(params)
return result
def reboot(name, call=None):
'''
Reboot a node
CLI Examples:
.. code-block:: bash
salt-cloud -a reboot myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Rebooting node %s', name)
instance_id = _get_node(name)['InstanceId']
params = {'Action': 'RebootInstance',
'InstanceId': instance_id}
result = query(params)
return result
def create_node(kwargs):
'''
Convenience function to make the rest api call for node creation.
'''
if not isinstance(kwargs, dict):
kwargs = {}
# Required parameters
params = {
'Action': 'CreateInstance',
'InstanceType': kwargs.get('size_id', ''),
'RegionId': kwargs.get('region_id', DEFAULT_LOCATION),
'ImageId': kwargs.get('image_id', ''),
'SecurityGroupId': kwargs.get('securitygroup_id', ''),
'InstanceName': kwargs.get('name', ''),
}
# Optional parameters'
optional = [
'InstanceName', 'InternetChargeType',
'InternetMaxBandwidthIn', 'InternetMaxBandwidthOut',
'HostName', 'Password', 'SystemDisk.Category', 'VSwitchId'
# 'DataDisk.n.Size', 'DataDisk.n.Category', 'DataDisk.n.SnapshotId'
]
for item in optional:
if item in kwargs:
params.update({item: kwargs[item]})
# invoke web call
result = query(params)
return result['InstanceId']
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'aliyun',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
kwargs = {
'name': vm_['name'],
'size_id': get_size(vm_),
'image_id': get_image(vm_),
'region_id': __get_location(vm_),
'securitygroup_id': get_securitygroup(vm_),
}
if 'vswitch_id' in vm_:
kwargs['VSwitchId'] = vm_['vswitch_id']
if 'internet_chargetype' in vm_:
kwargs['InternetChargeType'] = vm_['internet_chargetype']
if 'internet_maxbandwidthin' in vm_:
kwargs['InternetMaxBandwidthIn'] = six.text_type(vm_['internet_maxbandwidthin'])
if 'internet_maxbandwidthout' in vm_:
kwargs['InternetMaxBandwidthOut'] = six.text_type(vm_['internet_maxbandwidthOut'])
if 'hostname' in vm_:
kwargs['HostName'] = vm_['hostname']
if 'password' in vm_:
kwargs['Password'] = vm_['password']
if 'instance_name' in vm_:
kwargs['InstanceName'] = vm_['instance_name']
if 'systemdisk_category' in vm_:
kwargs['SystemDisk.Category'] = vm_['systemdisk_category']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
ret = create_node(kwargs)
except Exception as exc:
log.error(
'Error creating %s on Aliyun ECS\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: %s',
vm_['name'], six.text_type(exc),
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
# repair ip address error and start vm
time.sleep(8)
params = {'Action': 'StartInstance',
'InstanceId': ret}
query(params)
def __query_node_data(vm_name):
data = show_instance(vm_name, call='action')
if not data:
# Trigger an error in the wait_for_ip function
return False
if data.get('PublicIpAddress', None) is not None:
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_['name'],),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
if data['public_ips']:
ssh_ip = data['public_ips'][0]
elif data['private_ips']:
ssh_ip = data['private_ips'][0]
else:
log.info('No available ip:cant connect to salt')
return False
log.debug('VM %s is now running', ssh_ip)
vm_['ssh_host'] = ssh_ip
# The instance is booted and accessible, let's Salt it!
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
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'],
transport=__opts__['transport']
)
return ret
def _compute_signature(parameters, access_key_secret):
'''
Generate aliyun request signature
'''
def percent_encode(line):
if not isinstance(line, six.string_types):
return line
s = line
if sys.stdin.encoding is None:
s = line.decode().encode('utf8')
else:
s = line.decode(sys.stdin.encoding).encode('utf8')
res = _quote(s, '')
res = res.replace('+', '%20')
res = res.replace('*', '%2A')
res = res.replace('%7E', '~')
return res
sortedParameters = sorted(list(parameters.items()), key=lambda items: items[0])
canonicalizedQueryString = ''
for k, v in sortedParameters:
canonicalizedQueryString += '&' + percent_encode(k) \
+ '=' + percent_encode(v)
# All aliyun API only support GET method
stringToSign = 'GET&%2F&' + percent_encode(canonicalizedQueryString[1:])
h = hmac.new(to_bytes(access_key_secret + "&"), stringToSign, sha1)
signature = base64.encodestring(h.digest()).strip()
return signature
def query(params=None):
'''
Make a web call to aliyun ECS REST API
'''
path = 'https://ecs-cn-hangzhou.aliyuncs.com'
access_key_id = config.get_cloud_config_value(
'id', get_configured_provider(), __opts__, search_global=False
)
access_key_secret = config.get_cloud_config_value(
'key', get_configured_provider(), __opts__, search_global=False
)
timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
# public interface parameters
parameters = {
'Format': 'JSON',
'Version': DEFAULT_ALIYUN_API_VERSION,
'AccessKeyId': access_key_id,
'SignatureVersion': '1.0',
'SignatureMethod': 'HMAC-SHA1',
'SignatureNonce': six.text_type(uuid.uuid1()),
'TimeStamp': timestamp,
}
# include action or function parameters
if params:
parameters.update(params)
# Calculate the string for Signature
signature = _compute_signature(parameters, access_key_secret)
parameters['Signature'] = signature
request = requests.get(path, params=parameters, verify=True)
if request.status_code != 200:
raise SaltCloudSystemExit(
'An error occurred while querying aliyun ECS. HTTP Code: {0} '
'Error: \'{1}\''.format(
request.status_code,
request.text
)
)
log.debug(request.url)
content = request.text
result = salt.utils.json.loads(content)
if 'Code' in result:
raise SaltCloudSystemExit(
pprint.pformat(result.get('Message', {}))
)
return result
def script(vm_):
'''
Return the script deployment object
'''
deploy_script = salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
return deploy_script
def show_disk(name, call=None):
'''
Show the disk details of the instance
CLI Examples:
.. code-block:: bash
salt-cloud -a show_disk aliyun myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_disks action must be called with -a or --action.'
)
ret = {}
params = {
'Action': 'DescribeInstanceDisks',
'InstanceId': name
}
items = query(params=params)
for disk in items['Disks']['Disk']:
ret[disk['DiskId']] = {}
for item in disk:
ret[disk['DiskId']][item] = six.text_type(disk[item])
return ret
def list_monitor_data(kwargs=None, call=None):
'''
Get monitor data of the instance. If instance name is
missing, will show all the instance monitor data on the region.
CLI Examples:
.. code-block:: bash
salt-cloud -f list_monitor_data aliyun
salt-cloud -f list_monitor_data aliyun name=AY14051311071990225bd
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_monitor_data must be called with -f or --function.'
)
if not isinstance(kwargs, dict):
kwargs = {}
ret = {}
params = {
'Action': 'GetMonitorData',
'RegionId': get_location()
}
if 'name' in kwargs:
params['InstanceId'] = kwargs['name']
items = query(params=params)
monitorData = items['MonitorData']
for data in monitorData['InstanceMonitorData']:
ret[data['InstanceId']] = {}
for item in data:
ret[data['InstanceId']][item] = six.text_type(data[item])
return ret
def show_instance(name, call=None):
'''
Show the details from aliyun instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
return _get_node(name)
def _get_node(name):
attempts = 5
while attempts >= 0:
try:
return list_nodes_full()[name]
except KeyError:
attempts -= 1
log.debug(
'Failed to get the data for node \'%s\'. Remaining '
'attempts: %s', name, attempts
)
# Just a little delay between attempts...
time.sleep(0.5)
raise SaltCloudNotFound(
'The specified instance {0} not found'.format(name)
)
def show_image(kwargs, call=None):
'''
Show the details from aliyun image
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_images function must be called with '
'-f or --function'
)
if not isinstance(kwargs, dict):
kwargs = {}
location = get_location()
if 'location' in kwargs:
location = kwargs['location']
params = {
'Action': 'DescribeImages',
'RegionId': location,
'ImageId': kwargs['image']
}
ret = {}
items = query(params=params)
# DescribeImages so far support input multi-image. And
# if not found certain image, the response will include
# blank image list other than 'not found' error message
if 'Code' in items or not items['Images']['Image']:
raise SaltCloudNotFound('The specified image could not be found.')
log.debug(
'Total %s image found in Region %s',
items['TotalCount'], location
)
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 destroy(name, call=None):
'''
Destroy a node.
CLI Example:
.. code-block:: bash
salt-cloud -a destroy myinstance
salt-cloud -d myinstance
'''
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']
)
instanceId = _get_node(name)['InstanceId']
# have to stop instance before del it
stop_params = {
'Action': 'StopInstance',
'InstanceId': instanceId
}
query(stop_params)
params = {
'Action': 'DeleteInstance',
'InstanceId': instanceId
}
node = query(params)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return node
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.