desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'`<https://www.elastic.co/guide/en/elasticsearch/plugins/current/ingest.html>`_
:arg id: Pipeline ID
:arg master_timeout: Explicit operation timeout for connection to master
node
:arg timeout: Explicit operation timeout'
| @query_params('master_timeout', 'timeout')
def delete_pipeline(self, id, params=None):
| if (id in SKIP_IN_PATH):
raise ValueError("Empty value passed for a required argument 'id'.")
return self.transport.perform_request('DELETE', _make_path('_ingest', 'pipeline', id), params=params)
|
'`<https://www.elastic.co/guide/en/elasticsearch/plugins/current/ingest.html>`_
:arg body: The simulate definition
:arg id: Pipeline ID
:arg verbose: Verbose mode. Display data output for each processor in
executed pipeline, default False'
| @query_params('verbose')
def simulate(self, body, id=None, params=None):
| if (body in SKIP_IN_PATH):
raise ValueError("Empty value passed for a required argument 'body'.")
return self.transport.perform_request('GET', _make_path('_ingest', 'pipeline', id, '_simulate'), params=params, body=body)
|
'The HTTP status code of the response that precipitated the error or
``\'N/A\'`` if not applicable.'
| @property
def status_code(self):
| return self.args[0]
|
'A string error message.'
| @property
def error(self):
| return self.args[1]
|
'Dict of returned error info from ES, where available.'
| @property
def info(self):
| return self.args[2]
|
'List of errors from execution of the last chunk.'
| @property
def errors(self):
| return self.args[1]
|
':arg opts: dictionary of connection instances and their options'
| def __init__(self, opts):
| self.connection_opts = opts
|
'Select a connection from the given list.
:arg connections: list of live connections to choose from'
| def select(self, connections):
| pass
|
':arg connections: list of tuples containing the
:class:`~elasticsearch.Connection` instance and it\'s options
:arg dead_timeout: number of seconds a connection should be retired for
after a failure, increases on consecutive failures
:arg timeout_cutoff: number of consecutive failures after which the
timeout doesn\'t i... | def __init__(self, connections, dead_timeout=60, timeout_cutoff=5, selector_class=RoundRobinSelector, randomize_hosts=True, **kwargs):
| if (not connections):
raise ImproperlyConfigured('No defined connections, you need to specify at least one host.')
self.connection_opts = connections
self.connections = [c for (c, opts) in connections]
self.orig_connections = tuple(self.connections)
self.dead = ... |
'Mark the connection as dead (failed). Remove it from the live pool and
put it on a timeout.
:arg connection: the failed instance'
| def mark_dead(self, connection, now=None):
| now = (now if now else time.time())
try:
self.connections.remove(connection)
except ValueError:
return
else:
dead_count = (self.dead_count.get(connection, 0) + 1)
self.dead_count[connection] = dead_count
timeout = (self.dead_timeout * (2 ** min((dead_count - 1), s... |
'Mark connection as healthy after a resurrection. Resets the fail
counter for the connection.
:arg connection: the connection to redeem'
| def mark_live(self, connection):
| try:
del self.dead_count[connection]
except KeyError:
pass
|
'Attempt to resurrect a connection from the dead pool. It will try to
locate one (not all) eligible (it\'s timeout is over) connection to
return to the live pool. Any resurrected connection is also returned.
:arg force: resurrect a connection even if there is none eligible (used
when we have no live connections). If fo... | def resurrect(self, force=False):
| if self.dead.empty():
if force:
return random.choice(self.orig_connections)
return
try:
(timeout, connection) = self.dead.get(block=False)
except Empty:
if force:
return random.choice(self.orig_connections)
return
if ((not force) and (timeo... |
'Return a connection from the pool using the `ConnectionSelector`
instance.
It tries to resurrect eligible connections, forces a resurrection when
no connections are availible and passes the list of live connections to
the selector instance to choose from.
Returns a connection instance and it\'s current fail count.'
| def get_connection(self):
| self.resurrect()
connections = self.connections[:]
if (not connections):
return self.resurrect(True)
if (len(connections) > 1):
return self.selector.select(connections)
return connections[0]
|
'Explicitly closes connections'
| def close(self):
| for conn in self.orig_connections:
conn.close()
|
'Explicitly closes connections'
| def close(self):
| self.connection.close()
|
':arg host: hostname of the node (default: localhost)
:arg port: port to use (integer, default: 9200)
:arg url_prefix: optional url prefix for elasticsearch
:arg timeout: default timeout in seconds (float, default: 10)'
| def __init__(self, host='localhost', port=9200, use_ssl=False, url_prefix='', timeout=10, **kwargs):
| scheme = kwargs.get('scheme', 'http')
if (use_ssl or (scheme == 'https')):
scheme = 'https'
use_ssl = True
self.use_ssl = use_ssl
self.host = ('%s://%s:%s' % (scheme, host, port))
if url_prefix:
url_prefix = ('/' + url_prefix.strip('/'))
self.url_prefix = url_prefix
s... |
'Log a successful API call.'
| def log_request_success(self, method, full_url, path, body, status_code, response, duration):
| if body:
body = body.decode('utf-8')
logger.info('%s %s [status:%s request:%.3fs]', method, full_url, status_code, duration)
logger.debug('> %s', body)
logger.debug('< %s', response)
self._log_trace(method, path, body, status_code, response, duration)
|
'Log an unsuccessful API call.'
| def log_request_fail(self, method, full_url, path, body, duration, status_code=None, response=None, exception=None):
| if ((method == 'HEAD') and (status_code == 404)):
return
logger.warning('%s %s [status:%s request:%.3fs]', method, full_url, (status_code or 'N/A'), duration, exc_info=(exception is not None))
if body:
body = body.decode('utf-8')
logger.debug('> %s', body)
self._log_trace... |
'Locate appropriate exception and raise it.'
| def _raise_error(self, status_code, raw_data):
| error_message = raw_data
additional_info = None
try:
if raw_data:
additional_info = json.loads(raw_data)
error_message = additional_info.get('error', error_message)
if (isinstance(error_message, dict) and ('type' in error_message)):
error_message =... |
'Explicitly closes connection'
| def close(self):
| self.pool.close()
|
'Explicitly closes connections'
| def close(self):
| self.session.close()
|
'Explicitly close connection'
| def close(self):
| pass
|
'Pull all indices into `all_indices`, then populate `indices` and
`index_info`'
| def __get_indices(self):
| self.loggit.debug('Getting all indices')
self.all_indices = get_indices(self.client)
self.indices = self.all_indices[:]
if self.indices:
for index in self.indices:
self.__build_index_info(index)
self._get_metadata()
self._get_index_stats()
|
'Ensure that `index` is a key in `index_info`. If not, create a
sub-dictionary structure under that key.'
| def __build_index_info(self, index):
| self.loggit.debug('Building preliminary index metadata for {0}'.format(index))
if (not (index in self.index_info)):
self.index_info[index] = {'age': {}, 'number_of_replicas': 0, 'number_of_shards': 0, 'segments': 0, 'size_in_bytes': 0, 'docs': 0, 'state': ''}
|
'Populate `index_info` with index `size_in_bytes` and doc count
information for each index.'
| def _get_index_stats(self):
| self.loggit.debug('Getting index stats')
self.empty_list_check()
def iterate_over_stats(stats):
for index in stats['indices']:
size = stats['indices'][index]['total']['store']['size_in_bytes']
docs = stats['indices'][index]['total']['docs']['count']
self.log... |
'Populate `index_info` with index `size_in_bytes` and doc count
information for each index.'
| def _get_metadata(self):
| self.loggit.debug('Getting index metadata')
self.empty_list_check()
index_lists = chunk_index_list(self.indices)
for l in index_lists:
working_list = self.client.cluster.state(index=to_csv(l), metric='metadata')['metadata']['indices']
if working_list:
for index in list(... |
'Raise exception if `indices` is empty'
| def empty_list_check(self):
| self.loggit.debug('Checking for empty list')
if (not self.indices):
raise NoIndices('index_list object is empty.')
|
'Return the current value of `indices` as copy-by-value to prevent list
stomping during iterations'
| def working_list(self):
| self.loggit.debug('Generating working list of indices')
return self.indices[:]
|
'Populate `index_info` with segment information for each index.'
| def _get_segmentcounts(self):
| self.loggit.debug('Getting index segment counts')
self.empty_list_check()
index_lists = chunk_index_list(self.indices)
for l in index_lists:
working_list = self.client.indices.segments(index=to_csv(l))['indices']
if working_list:
for index in list(working_list.keys()... |
'Add indices to `index_info` based on the age as indicated by the index
name pattern, if it matches `timestring`
:arg timestring: An strftime pattern'
| def _get_name_based_ages(self, timestring):
| self.loggit.debug('Getting ages of indices by "name"')
self.empty_list_check()
ts = TimestringSearch(timestring)
for index in self.working_list():
epoch = ts.get_epoch(index)
if isinstance(epoch, int):
self.index_info[index]['age']['name'] = epoch
|
'Add indices to `index_info` based on the value the stats api returns,
as determined by `field`
:arg field: The field with the date value. The field must be mapped in
elasticsearch as a date datatype. Default: ``@timestamp``'
| def _get_field_stats_dates(self, field='@timestamp'):
| self.loggit.debug('Getting index date from field_stats API')
self.loggit.debug('Cannot use field_stats on closed indices. Omitting any closed indices.')
self.filter_closed()
index_lists = chunk_index_list(self.indices)
for l in index_lists:
worki... |
'This method initiates index age calculation based on the given
parameters. Exceptions are raised when they are improperly configured.
Set instance variable `age_keyfield` for use later, if needed.
:arg source: Source of index age. Can be one of \'name\', \'creation_date\',
or \'field_stats\'
:arg timestring: An strft... | def _calculate_ages(self, source=None, timestring=None, field=None, stats_result=None):
| self.age_keyfield = source
if (source == 'name'):
if (not timestring):
raise MissingArgument('source "name" requires the "timestring" keyword argument')
self._get_name_based_ages(timestring)
elif (source == 'creation_date'):
pass
elif (source == 'fie... |
'Take a list of indices and sort them by date.
By default, the youngest are first with `reverse=True`, but the oldest
can be first by setting `reverse=False`'
| def _sort_by_age(self, index_list, reverse=True):
| temp = {}
for index in index_list:
if (self.age_keyfield in self.index_info[index]['age']):
temp[index] = self.index_info[index]['age'][self.age_keyfield]
else:
msg = '{0} does not have age key "{1}" in IndexList metadata'.format(index, self... |
'Match indices by regular expression (pattern).
:arg kind: Can be one of: ``suffix``, ``prefix``, ``regex``, or
``timestring``. This option defines what kind of filter you will be
building.
:arg value: Depends on `kind`. It is the strftime string if `kind` is
``timestring``. It\'s used to build the regular expression f... | def filter_by_regex(self, kind=None, value=None, exclude=False):
| self.loggit.debug('Filtering indices by regex')
if (kind not in ['regex', 'prefix', 'suffix', 'timestring']):
raise ValueError('{0}: Invalid value for kind'.format(kind))
if (value == 0):
pass
elif (not value):
raise ValueError('{0}: Invalid value fo... |
'Match `indices` by relative age calculations.
:arg source: Source of index age. Can be one of \'name\', \'creation_date\',
or \'field_stats\'
:arg direction: Time to filter, either ``older`` or ``younger``
:arg timestring: An strftime string to match the datestamp in an index
name. Only used for index filtering by ``n... | def filter_by_age(self, source='name', direction=None, timestring=None, unit=None, unit_count=None, field=None, stats_result='min_value', epoch=None, exclude=False):
| self.loggit.debug('Filtering indices by age')
PoR = get_point_of_reference(unit, unit_count, epoch)
if (not direction):
raise MissingArgument('Must provide a value for "direction"')
if (direction not in ['older', 'younger']):
raise ValueError('Invalid value ... |
'Remove indices from the actionable list based on space
consumed, sorted reverse-alphabetically by default. If you set
`reverse` to `False`, it will be sorted alphabetically.
The default is usually what you will want. If only one kind of index is
provided--for example, indices matching ``logstash-%Y.%m.%d``--then
reve... | def filter_by_space(self, disk_space=None, reverse=True, use_age=False, source='creation_date', timestring=None, field=None, stats_result='min_value', exclude=False):
| self.loggit.debug('Filtering indices by disk space')
if (not disk_space):
raise MissingArgument('No value for "disk_space" provided')
disk_space = float(disk_space)
disk_usage = 0.0
disk_limit = (disk_space * (2 ** 30))
self.loggit.debug('Cannot get disk ... |
'Match any index named ``.kibana``, ``kibana-int``, ``.marvel-kibana``,
or ``.marvel-es-data`` in `indices`.
:arg exclude: If `exclude` is `True`, this filter will remove matching
indices from `indices`. If `exclude` is `False`, then only matching
indices will be kept in `indices`.
Default is `True`'
| def filter_kibana(self, exclude=True):
| self.loggit.debug('Filtering kibana indices')
self.empty_list_check()
for index in self.working_list():
if (index in ['.kibana', '.marvel-kibana', 'kibana-int', '.marvel-es-data']):
self.__excludify(True, exclude, index)
|
'Match any index which has `max_num_segments` per shard or fewer in the
actionable list.
:arg max_num_segments: Cutoff number of segments per shard.
:arg exclude: If `exclude` is `True`, this filter will remove matching
indices from `indices`. If `exclude` is `False`, then only matching
indices will be kept in `indices... | def filter_forceMerged(self, max_num_segments=None, exclude=True):
| self.loggit.debug('Filtering forceMerged indices')
if (not max_num_segments):
raise MissingArgument('Missing value for "max_num_segments"')
self.loggit.debug('Cannot get segment count of closed indices. Omitting any closed indices.')
self.filter_c... |
'Filter out closed indices from `indices`
:arg exclude: If `exclude` is `True`, this filter will remove matching
indices from `indices`. If `exclude` is `False`, then only matching
indices will be kept in `indices`.
Default is `True`'
| def filter_closed(self, exclude=True):
| self.loggit.debug('Filtering closed indices')
self.empty_list_check()
for index in self.working_list():
condition = (self.index_info[index]['state'] == 'close')
self.loggit.debug('Index {0} state: {1}'.format(index, self.index_info[index]['state']))
self.__excludify(co... |
'Filter out opened indices from `indices`
:arg exclude: If `exclude` is `True`, this filter will remove matching
indices from `indices`. If `exclude` is `False`, then only matching
indices will be kept in `indices`.
Default is `True`'
| def filter_opened(self, exclude=True):
| self.loggit.debug('Filtering open indices')
self.empty_list_check()
for index in self.working_list():
condition = (self.index_info[index]['state'] == 'open')
self.loggit.debug('Index {0} state: {1}'.format(index, self.index_info[index]['state']))
self.__excludify(condi... |
'Match indices that have the routing allocation rule of
`key=value` from `indices`
:arg key: The allocation attribute to check for
:arg value: The value to check for
:arg allocation_type: Type of allocation to apply
:arg exclude: If `exclude` is `True`, this filter will remove matching
indices from `indices`. If `exclu... | def filter_allocated(self, key=None, value=None, allocation_type='require', exclude=True):
| self.loggit.debug('Filtering indices with shard routing allocation rules')
if (not key):
raise MissingArgument('No value for "key" provided')
if (not value):
raise MissingArgument('No value for "value" provided')
if (not (allocation_type in ['inc... |
'Match indices which are associated with the alias or list of aliases
identified by `aliases`.
An update to Elasticsearch 5.5.0 changes the behavior of this from
previous 5.x versions:
https://www.elastic.co/guide/en/elasticsearch/reference/5.5/breaking-changes-5.5.html#breaking_55_rest_changes
What this means is that ... | def filter_by_alias(self, aliases=None, exclude=False):
| self.loggit.debug('Filtering indices matching aliases: "{0}"'.format(aliases))
if (not aliases):
raise MissingArgument('No value for "aliases" provided')
aliases = ensure_list(aliases)
self.empty_list_check()
index_lists = chunk_index_list(self.indices)
for l in i... |
'Remove indices from the actionable list beyond the number `count`,
sorted reverse-alphabetically by default. If you set `reverse` to
`False`, it will be sorted alphabetically.
The default is usually what you will want. If only one kind of index is
provided--for example, indices matching ``logstash-%Y.%m.%d``--then
re... | def filter_by_count(self, count=None, reverse=True, use_age=False, source='creation_date', timestring=None, field=None, stats_result='min_value', exclude=True):
| self.loggit.debug('Filtering indices by count')
if (not count):
raise MissingArgument('No value for "count" provided')
working_list = self.working_list()
if use_age:
if (source != 'name'):
self.loggit.warn('Cannot get age information from c... |
'Match `indices` within ages within a given period.
:arg source: Source of index age. Can be one of \'name\', \'creation_date\',
or \'field_stats\'
:arg range_from: How many ``unit`` (s) in the past/future is the origin?
:arg range_to: How many ``unit`` (s) in the past/future is the end point?
:arg timestring: An strft... | def filter_period(self, source='name', range_from=None, range_to=None, timestring=None, unit=None, field=None, stats_result='min_value', week_starts_on='sunday', epoch=None, exclude=False):
| self.loggit.debug('Filtering indices by age')
try:
(start, end) = date_range(unit, range_from, range_to, epoch, week_starts_on=week_starts_on)
except Exception as e:
report_failure(e)
self._calculate_ages(source=source, timestring=timestring, field=field, stats_result=stats_resu... |
'Iterate over the filters defined in `config` and execute them.
:arg filter_dict: The configuration dictionary
.. note:: `filter_dict` should be a dictionary with the following form:
.. code-block:: python
{ \'filters\' : [
\'filtertype\': \'the_filter_type\',
\'key1\' : \'value1\',
\'keyN\' : \'valueN\''
| def iterate_filters(self, filter_dict):
| self.loggit.debug('Iterating over a list of filters')
if ((not ('filters' in filter_dict)) or (len(filter_dict['filters']) < 1)):
logger.info('No filters in config. Returning unaltered object.')
return
self.loggit.debug('All filters: {0}'.format(fil... |
'Validate ``config`` with the provided voluptuous ``schema``.
``test_what`` and ``location`` are for reporting the results, in case of
failure. If validation is successful, the method returns ``config`` as
valid.
:arg config: A configuration dictionary.
:type config: dict
:arg schema: A voluptuous schema definition
:t... | def __init__(self, config, schema, test_what, location):
| self.loggit = logging.getLogger('curator.validators.SchemaCheck')
self.loggit.debug('Schema: {0}'.format(schema))
self.loggit.debug('"{0}" config: {1}'.format(test_what, config))
self.config = config
self.schema = schema
self.test_what = test_what
self.location = location
|
'Report the error, and try to report the bad key or value as well.'
| def __parse_error(self):
| def get_badvalue(data_string, data):
elements = re.sub("['\\]]", '', data_string).split('[')
elements.pop(0)
value = None
for k in elements:
try:
key = int(k)
except ValueError:
key = k
if (value == None):
... |
'Return the epoch timestamp extracted from the `timestring` appearing in
`searchme`.
:arg searchme: A string to be searched for a date pattern that matches
`timestring`
:rtype: int'
| def get_epoch(self, searchme):
| match = self.pattern.search(searchme)
if match:
if match.group('date'):
timestamp = match.group('date')
return datetime_to_epoch(get_datetime(timestamp, self.timestring))
|
'Pull all snapshots into `snapshots` and populate
`snapshot_info`'
| def __get_snapshots(self):
| self.all_snapshots = get_snapshot_data(self.client, self.repository)
for list_item in self.all_snapshots:
if ('snapshot' in list_item.keys()):
self.snapshots.append(list_item['snapshot'])
self.snapshot_info[list_item['snapshot']] = list_item
self.empty_list_check()
|
'Raise exception if `snapshots` is empty'
| def empty_list_check(self):
| if (not self.snapshots):
raise NoSnapshots('snapshot_list object is empty.')
|
'Return the current value of `snapshots` as copy-by-value to prevent list
stomping during iterations'
| def working_list(self):
| return self.snapshots[:]
|
'Add a snapshot age to `snapshot_info` based on the age as indicated
by the snapshot name pattern, if it matches `timestring`. This is
stored at key ``age_by_name``.
:arg timestring: An strftime pattern'
| def _get_name_based_ages(self, timestring):
| self.empty_list_check()
ts = TimestringSearch(timestring)
for snapshot in self.working_list():
epoch = ts.get_epoch(snapshot)
if epoch:
self.snapshot_info[snapshot]['age_by_name'] = epoch
else:
self.snapshot_info[snapshot]['age_by_name'] = None
|
'This method initiates snapshot age calculation based on the given
parameters. Exceptions are raised when they are improperly configured.
Set instance variable `age_keyfield` for use later, if needed.
:arg source: Source of snapshot age. Can be \'name\' or \'creation_date\'.
:arg timestring: An strftime string to matc... | def _calculate_ages(self, source='creation_date', timestring=None):
| if (source == 'name'):
self.age_keyfield = 'age_by_name'
if (not timestring):
raise MissingArgument('source "name" requires the "timestring" keyword argument')
self._get_name_based_ages(timestring)
elif (source == 'creation_date'):
self.age_keyfield ... |
'Take a list of snapshots and sort them by date.
By default, the youngest are first with `reverse=True`, but the oldest
can be first by setting `reverse=False`'
| def _sort_by_age(self, snapshot_list, reverse=True):
| temp = {}
for snap in snapshot_list:
if (self.age_keyfield in self.snapshot_info[snap]):
temp[snap] = self.snapshot_info[snap][self.age_keyfield]
else:
msg = '{0} does not have age key "{1}" in SnapshotList metadata'.format(snap, self.age_ke... |
'Return the most recent snapshot based on `start_time_in_millis`.'
| def most_recent(self):
| self.empty_list_check()
most_recent_time = 0
most_recent_snap = ''
for snapshot in self.snapshots:
snaptime = fix_epoch(self.snapshot_info[snapshot]['start_time_in_millis'])
if (snaptime > most_recent_time):
most_recent_snap = snapshot
most_recent_time = snaptime
... |
'Filter out snapshots not matching the pattern, or in the case of
exclude, filter those matching the pattern.
:arg kind: Can be one of: ``suffix``, ``prefix``, ``regex``, or
``timestring``. This option defines what kind of filter you will be
building.
:arg value: Depends on `kind`. It is the strftime string if `kind` i... | def filter_by_regex(self, kind=None, value=None, exclude=False):
| if (kind not in ['regex', 'prefix', 'suffix', 'timestring']):
raise ValueError('{0}: Invalid value for kind'.format(kind))
if (value == 0):
pass
elif (not value):
raise ValueError('{0}: Invalid value for "value". Cannot be "None" type, empty, ... |
'Remove snapshots from `snapshots` by relative age calculations.
:arg source: Source of snapshot age. Can be \'name\', or \'creation_date\'.
:arg direction: Time to filter, either ``older`` or ``younger``
:arg timestring: An strftime string to match the datestamp in an
snapshot name. Only used for snapshot filtering by... | def filter_by_age(self, source='creation_date', direction=None, timestring=None, unit=None, unit_count=None, epoch=None, exclude=False):
| self.loggit.debug('Starting filter_by_age')
PoR = get_point_of_reference(unit, unit_count, epoch)
self.loggit.debug('Point of Reference: {0}'.format(PoR))
if (not direction):
raise MissingArgument('Must provide a value for "direction"')
if (direction not in ['older... |
'Filter out snapshots not matching ``state``, or in the case of exclude,
filter those matching ``state``.
:arg state: The snapshot state to filter for. Must be one of
``SUCCESS``, ``PARTIAL``, ``FAILED``, or ``IN_PROGRESS``.
:arg exclude: If `exclude` is `True`, this filter will remove matching
snapshots from `snapshot... | def filter_by_state(self, state=None, exclude=False):
| if (state.upper() not in ['SUCCESS', 'PARTIAL', 'FAILED', 'IN_PROGRESS']):
raise ValueError('{0}: Invalid value for state'.format(state))
self.empty_list_check()
for snapshot in self.working_list():
self.loggit.debug('Filter by state: Snapshot: {0}'.format(snapshot))
... |
'Remove snapshots from the actionable list beyond the number `count`,
sorted reverse-alphabetically by default. If you set `reverse` to
`False`, it will be sorted alphabetically.
The default is usually what you will want. If only one kind of snapshot
is provided--for example, snapshots matching ``curator-%Y%m%d%H%M%S`... | def filter_by_count(self, count=None, reverse=True, use_age=False, source='creation_date', timestring=None, exclude=True):
| self.loggit.debug('Filtering snapshots by count')
if (not count):
raise MissingArgument('No value for "count" provided')
working_list = self.working_list()
if use_age:
self._calculate_ages(source=source, timestring=timestring)
sorted_snapshots = self._sort_by... |
'Match `indices` within ages within a given period.
:arg source: Source of snapshot age. Can be \'name\', or \'creation_date\'.
:arg range_from: How many ``unit`` (s) in the past/future is the origin?
:arg range_to: How many ``unit`` (s) in the past/future is the end point?
:arg timestring: An strftime string to match ... | def filter_period(self, source='name', range_from=None, range_to=None, timestring=None, unit=None, field=None, stats_result='min_value', week_starts_on='sunday', epoch=None, exclude=False):
| self.loggit.debug('Filtering snapshots by period')
try:
(start, end) = date_range(unit, range_from, range_to, epoch, week_starts_on=week_starts_on)
except Exception as e:
report_failure(e)
self._calculate_ages(source=source, timestring=timestring)
for snapshot in self.workin... |
'Iterate over the filters defined in `config` and execute them.
:arg config: A dictionary of filters, as extracted from the YAML
configuration file.
.. note:: `config` should be a dictionary with the following form:
.. code-block:: python
{ \'filters\' : [
\'filtertype\': \'the_filter_type\',
\'key1\' : \'value1\',
\'k... | def iterate_filters(self, config):
| if ((not ('filters' in config)) or (len(config['filters']) < 1)):
logger.info('No filters in config. Returning unaltered object.')
return
self.loggit.debug('All filters: {0}'.format(config['filters']))
for f in config['filters']:
self.loggit.debug('Top ... |
'Define the Alias object.
:arg name: The alias name
:arg extra_settings: Extra settings, including filters and routing. For
more information see
https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-aliases.html
:type extra_settings: dict, representing the settings.'
| def __init__(self, name=None, extra_settings={}, **kwargs):
| if (not name):
raise MissingArgument('No value for "name" provided.')
self.name = parse_date_pattern(name)
self.actions = []
self.client = None
self.extra_settings = extra_settings
self.loggit = logging.getLogger('curator.actions.alias')
|
'Create `add` statements for each index in `ilo` for `alias`, then
append them to `actions`. Add any `extras` that may be there.
:arg ilo: A :class:`curator.indexlist.IndexList` object'
| def add(self, ilo, warn_if_no_indices=False):
| verify_index_list(ilo)
if (not self.client):
self.client = ilo.client
try:
ilo.empty_list_check()
except NoIndices:
if warn_if_no_indices:
self.loggit.warn('No indices found after processing filters. Nothing to add to {0}'.format(self.nam... |
'Create `remove` statements for each index in `ilo` for `alias`,
then append them to `actions`.
:arg ilo: A :class:`curator.indexlist.IndexList` object'
| def remove(self, ilo, warn_if_no_indices=False):
| verify_index_list(ilo)
if (not self.client):
self.client = ilo.client
try:
ilo.empty_list_check()
except NoIndices:
if warn_if_no_indices:
self.loggit.warn('No indices found after processing filters. Nothing to remove from {0}'.format(sel... |
'Return a `body` string suitable for use with the `update_aliases` API
call.'
| def body(self):
| if (not self.actions):
raise ActionError('No "add" or "remove" operations')
self.loggit.debug('Alias actions: {0}'.format(self.actions))
return {'actions': self.actions}
|
'Log what the output would be, but take no action.'
| def do_dry_run(self):
| self.loggit.info('DRY-RUN MODE. No changes will be made.')
for item in self.body()['actions']:
job = list(item.keys())[0]
index = item[job]['index']
alias = item[job]['alias']
self.loggit.info('DRY-RUN: alias: {0}ing index "{1}" {2} alias ... |
'Run the API call `update_aliases` with the results of `body()`'
| def do_action(self):
| self.loggit.info('Updating aliases...')
self.loggit.info('Alias actions: {0}'.format(self.body()))
try:
self.client.indices.update_aliases(body=self.body())
except Exception as e:
report_failure(e)
|
':arg ilo: A :class:`curator.indexlist.IndexList` object
:arg key: An arbitrary metadata attribute key. Must match the key
assigned to at least some of your nodes to have any effect.
:arg value: An arbitrary metadata attribute value. Must correspond to
values associated with `key` assigned to at least some of your no... | def __init__(self, ilo, key=None, value=None, allocation_type='require', wait_for_completion=False, wait_interval=3, max_wait=(-1)):
| verify_index_list(ilo)
if (not key):
raise MissingArgument('No value for "key" provided')
if (allocation_type not in ['require', 'include', 'exclude']):
raise ValueError('{0} is an invalid allocation_type. Must be one of "require", "include", ... |
'Log what the output would be, but take no action.'
| def do_dry_run(self):
| show_dry_run(self.index_list, 'allocation', body=self.body)
|
'Change allocation settings for indices in `index_list.indices` with the
settings in `body`.'
| def do_action(self):
| self.loggit.debug('Cannot get change shard routing allocation of closed indices. Omitting any closed indices.')
self.index_list.filter_closed()
self.index_list.empty_list_check()
self.loggit.info('Updating index setting {0}'.format(self.body))
try:
... |
':arg ilo: A :class:`curator.indexlist.IndexList` object
:arg delete_aliases: If `True`, will delete any associated aliases
before closing indices.
:type delete_aliases: bool'
| def __init__(self, ilo, delete_aliases=False):
| verify_index_list(ilo)
self.index_list = ilo
self.delete_aliases = delete_aliases
self.client = ilo.client
self.loggit = logging.getLogger('curator.actions.close')
|
'Log what the output would be, but take no action.'
| def do_dry_run(self):
| show_dry_run(self.index_list, 'close', **{'delete_aliases': self.delete_aliases})
|
'Close open indices in `index_list.indices`'
| def do_action(self):
| self.index_list.filter_closed()
self.index_list.empty_list_check()
self.loggit.info('Closing selected indices: {0}'.format(self.index_list.indices))
try:
index_lists = chunk_index_list(self.index_list.indices)
for l in index_lists:
if self.delete_aliases:
... |
'For now, the cluster routing settings are hardcoded to be ``transient``
:arg client: An :class:`elasticsearch.Elasticsearch` client object
:arg routing_type: Type of routing to apply. Either `allocation` or
`rebalance`
:arg setting: Currently, the only acceptable value for `setting` is
``enable``. This is here in case... | def __init__(self, client, routing_type=None, setting=None, value=None, wait_for_completion=False, wait_interval=9, max_wait=(-1)):
| verify_client_object(client)
self.client = client
self.loggit = logging.getLogger('curator.actions.cluster_routing')
self.wfc = wait_for_completion
self.wait_interval = wait_interval
self.max_wait = max_wait
if (setting != 'enable'):
raise ValueError('Invalid value for "sett... |
'Log what the output would be, but take no action.'
| def do_dry_run(self):
| logger.info('DRY-RUN MODE. No changes will be made.')
self.loggit.info('DRY-RUN: Update cluster routing settings with arguments: {0}'.format(self.body))
|
'Change cluster routing settings with the settings in `body`.'
| def do_action(self):
| self.loggit.info('Updating cluster settings: {0}'.format(self.body))
try:
self.client.cluster.put_settings(body=self.body)
if self.wfc:
logger.debug('Waiting for shards to complete routing and/or rebalancing')
wait_for_it(self.client, 'cluste... |
':arg client: An :class:`elasticsearch.Elasticsearch` client object
:arg name: A name, which can contain :py:func:`time.strftime`
strings
:arg extra_settings: The `settings` and `mappings` for the index. For
more information see
https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-create-index.html
:... | def __init__(self, client, name, extra_settings={}):
| verify_client_object(client)
if (not name):
raise ConfigurationError('Value for "name" not provided.')
self.name = parse_date_pattern(name)
self.body = extra_settings
self.client = client
self.loggit = logging.getLogger('curator.actions.create_index')
|
'Log what the output would be, but take no action.'
| def do_dry_run(self):
| logger.info('DRY-RUN MODE. No changes will be made.')
self.loggit.info('DRY-RUN: create_index "{0}" with arguments: {1}'.format(self.name, self.body))
|
'Create index identified by `name` with settings in `body`'
| def do_action(self):
| self.loggit.info('Creating index "{0}" with settings: {1}'.format(self.name, self.body))
try:
self.client.indices.create(index=self.name, body=self.body)
except Exception as e:
report_failure(e)
|
':arg ilo: A :class:`curator.indexlist.IndexList` object
:arg master_timeout: Number of seconds to wait for master node response'
| def __init__(self, ilo, master_timeout=30):
| verify_index_list(ilo)
if (not isinstance(master_timeout, int)):
raise TypeError('Incorrect type for "master_timeout": {0}. Should be integer value.'.format(type(master_timeout)))
self.index_list = ilo
self.client = ilo.client
self.master_timeout = (str(master_timeout... |
'Breakout method to aid readability
:arg result: A list of indices from `_get_result_list`
:arg count: The number of tries that have occurred
:rtype: bool'
| def _verify_result(self, result, count):
| if (len(result) > 0):
self.loggit.error('The following indices failed to delete on try #{0}:'.format(count))
for idx in result:
self.loggit.error('---{0}'.format(idx))
return False
else:
self.loggit.debug('Successfully deleted all indi... |
'Loop through deletes 3 times to ensure they complete
:arg chunk_list: A list of indices pre-chunked so it won\'t overload the
URL size limit.'
| def __chunk_loop(self, chunk_list):
| working_list = chunk_list
for count in range(1, 4):
for i in working_list:
self.loggit.info('---deleting index {0}'.format(i))
self.client.indices.delete(index=to_csv(working_list), master_timeout=self.master_timeout)
result = [i for i in working_list if (i in get_indic... |
'Log what the output would be, but take no action.'
| def do_dry_run(self):
| show_dry_run(self.index_list, 'delete_indices')
|
'Delete indices in `index_list.indices`'
| def do_action(self):
| self.index_list.empty_list_check()
self.loggit.info('Deleting selected indices: {0}'.format(self.index_list.indices))
try:
index_lists = chunk_index_list(self.index_list.indices)
for l in index_lists:
self.__chunk_loop(l)
except Exception as e:
report_failure... |
':arg ilo: A :class:`curator.indexlist.IndexList` object
:arg max_num_segments: Number of segments per shard to forceMerge
:arg delay: Number of seconds to delay between forceMerge operations'
| def __init__(self, ilo, max_num_segments=None, delay=0):
| verify_index_list(ilo)
if (not max_num_segments):
raise MissingArgument('Missing value for "max_num_segments"')
self.client = ilo.client
self.index_list = ilo
self.max_num_segments = max_num_segments
self.delay = delay
self.loggit = logging.getLogger('curator.actions.forceme... |
'Log what the output would be, but take no action.'
| def do_dry_run(self):
| show_dry_run(self.index_list, 'forcemerge', max_num_segments=self.max_num_segments, delay=self.delay)
|
'forcemerge indices in `index_list.indices`'
| def do_action(self):
| self.index_list.empty_list_check()
self.index_list.filter_forceMerged(max_num_segments=self.max_num_segments)
self.loggit.info('forceMerging selected indices')
try:
for index_name in self.index_list.indices:
self.loggit.info('forceMerging index {0} to {1} segment... |
':arg ilo: A :class:`curator.indexlist.IndexList` object
:arg index_settings: A dictionary structure with one or more index
settings to change.
:arg ignore_unavailable: Whether specified concrete indices should be
ignored when unavailable (missing or closed)
:arg preserve_existing: Whether to update existing settings. ... | def __init__(self, ilo, index_settings={}, ignore_unavailable=False, preserve_existing=False):
| verify_index_list(ilo)
if (not index_settings):
raise ConfigurationError('Missing value for "index_settings"')
self.client = ilo.client
self.index_list = ilo
self.body = index_settings
self.ignore_unavailable = ignore_unavailable
self.preserve_existing = preserve_existing
... |
'Log what the output would be, but take no action.'
| def do_dry_run(self):
| show_dry_run(self.index_list, 'indexsettings', **self.body)
|
':arg ilo: A :class:`curator.indexlist.IndexList` object'
| def __init__(self, ilo):
| verify_index_list(ilo)
self.client = ilo.client
self.index_list = ilo
self.loggit = logging.getLogger('curator.actions.open')
|
'Log what the output would be, but take no action.'
| def do_dry_run(self):
| show_dry_run(self.index_list, 'open')
|
'Open closed indices in `index_list.indices`'
| def do_action(self):
| self.index_list.empty_list_check()
self.loggit.info('Opening selected indices: {0}'.format(self.index_list.indices))
try:
index_lists = chunk_index_list(self.index_list.indices)
for l in index_lists:
self.client.indices.open(index=to_csv(l))
except Exception as e:
... |
':arg ilo: A :class:`curator.indexlist.IndexList` object
:arg count: The count of replicas per shard
:arg wait_for_completion: Wait (or not) for the operation
to complete before returning. (default: `False`)
:type wait_for_completion: bool
:arg wait_interval: How long in seconds to wait between checks for
completion.
... | def __init__(self, ilo, count=None, wait_for_completion=False, wait_interval=9, max_wait=(-1)):
| verify_index_list(ilo)
if (count == 0):
pass
elif (not count):
raise MissingArgument('Missing value for "count"')
self.client = ilo.client
self.index_list = ilo
self.count = count
self.wfc = wait_for_completion
self.wait_interval = wait_interval
self.max_wait... |
'Log what the output would be, but take no action.'
| def do_dry_run(self):
| show_dry_run(self.index_list, 'replicas', count=self.count)
|
'Update the replica count of indices in `index_list.indices`'
| def do_action(self):
| self.index_list.empty_list_check()
self.loggit.debug('Cannot get update replica count of closed indices. Omitting any closed indices.')
self.index_list.filter_closed()
self.loggit.info('Setting the replica count to {0} for indices: {1}'.format... |
':arg client: An :class:`elasticsearch.Elasticsearch` client object
:arg name: The name of the single-index-mapped alias to test for
rollover conditions.
:new_index: The new index name
:arg conditions: A dictionary of conditions to test
:arg extra_settings: Must be either `None`, or a dictionary of settings
to apply to... | def __init__(self, client, name, conditions, new_index=None, extra_settings=None, wait_for_active_shards=1):
| verify_client_object(client)
self.loggit = logging.getLogger('curator.actions.rollover')
if (not isinstance(conditions, dict)):
raise ConfigurationError('"conditions" must be a dictionary')
else:
self.loggit.debug('"conditions" is {0}'.format(conditions))
if ((not i... |
'Create a body from conditions and settings'
| def body(self):
| retval = {}
retval['conditions'] = self.conditions
if self.settings:
retval['settings'] = self.settings
return retval
|
'This exists solely to prevent having to have duplicate code in both
`do_dry_run` and `do_action`'
| def doit(self, dry_run=False):
| return self.client.indices.rollover(alias=self.name, new_index=self.new_index, body=self.body(), dry_run=dry_run, wait_for_active_shards=self.wait_for_active_shards)
|
'Log what the output would be, but take no action.'
| def do_dry_run(self):
| logger.info('DRY-RUN MODE. No changes will be made.')
result = self.doit(dry_run=True)
logger.info('DRY-RUN: rollover: {0} result: {1}'.format(self.name, result))
|
'Rollover the index referenced by alias `name`'
| def do_action(self):
| self.loggit.info('Performing index rollover')
try:
self.doit()
except Exception as e:
report_failure(e)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.