id: elasticsearch-mapping-explosion-guard
namespace: company.team
description: |
Catch Elasticsearch indices whose field count is closing in on index.mapping.total_fields.limit
because dynamic mapping keeps adding fields from user-controlled keys. The flow names the object
where new fields keep appearing, alerts Slack once per change with the top paths and sample keys,
and with on-call approval makes that object dynamic: false (or flattened for new indices), then
re-reads the mappings to confirm the fix.
triggers:
- id: explosion_reported
type: io.kestra.plugin.core.trigger.Webhook
key: "{{ secret('ES_MAPPING_GUARD_WEBHOOK_KEY') }}"
description: Call this when a log pipeline or alert reports a field explosion,
e.g. `curl -X POST
"http://localhost:8080/api/v1/executions/webhook/company.team/elasticsearch-mapping-explosion-guard/$KEY"`,
where `$KEY` is the value of the ES_MAPPING_GUARD_WEBHOOK_KEY secret.
- id: hourly_check
type: io.kestra.plugin.core.trigger.Schedule
cron: "23 * * * *"
disabled: true
description: Hourly sweep, off by default. Turn it on once the secrets and
inputs are set; the webhook is the event-based entry point.
inputs:
- id: es_url
type: STRING
defaults: http://localhost:9200
description: Base URL of the cluster. Use the HTTPS endpoint in production,
because the basic-auth secrets are sent to it.
- id: index_pattern
type: STRING
defaults: user-events-*
description: Indices to watch, as an Elasticsearch wildcard. Use the prefix of
the indices that take user-controlled keys (events, attributes, tags).
- id: field_warn_percent
type: FLOAT
defaults: 70
description: Warn when an index uses this share of its total_fields limit. The
default limit is 1000, and an index that is 70% full has little room for a
burst of new keys.
- id: field_critical_percent
type: FLOAT
defaults: 90
description: Critical level. At this share one more burst of dynamic keys can
make the index reject documents, so on-call is asked to act.
- id: object_growth_min
type: INT
defaults: 20
description: Mapped fields added under one object between two runs that name the
object as an explosion. A string key maps two fields (the text field and
its keyword sub-field), so 10 new string keys count as 20. Lower it for
small indices; raise it where many fields are expected.
- id: write_alias
type: STRING
required: false
description: Write alias that receives new documents. Needed to pick the write
index and to roll over. Leave it empty to apply the fix to every index
that shows the explosion.
- id: index_template
type: STRING
required: false
description: Composable index template that new indices are created from, e.g.
user-events-template. Its mapping gets the same fix, so the next index is
not affected. Leave it empty to skip the template.
- id: rollover_on_approval
type: BOOL
defaults: false
description: After an approved fix, roll the write alias over so the next index
is created from the patched template. Needs write_alias. Rolling over is
not undone by the flow, so it is off by default.
- id: kestra_url
type: STRING
defaults: http://localhost:8080
description: Base URL of your Kestra UI, used for the link to the approval form
in Slack.
variables:
# One baseline per cluster and index pattern, so two copies of this flow (or two inputs) never share state.
baseline_key: "es_mapping_baseline_{{ (inputs.es_url ~ '|' ~
inputs.index_pattern) | sha256 }}"
tasks:
- id: validate_inputs
type: io.kestra.plugin.core.flow.If
description: Reject inconsistent settings before any request reaches the cluster.
condition: >-
{{ inputs.field_warn_percent >= inputs.field_critical_percent
or (inputs.index_pattern | trim) == ''
or (inputs.rollover_on_approval and (inputs.write_alias ?? '') == '') }}
then:
- id: invalid_settings
type: io.kestra.plugin.core.execution.Fail
errorMessage: "Invalid settings: warn must be below critical, index_pattern must
not be empty, and rollover_on_approval needs write_alias. Fix the
inputs and run again"
- id: check_cluster
type: io.kestra.plugin.core.http.Request
description: Fail fast when the cluster is unreachable or the credentials are rejected.
uri: "{{ inputs.es_url }}/"
method: GET
options:
allowFailed: true
timeout:
connectTimeout: PT10S
readIdleTimeout: PT60S
auth:
type: BASIC
username: "{{ secret('ELASTICSEARCH_USERNAME') }}"
password: "{{ secret('ELASTICSEARCH_PASSWORD') }}"
retry:
type: exponential
interval: PT2S
maxInterval: PT30S
maxAttempts: 3
- id: cluster_rejected
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.check_cluster.code >= 400 }}"
then:
- id: fail_cluster
type: io.kestra.plugin.core.execution.Fail
errorMessage: "Elasticsearch at {{ inputs.es_url }} answered HTTP {{
outputs.check_cluster.code }}: {{ (outputs.check_cluster.body |
jq('.error.reason') | first) ?? 'no error body' }}. Check
ELASTICSEARCH_USERNAME and ELASTICSEARCH_PASSWORD"
- id: fetch_mappings
type: io.kestra.plugin.core.http.Request
description: Mapping of every index that matches the pattern. The field count is
read from this response.
uri: "{{ inputs.es_url }}/{{ inputs.index_pattern }}/_mapping"
method: GET
options:
allowFailed: true
timeout:
connectTimeout: PT10S
readIdleTimeout: PT60S
auth:
type: BASIC
username: "{{ secret('ELASTICSEARCH_USERNAME') }}"
password: "{{ secret('ELASTICSEARCH_PASSWORD') }}"
retry:
type: exponential
interval: PT2S
maxInterval: PT30S
maxAttempts: 3
- id: mappings_rejected
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.fetch_mappings.code >= 400 }}"
then:
- id: fail_mappings
type: io.kestra.plugin.core.execution.Fail
errorMessage: "Could not read the mappings of {{ inputs.index_pattern }}: HTTP
{{ outputs.fetch_mappings.code }}, {{ (outputs.fetch_mappings.body |
jq('.error.reason') | first) ?? 'no error body' }}"
- id: fetch_limits
type: io.kestra.plugin.core.http.Request
description: The total_fields limit of each index. include_defaults returns the
cluster default for indices that do not set their own.
uri: "{{ inputs.es_url }}/{{ inputs.index_pattern
}}/_settings/index.mapping.total_fields.limit?flat_settings=true&include_\
defaults=true"
method: GET
options:
allowFailed: true
timeout:
connectTimeout: PT10S
readIdleTimeout: PT60S
auth:
type: BASIC
username: "{{ secret('ELASTICSEARCH_USERNAME') }}"
password: "{{ secret('ELASTICSEARCH_PASSWORD') }}"
retry:
type: exponential
interval: PT2S
maxInterval: PT30S
maxAttempts: 3
- id: limits_rejected
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.fetch_limits.code >= 400 }}"
then:
- id: fail_limits
type: io.kestra.plugin.core.execution.Fail
errorMessage: "Could not read the total_fields limits of {{ inputs.index_pattern
}}: HTTP {{ outputs.fetch_limits.code }}, {{
(outputs.fetch_limits.body | jq('.error.reason') | first) ?? 'no error
body' }}"
- id: write_alias_lookup
type: io.kestra.plugin.core.flow.If
description: Only when a write alias is given, look up which index receives writes.
condition: "{{ (inputs.write_alias ?? '') != '' }}"
then:
- id: fetch_alias
type: io.kestra.plugin.core.http.Request
uri: "{{ inputs.es_url }}/_alias/{{ inputs.write_alias }}"
method: GET
options:
allowFailed: true
timeout:
connectTimeout: PT10S
readIdleTimeout: PT60S
auth:
type: BASIC
username: "{{ secret('ELASTICSEARCH_USERNAME') }}"
password: "{{ secret('ELASTICSEARCH_PASSWORD') }}"
retry:
type: exponential
interval: PT2S
maxInterval: PT30S
maxAttempts: 3
- id: alias_rejected
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.fetch_alias.code >= 400 }}"
then:
- id: fail_alias
type: io.kestra.plugin.core.execution.Fail
errorMessage: "Write alias {{ inputs.write_alias }} could not be read: HTTP {{
outputs.fetch_alias.code }}, {{ (outputs.fetch_alias.body |
jq('.error.reason') | first) ?? 'no error body' }}"
- id: analyze
type: io.kestra.plugin.scripts.python.Script
description: Count the fields of every index and compare them with the baseline
in the KV store. New fields are grouped by the object they were added
under. Standard library only.
taskRunner:
type: io.kestra.plugin.core.runner.Process
inputFiles:
mappings.json: "{{ outputs.fetch_mappings.body }}"
limits.json: "{{ outputs.fetch_limits.body }}"
alias.json: "{{ outputs.fetch_alias.body ?? '{}' }}"
state.json: "{{ (kv(render(vars.baseline_key), errorOnMissing=false) ?? {}) |
toJson }}"
params.json: "{{ {'warn': inputs.field_warn_percent, 'critical':
inputs.field_critical_percent, 'min_growth': inputs.object_growth_min,
'write_alias': inputs.write_alias ?? '', 'template':
inputs.index_template ?? '', 'rollover': inputs.rollover_on_approval} |
toJson }}"
outputFiles:
- new_state.json
- report.json
script: |
import json
KEY = 'index.mapping.total_fields.limit'
params = json.load(open('params.json'))
mappings = json.load(open('mappings.json'))
limits = json.load(open('limits.json'))
alias = json.load(open('alias.json'))
state = json.load(open('state.json')) or {}
default_limit = 1000
for entry in limits.values():
if (entry.get('defaults') or {}).get(KEY):
default_limit = int(entry['defaults'][KEY])
break
def ancestors(p, new_top):
# deepest object first; '(root)' only collects keys that are new at the top level of the document,
# so scattered growth inside existing objects is never turned into a root-wide dynamic: false
parts = p.split('.')
out = ['.'.join(parts[:i]) for i in range(len(parts) - 1, 0, -1)]
if parts[0] in new_top:
out.append('(root)')
return out
def walk(props, prefix, out):
# every object and leaf counts toward the limit, and so does every multi-field
for name, spec in (props or {}).items():
path = prefix + '.' + name if prefix else name
out.append(path)
spec = spec or {}
walk(spec.get('properties'), path, out)
for sub in (spec.get('fields') or {}):
out.append(path + '.' + sub)
return out
write_index = None
if params['write_alias']:
for idx, entry in alias.items():
if ((entry.get('aliases') or {}).get(params['write_alias']) or {}).get('is_write_index'):
write_index = idx
if write_index is None and len(alias) == 1:
write_index = list(alias)[0]
if write_index is None:
raise ValueError('write_alias %s has no write index' % params['write_alias'])
report, new_state, alerts, offenders_all = {}, {}, [], []
for idx in sorted(mappings):
paths = walk((mappings[idx].get('mappings') or {}).get('properties'), '', [])
limit = int(((limits.get(idx) or {}).get('settings') or {}).get(KEY) or default_limit)
used = round(100.0 * len(paths) / limit, 2)
level = 'critical' if used >= params['critical'] else ('warn' if used >= params['warn'] else 'ok')
prev = state.get(idx)
new = []
new_top = set()
if prev is not None:
seen = set(prev.get('paths', []))
new = [p for p in paths if p not in seen]
old_top = {p.split('.')[0] for p in seen}
new_top = {p.split('.')[0] for p in new} - old_top
# a new path belongs to the deepest object above it that gained min_growth fields
counts = {}
for p in new:
for a in ancestors(p, new_top):
counts[a] = counts.get(a, 0) + 1
groups = {}
for p in new:
for a in ancestors(p, new_top):
if counts[a] >= params['min_growth']:
groups.setdefault(a, []).append(p)
break
# report a group only when its own members reach the threshold, not just its subtree
groups = {k: v for k, v in groups.items() if len(v) >= params['min_growth']}
offenders = []
for parent, ps in groups.items():
kids = sorted({(p if parent == '(root)' else p[len(parent) + 1:]).split('.')[0] for p in ps})
offenders.append({'index': idx, 'parent': parent, 'new': len(ps), 'keys': kids[:5], 'key_count': len(kids)})
offenders.sort(key=lambda o: -o['new'])
offenders_all.extend(offenders)
prev_level = prev.get('level', 'ok') if prev else 'ok'
level_changed = level != 'ok' and level != prev_level
if offenders or level_changed:
lines = []
for o in offenders[:3]:
lines.append('- %s: %d new mapped fields under `%s` (%d new keys since the last check, e.g. %s)' % (idx, o['new'], o['parent'], o['key_count'], ', '.join(o['keys'])))
if not offenders:
lines.append('- %s: %s, %s of %s fields (%s%% of the limit)' % (idx, level, '{:,}'.format(len(paths)), '{:,}'.format(limit), used))
alerts.extend(lines)
report[idx] = {'fields': len(paths), 'limit': limit, 'used_percent': used, 'level': level,
'new_fields': len(new), 'offenders': offenders}
new_state[idx] = {'paths': paths, 'level': level}
top = offenders_all[0] if offenders_all else None
target_parent = top['parent'] if top else ''
target_indices = sorted({o['index'] for o in offenders_all if o['parent'] == target_parent}) if top else []
if top and params['write_alias']:
write_targets = [write_index]
else:
write_targets = target_indices
def dyn_body(parent):
# PUT _mapping body that sets dynamic: false on the object, creating the path if needed
if parent == '(root)':
return {'dynamic': False}
node = {'type': 'object', 'dynamic': False}
for name in reversed(parent.split('.')):
node = {'properties': {name: node}}
return node
if alerts:
text = 'Elasticsearch mapping guard: field limit alert\n' + '\n'.join(alerts)
if top:
text += '\nDecision needed. Proposed fix, applied only if approved within 2 hours: set `%s` to dynamic false on %s' % (
target_parent, ', '.join(write_targets) or 'the matching indices')
if params['template']:
text += ', and on template `%s` (dynamic false, or flattened for new indices)' % params['template']
text += '.'
if params['rollover'] and params['write_alias']:
text += ' Then roll over `%s`.' % params['write_alias']
else:
text = ''
print('::' + json.dumps({'outputs': {
'needs_alert': 'true' if alerts else 'false',
'needs_decision': 'true' if top else 'false',
'alert_text': text,
'target_parent': target_parent,
'targets': json.dumps(write_targets),
'mapping_body': json.dumps(dyn_body(target_parent)) if top else '',
'report_json': json.dumps(report)
}}) + '::')
json.dump(new_state, open('new_state.json', 'w'))
json.dump(report, open('report.json', 'w'))
- id: alert_change
type: io.kestra.plugin.core.flow.If
description: One Slack message per change. A run with nothing new and no level
change posts nothing.
condition: "{{ outputs.analyze.vars.needs_alert == 'true' }}"
then:
- id: notify_change
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
messageText: |
{{ outputs.analyze.vars.alert_text }}
Review: {{ inputs.kestra_url }}/ui/main/executions/{{ flow.namespace }}/{{ flow.id }}/{{ execution.id }}
retry:
type: exponential
interval: PT2S
maxInterval: PT30S
maxAttempts: 3
- id: store_baseline
type: io.kestra.plugin.core.kv.Set
description: Advance the baseline only after the alert went out. If Slack
failed, the next run sees the same new fields again and alerts.
key: "{{ render(vars.baseline_key) }}"
kvType: JSON
value: "{{ read(outputs.analyze.outputFiles['new_state.json']) }}"
- id: decide
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.analyze.vars.needs_decision == 'true' }}"
then:
- id: wait_for_decision
type: io.kestra.plugin.core.flow.Pause
description: Waits for on-call. No answer within two hours resumes with the
defaults, so nothing changes.
pauseDuration: PT2H
behavior: RESUME
onResume:
- id: apply_fix
type: BOOL
defaults: false
description: Apply the proposed fix to the template and the write index.
- id: template_mode
type: SELECT
values:
- dynamic_false
- flattened
defaults: dynamic_false
required: true
description: For new indices, dynamic false keeps the object's keys in _source
only, while flattened stores the whole object as one field.
Existing indices always get dynamic false.
- id: apply
type: io.kestra.plugin.core.flow.If
description: A Pause that times out resumes without onResume values, so both
reads fall back to the defaults.
condition: "{{ ((outputs.wait_for_decision.onResume ?? {}).apply_fix ?? false)
== true }}"
then:
- id: template_patch
type: io.kestra.plugin.core.flow.If
description: The template fix is what keeps new indices from exploding again.
condition: "{{ (inputs.index_template ?? '') != '' }}"
then:
- id: get_template
type: io.kestra.plugin.core.http.Request
uri: "{{ inputs.es_url }}/_index_template/{{ inputs.index_template }}"
method: GET
options:
allowFailed: true
timeout:
connectTimeout: PT10S
readIdleTimeout: PT60S
auth:
type: BASIC
username: "{{ secret('ELASTICSEARCH_USERNAME') }}"
password: "{{ secret('ELASTICSEARCH_PASSWORD') }}"
retry:
type: exponential
interval: PT2S
maxInterval: PT30S
maxAttempts: 3
- id: get_template_rejected
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.get_template.code >= 400 }}"
then:
- id: fail_get_template
type: io.kestra.plugin.core.execution.Fail
errorMessage: "Could not read index template {{ inputs.index_template }}: HTTP
{{ outputs.get_template.code }}, {{
(outputs.get_template.body | jq('.error.reason') | first)
?? 'no error body' }}"
- id: build_template
type: io.kestra.plugin.scripts.python.Script
description: Set the object in the template to dynamic false or flattened.
Everything else in the template is kept as it was.
taskRunner:
type: io.kestra.plugin.core.runner.Process
inputFiles:
template.json: "{{ outputs.get_template.body }}"
params.json: "{{ {'parent': outputs.analyze.vars.target_parent, 'mode':
((outputs.wait_for_decision.onResume ?? {}).template_mode ??
'dynamic_false')} | toJson }}"
script: |
import json
body = (json.load(open('template.json')).get('index_templates') or [{}])[0].get('index_template') or {}
params = json.load(open('params.json'))
template = body.setdefault('template', {})
mappings = template.setdefault('mappings', {})
parent = params['parent']
if parent == '(root)':
mappings['dynamic'] = False
else:
cur = mappings
parts = parent.split('.')
for i, name in enumerate(parts):
props = cur.setdefault('properties', {})
node = props.setdefault(name, {'type': 'object'})
if i == len(parts) - 1:
if params['mode'] == 'flattened':
props[name] = {'type': 'flattened'}
else:
node['dynamic'] = False
cur = node
print('::' + json.dumps({'outputs': {'body': json.dumps(body)}}) + '::')
- id: put_template
type: io.kestra.plugin.core.http.Request
uri: "{{ inputs.es_url }}/_index_template/{{ inputs.index_template }}"
method: PUT
contentType: application/json
body: "{{ outputs.build_template.vars.body }}"
options:
allowFailed: true
timeout:
connectTimeout: PT10S
readIdleTimeout: PT60S
auth:
type: BASIC
username: "{{ secret('ELASTICSEARCH_USERNAME') }}"
password: "{{ secret('ELASTICSEARCH_PASSWORD') }}"
retry:
type: exponential
interval: PT2S
maxInterval: PT30S
maxAttempts: 3
- id: put_template_rejected
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.put_template.code >= 400 }}"
then:
- id: fail_put_template
type: io.kestra.plugin.core.execution.Fail
errorMessage: "Index template {{ inputs.index_template }} was not patched: HTTP
{{ outputs.put_template.code }}, {{
(outputs.put_template.body | jq('.error.reason') | first)
?? 'no error body' }}"
- id: get_template_after
type: io.kestra.plugin.core.http.Request
description: Read the template back so the outcome reports what the cluster
stored.
uri: "{{ inputs.es_url }}/_index_template/{{ inputs.index_template }}"
method: GET
options:
allowFailed: true
timeout:
connectTimeout: PT10S
readIdleTimeout: PT60S
auth:
type: BASIC
username: "{{ secret('ELASTICSEARCH_USERNAME') }}"
password: "{{ secret('ELASTICSEARCH_PASSWORD') }}"
retry:
type: exponential
interval: PT2S
maxInterval: PT30S
maxAttempts: 3
- id: write_mapping
type: io.kestra.plugin.core.flow.Loop
description: One _mapping update per target index. Each one is isolated, so a
failing index does not stop the others; the recheck reports what
actually changed.
values: "{{ outputs.analyze.vars.targets }}"
tasks:
- id: put_one
type: io.kestra.plugin.core.flow.Sequential
allowFailure: true
tasks:
- id: put_mapping
type: io.kestra.plugin.core.http.Request
uri: "{{ inputs.es_url }}/{{ item.value }}/_mapping"
method: PUT
contentType: application/json
body: "{{ outputs.analyze.vars.mapping_body }}"
options:
allowFailed: true
timeout:
connectTimeout: PT10S
readIdleTimeout: PT60S
auth:
type: BASIC
username: "{{ secret('ELASTICSEARCH_USERNAME') }}"
password: "{{ secret('ELASTICSEARCH_PASSWORD') }}"
retry:
type: exponential
interval: PT2S
maxInterval: PT30S
maxAttempts: 3
- id: rollover
type: io.kestra.plugin.core.flow.If
description: The next write index is created from the patched template, so it
does not explode the same way.
condition: "{{ inputs.rollover_on_approval == true and (inputs.write_alias ??
'') != '' }}"
then:
- id: rollover_alias
type: io.kestra.plugin.core.http.Request
uri: "{{ inputs.es_url }}/{{ inputs.write_alias }}/_rollover"
method: POST
contentType: application/json
body: "{}"
options:
allowFailed: true
timeout:
connectTimeout: PT10S
readIdleTimeout: PT60S
auth:
type: BASIC
username: "{{ secret('ELASTICSEARCH_USERNAME') }}"
password: "{{ secret('ELASTICSEARCH_PASSWORD') }}"
retry:
type: exponential
interval: PT2S
maxInterval: PT30S
maxAttempts: 3
- id: rollover_rejected
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.rollover_alias.code >= 400 }}"
then:
- id: fail_rollover
type: io.kestra.plugin.core.execution.Fail
errorMessage: "Rollover of {{ inputs.write_alias }} failed: HTTP {{
outputs.rollover_alias.code }}, {{
(outputs.rollover_alias.body | jq('.error.reason') |
first) ?? 'no error body' }}. The mapping fix was applied;
roll over by hand once this is resolved"
- id: recheck_mappings
type: io.kestra.plugin.core.http.Request
description: Read the mappings again after the change, including any index
created by the rollover.
uri: "{{ inputs.es_url }}/{{ inputs.index_pattern }}/_mapping"
method: GET
options:
allowFailed: true
timeout:
connectTimeout: PT10S
readIdleTimeout: PT60S
auth:
type: BASIC
username: "{{ secret('ELASTICSEARCH_USERNAME') }}"
password: "{{ secret('ELASTICSEARCH_PASSWORD') }}"
retry:
type: exponential
interval: PT2S
maxInterval: PT30S
maxAttempts: 3
- id: recheck_limits
type: io.kestra.plugin.core.http.Request
uri: "{{ inputs.es_url }}/{{ inputs.index_pattern
}}/_settings/index.mapping.total_fields.limit?flat_settings=true&\
include_defaults=true"
method: GET
options:
allowFailed: true
timeout:
connectTimeout: PT10S
readIdleTimeout: PT60S
auth:
type: BASIC
username: "{{ secret('ELASTICSEARCH_USERNAME') }}"
password: "{{ secret('ELASTICSEARCH_PASSWORD') }}"
retry:
type: exponential
interval: PT2S
maxInterval: PT30S
maxAttempts: 3
- id: recheck
type: io.kestra.plugin.scripts.python.Script
description: Count the fields again and check that the target object is now
dynamic false (or flattened) in each index and in the template.
taskRunner:
type: io.kestra.plugin.core.runner.Process
inputFiles:
before.json: "{{ outputs.analyze.outputFiles['report.json'] }}"
after.json: "{{ outputs.recheck_mappings.body }}"
limits.json: "{{ outputs.recheck_limits.body }}"
template_after.json: "{{ outputs.get_template_after.body ?? '{}' }}"
params.json: "{{ {'parent': outputs.analyze.vars.target_parent, 'mode':
((outputs.wait_for_decision.onResume ?? {}).template_mode ??
'dynamic_false'), 'template': inputs.index_template ?? '',
'write_alias': inputs.write_alias ?? '', 'rollover':
outputs.rollover_alias.code ?? '', 'put':
outputs.put_template.code ?? 'skipped', 'targets':
outputs.analyze.vars.targets, 'mappings_code':
outputs.recheck_mappings.code, 'limits_code':
outputs.recheck_limits.code} | toJson }}"
script: |
import json
KEY = 'index.mapping.total_fields.limit'
before = json.load(open('before.json'))
after = json.load(open('after.json'))
limits = json.load(open('limits.json'))
params = json.load(open('params.json'))
tpl_entry = (json.load(open('template_after.json')).get('index_templates') or [{}])[0]
tpl_mappings = ((tpl_entry.get('index_template') or {}).get('template') or {}).get('mappings') or {}
parent = params['parent']
# an error body (4xx/5xx) is not a mapping: report it instead of reading it as indices
def failed(code, body):
return int(code) >= 400 or 'error' in body
if failed(params['mappings_code'], after) or failed(params['limits_code'], limits):
bad = after if failed(params['mappings_code'], after) else limits
err = bad.get('error')
reason = (err.get('reason') if isinstance(err, dict) else err) or 'no error body'
head = 'Elasticsearch mapping guard: fix sent for `%s`, but the result could not be read back (HTTP %s/%s: %s). Check the mappings by hand.' % (
parent, params['mappings_code'], params['limits_code'], reason)
print('::' + json.dumps({'outputs': {'outcome': head, 'fixed': 'false'}}) + '::')
raise SystemExit(0)
default_limit = 1000
for entry in limits.values():
if (entry.get('defaults') or {}).get(KEY):
default_limit = int(entry['defaults'][KEY])
break
def walk(props, prefix, out):
for name, spec in (props or {}).items():
path = prefix + '.' + name if prefix else name
out.append(path)
spec = spec or {}
walk(spec.get('properties'), path, out)
for sub in (spec.get('fields') or {}):
out.append(path + '.' + sub)
return out
def describe(root, parent):
node = root
if parent != '(root)':
for name in parent.split('.'):
node = ((node or {}).get('properties') or {}).get(name)
if node is None:
return 'not mapped'
if node.get('type') == 'flattened':
return 'flattened'
if str(node.get('dynamic', 'true')).lower() == 'false':
return 'dynamic false'
return 'still dynamic'
lines = []
done = True
for idx in sorted(after):
root = after[idx].get('mappings') or {}
count = len(walk(root.get('properties'), '', []))
limit = int(((limits.get(idx) or {}).get('settings') or {}).get(KEY) or default_limit)
state = describe(root, parent)
if idx in before:
head = '%s: %s of %s fields before, %s after' % (idx, '{:,}'.format(before[idx]['fields']), '{:,}'.format(before[idx]['limit']), '{:,}'.format(count))
else:
head = '%s: new index, %s fields of %s' % (idx, '{:,}'.format(count), '{:,}'.format(limit))
if idx in params['targets'] or idx not in before:
if state not in ('dynamic false', 'flattened'):
done = False
lines.append('- %s, `%s`: %s' % (head, parent, state))
else:
lines.append('- %s' % head)
if params['template']:
tstate = describe(tpl_mappings, parent)
if tstate not in ('dynamic false', 'flattened'):
done = False
lines.append('- Template `%s`, `%s`: %s' % (params['template'], parent, tstate))
else:
lines.append('- No template configured: new indices still map `%s` dynamically' % parent)
if params['rollover'] != '' and params['write_alias']:
lines.append('- Rollover of `%s`: HTTP %s' % (params['write_alias'], params['rollover']))
head = ('Elasticsearch mapping guard: fix applied to `%s`, %s' % (parent, 'all targets fixed' if done else 'NOT fully fixed, see below'))
print('::' + json.dumps({'outputs': {'outcome': head + '\n' + '\n'.join(lines), 'fixed': 'true' if done else 'false'}}) + '::')
- id: notify_outcome
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
messageText: |
{{ outputs.recheck.vars.outcome }}
Run: {{ inputs.kestra_url }}/ui/main/executions/{{ flow.namespace }}/{{ flow.id }}/{{ execution.id }}
retry:
type: exponential
interval: PT2S
maxInterval: PT30S
maxAttempts: 3
else:
- id: notify_no_change
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
messageText: "Elasticsearch mapping guard: no fix was applied to `{{
outputs.analyze.vars.target_parent }}` (declined or no answer
within 2 hours). Nothing was changed."
retry:
type: exponential
interval: PT2S
maxInterval: PT30S
maxAttempts: 3
errors:
- id: alert_failure
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
messageText: >-
Elasticsearch mapping guard failed in execution {{ execution.id }} {% if
errorLogs() | length > 0 %}at `{{ errorLogs()[0]['taskId'] }}`: {{
errorLogs()[0]['message'] | split(' \[\[') | first }}{% else %}without an
error message{% endif %}. {{ inputs.kestra_url }}/ui/main/executions/{{
flow.namespace }}/{{ flow.id }}/{{ execution.id }}
outputs:
- id: indices
type: JSON
description: Field count, limit, usage and level of each matched index, with the
new fields since the last run.
value: "{{ outputs.analyze.vars.report_json ?? '{}' }}"