id: sqlserver-datafile-space-exhaustion-guard
namespace: company.team
description: |
Find SQL Server data files that are close to running out of space and heading
for error 1105. The audit reads the used space, file size, MAXSIZE and growth
increment for every ROWS data file in the connected database from
sys.database_files and FILEPROPERTY, reads the volume free space from
sys.dm_os_volume_stats, works out the real headroom, alerts Slack, then behind
a safe by default gate and a human approval it raises MAXSIZE, pre-grows the
file and sets a sane fixed FILEGROWTH with one ALTER DATABASE MODIFY FILE. It
re-reads sys.database_files afterwards and fails the run if the real headroom
is still below the floor. A file on a full volume cannot be grown, so it is
reported rather than touched. Only ONLINE FULL or SIMPLE user databases are
considered, never master, model, msdb or tempdb.
inputs:
- id: url
type: STRING
displayName: JDBC URL
description: Points at the database to check. Used space comes from the
connected database, so include the database in the URL, for example
jdbc:sqlserver://host:1433;databaseName=app.
defaults: "jdbc:sqlserver://localhost:1433"
- id: user
type: STRING
displayName: SQL Server login
defaults: sa
- id: password
type: STRING
displayName: SQL Server password
description: Defaults to the SQLSERVER_PASSWORD secret. Override only for local testing.
defaults: "{{ secret('SQLSERVER_PASSWORD') }}"
- id: used_pct_threshold
type: INT
displayName: Used percentage threshold
description: Flag a capped data file once its used space reaches this share of
its MAXSIZE. Above it the file is close to the hard ceiling that produces
error 1105.
defaults: 80
- id: min_headroom_mb
type: INT
displayName: Minimum headroom in MB
description: Flag any data file with less real headroom than this. The run also
fails if the headroom is still below it after the grow. Headroom is the
free space in the file plus the smaller of the room left to MAXSIZE and
the free space on the volume.
defaults: 256
- id: volume_free_floor_mb
type: INT
displayName: Volume free floor in MB
description: Flag an unlimited growth data file whose volume has less free space
than this. An unlimited file on a full volume is a disk problem, so it is
reported, not grown.
defaults: 2048
- id: min_file_size_mb
type: INT
displayName: Minimum file size in MB
description: Ignore data files smaller than this. A tiny file is noise and grows
past the number before it threatens anything.
defaults: 8
- id: min_growth_mb
type: INT
displayName: Minimum healthy growth in MB
description: A fixed FILEGROWTH under this is unsafe. Any percent growth is
unsafe too. A file that cannot grow in sane steps reaches its ceiling in
many tiny jumps.
defaults: 16
- id: target_maxsize_mb
type: INT
displayName: Target MAXSIZE in MB
description: The MAXSIZE a grown file is raised to. The flow never sets a
MAXSIZE below the new file size or the current MAXSIZE, so a large file is
raised above its new size and a bigger existing cap is kept.
defaults: 10240
- id: filegrowth_mb
type: INT
displayName: Fixed FILEGROWTH in MB
description: The fixed growth increment left on the file, so future growth adds
space in sane steps instead of stalling or overshooting.
defaults: 256
- id: auto_remediate
type: BOOL
displayName: Auto remediate
description: Allow the ALTER DATABASE MODIFY FILE statements to run.
defaults: false
- id: dry_run
type: BOOL
displayName: Dry run
description: Must be false, together with auto_remediate, before any statement runs.
defaults: true
variables:
audit_sql: |
WITH files AS (
SELECT df.name AS logical_name, df.physical_name, df.file_id,
CAST(df.size AS bigint) * 8 / 1024 AS size_mb,
CASE WHEN df.max_size = -1 THEN -1 ELSE CAST(df.max_size AS bigint) * 8 / 1024 END AS max_size_mb,
df.is_percent_growth,
CASE WHEN df.is_percent_growth = 1 THEN CAST(df.growth AS bigint) ELSE CAST(df.growth AS bigint) * 8 / 1024 END AS growth_setting,
CAST(FILEPROPERTY(df.name, 'SpaceUsed') AS bigint) * 8 / 1024 AS used_mb,
vs.total_bytes / 1048576 AS volume_total_mb,
vs.available_bytes / 1048576 AS volume_avail_mb
FROM sys.database_files df
CROSS APPLY sys.dm_os_volume_stats(DB_ID(), df.file_id) vs
WHERE df.type_desc = 'ROWS' AND df.state_desc = 'ONLINE'
),
scored AS (
SELECT *,
CASE WHEN max_size_mb = -1 THEN (size_mb - used_mb) + volume_avail_mb
ELSE (size_mb - used_mb) + CASE WHEN (max_size_mb - size_mb) < volume_avail_mb THEN (max_size_mb - size_mb) ELSE volume_avail_mb END
END AS headroom_mb,
CASE WHEN max_size_mb = -1 THEN NULL ELSE CAST(100.0 * used_mb / NULLIF(max_size_mb, 0) AS DECIMAL(5, 1)) END AS used_pct,
CASE WHEN is_percent_growth = 1 OR growth_setting = 0 OR (is_percent_growth = 0 AND growth_setting < {{ inputs.min_growth_mb }}) THEN 1 ELSE 0 END AS unsafe_growth,
CASE WHEN size_mb > used_mb + {{ inputs.min_headroom_mb }} THEN size_mb ELSE used_mb + {{ inputs.min_headroom_mb }} END AS new_size_mb
FROM files
WHERE size_mb >= {{ inputs.min_file_size_mb }}
),
sized AS (
SELECT *,
CASE WHEN {{ inputs.target_maxsize_mb }} > new_size_mb + {{ inputs.filegrowth_mb }} THEN {{ inputs.target_maxsize_mb }} ELSE new_size_mb + {{ inputs.filegrowth_mb }} END AS wanted_max_mb
FROM scored
),
planned AS (
SELECT *, CASE WHEN wanted_max_mb > max_size_mb THEN wanted_max_mb ELSE max_size_mb END AS new_max_mb
FROM sized
)
SELECT DB_NAME() AS database_name,
CONVERT(nvarchar(60), DATABASEPROPERTYEX(DB_NAME(), 'Recovery')) AS recovery_model,
logical_name, physical_name, file_id, size_mb, max_size_mb, is_percent_growth, growth_setting, used_mb,
volume_total_mb, volume_avail_mb, headroom_mb, used_pct, unsafe_growth,
CASE WHEN max_size_mb = -1 THEN 'REPORT_ONLY' ELSE 'GROW_FILE' END AS fix_action,
CONCAT(CHAR(39), REPLACE(logical_name, CHAR(39), CHAR(39) + CHAR(39)), CHAR(39)) AS name_literal,
CASE WHEN max_size_mb = -1 THEN ''
ELSE CONCAT('ALTER DATABASE ', QUOTENAME(DB_NAME()), ' MODIFY FILE (NAME = ', QUOTENAME(logical_name),
', SIZE = ', CAST(new_size_mb AS varchar(20)), 'MB',
', MAXSIZE = ', CAST(new_max_mb AS varchar(20)), 'MB',
', FILEGROWTH = ', CAST({{ inputs.filegrowth_mb }} AS varchar(20)), 'MB)')
END AS resize_sql
FROM planned
WHERE DB_ID() > 4
AND DB_NAME() NOT IN ('master', 'model', 'msdb', 'tempdb')
AND CONVERT(nvarchar(60), DATABASEPROPERTYEX(DB_NAME(), 'Recovery')) IN ('FULL', 'SIMPLE')
AND (
(max_size_mb <> -1 AND (used_pct >= {{ inputs.used_pct_threshold }} OR headroom_mb < {{ inputs.min_headroom_mb }} OR (unsafe_growth = 1 AND used_pct >= {{ inputs.used_pct_threshold }} / 2.0)))
OR (max_size_mb = -1 AND (headroom_mb < {{ inputs.min_headroom_mb }} OR volume_avail_mb < {{ inputs.volume_free_floor_mb }}))
)
ORDER BY headroom_mb ASC
measure_sql: |
WITH files AS (
SELECT df.name AS logical_name,
CAST(df.size AS bigint) * 8 / 1024 AS size_mb,
CASE WHEN df.max_size = -1 THEN -1 ELSE CAST(df.max_size AS bigint) * 8 / 1024 END AS max_size_mb,
df.is_percent_growth,
CASE WHEN df.is_percent_growth = 1 THEN CAST(df.growth AS bigint) ELSE CAST(df.growth AS bigint) * 8 / 1024 END AS growth_setting,
CAST(FILEPROPERTY(df.name, 'SpaceUsed') AS bigint) * 8 / 1024 AS used_mb,
vs.available_bytes / 1048576 AS volume_avail_mb
FROM sys.database_files df
CROSS APPLY sys.dm_os_volume_stats(DB_ID(), df.file_id) vs
WHERE df.type_desc = 'ROWS' AND df.state_desc = 'ONLINE'
),
scored AS (
SELECT *,
CASE WHEN max_size_mb = -1 THEN (size_mb - used_mb) + volume_avail_mb
ELSE (size_mb - used_mb) + CASE WHEN (max_size_mb - size_mb) < volume_avail_mb THEN (max_size_mb - size_mb) ELSE volume_avail_mb END
END AS headroom_mb,
CASE WHEN max_size_mb = -1 THEN NULL ELSE CAST(100.0 * used_mb / NULLIF(max_size_mb, 0) AS DECIMAL(5, 1)) END AS used_pct
FROM files
)
SELECT DB_NAME() AS database_name, logical_name, size_mb, max_size_mb, used_mb, growth_setting, is_percent_growth, headroom_mb, used_pct,
CASE WHEN headroom_mb < {{ inputs.min_headroom_mb }} THEN 1 ELSE 0 END AS still_at_risk
FROM scored
WHERE logical_name IN ({{ outputs.targets.values.grow_files_literal }})
ORDER BY headroom_mb ASC
tasks:
- id: audit
type: io.kestra.plugin.jdbc.sqlserver.Query
description: Read-only. Reads every ROWS data file in the connected database,
its size, MAXSIZE, growth and used space from sys.database_files and
FILEPROPERTY plus the volume free space from sys.dm_os_volume_stats. It
works out the real headroom and keeps the files near their MAXSIZE or on a
near full volume. A system database or a database that is not FULL or
SIMPLE recovery returns nothing.
url: "{{ inputs.url }}"
username: "{{ inputs.user }}"
password: "{{ inputs.password }}"
trustServerCertificate: true
fetchType: FETCH
sql: "{{ render(vars.audit_sql) }}"
- id: targets
type: io.kestra.plugin.core.output.OutputValues
description: Split the findings. Capped files near their ceiling are the grow
plan. Unlimited files on a full volume are report only. Each grow
statement is built in T-SQL with QUOTENAME, so identifiers are quoted by
the server.
values:
plan: "{{ outputs.audit.rows | jq('[.[] | select(.fix_action==\"GROW_FILE\") |
{db: .database_name, logical: .logical_name, resize: .resize_sql, size:
.size_mb, max: .max_size_mb, used: .used_mb, growth: .growth_setting,
headroom: .headroom_mb, used_pct: .used_pct}]') | first | toJson }}"
grow_count: "{{ outputs.audit.rows | jq('[.[] |
select(.fix_action==\"GROW_FILE\")] | length') | first }}"
report_count: "{{ outputs.audit.rows | jq('[.[] |
select(.fix_action==\"REPORT_ONLY\")] | length') | first }}"
grow_files_literal: "{{ outputs.audit.rows | jq('[.[] |
select(.fix_action==\"GROW_FILE\") | .name_literal] | join(\",\")') |
first }}"
- id: summary
type: io.kestra.plugin.core.log.Log
message: >-
SQL Server data file audit on {{ inputs.url }}: {{ outputs.audit.size }}
data file(s) at risk ({{ outputs.targets.values.grow_count }} growable, {{
outputs.targets.values.report_count }} disk level report only). {{
outputs.audit.rows | jq('map("\(.database_name)/\(.logical_name)
used=\(.used_mb)MB size=\(.size_mb)MB max=\(if .max_size_mb == -1 then
"unlimited" else "\(.max_size_mb)MB" end) headroom=\(.headroom_mb)MB
growth=\(if .is_percent_growth == 1 then "\(.growth_setting)pct" else
"\(.growth_setting)MB" end) [\(.fix_action)]") | join("; ")') | first }}
- id: route
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.audit.size > 0 }}"
then:
- id: alert
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{{ {'text': 'SQL Server ' ~ inputs.url ~ ': ' ~ outputs.audit.size ~ ' data file(s) at risk of error 1105: ' ~ (outputs.audit.rows | jq('map("\(.database_name)/\(.logical_name) used=\(.used_mb)MB max=\(if .max_size_mb == -1 then "unlimited" else "\(.max_size_mb)MB" end) headroom=\(.headroom_mb)MB [\(.fix_action)]") | join("; ")') | first) ~ '.' ~ (inputs.auto_remediate and not inputs.dry_run ? ' Waiting for approval to raise MAXSIZE and pre-grow the growable files.' : ' No change applied (auto_remediate=' ~ inputs.auto_remediate ~ ', dry_run=' ~ inputs.dry_run ~ ').')} | toJson }}
- id: remediate_gate
type: io.kestra.plugin.core.flow.If
condition: "{{ inputs.auto_remediate and not inputs.dry_run }}"
then:
- id: approval_gate
type: io.kestra.plugin.core.flow.Pause
description: Hold the run until a human approves. Pre-growing a data file writes
to the volume and briefly loads it, so the change never starts on
its own.
pauseDuration: PT2H
behavior: FAIL
onResume:
- id: approved
type: BOOL
required: false
description: Set true to raise MAXSIZE and pre-grow the listed files. Anything
else leaves them alone.
- id: apply
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.approval_gate.onResume.approved ?? false }}"
then:
- id: grow_branch
type: io.kestra.plugin.core.flow.If
condition: "{{ (outputs.targets.values.grow_count | number) > 0 }}"
then:
- id: remediate
type: io.kestra.plugin.core.flow.Loop
description: Serial on purpose. concurrencyLimit 1 keeps two grows from writing
to the same volume at once. Each statement runs as its own
autocommitting Query because ALTER DATABASE cannot run
inside an explicit transaction. allowFailure is set so a
grow that the volume cannot satisfy routes to the re-read
rather than crashing the run.
concurrencyLimit: 1
values: "{{ outputs.targets.values.plan }}"
tasks:
- id: resize_file
type: io.kestra.plugin.jdbc.sqlserver.Query
description: One ALTER DATABASE MODIFY FILE raises MAXSIZE, pre-grows the file
to leave real headroom now and sets a sane fixed
FILEGROWTH. The pre-grow writes to the volume, so it
can fail if the disk is genuinely full. That failure
is caught by the re-read, never reported as success.
url: "{{ inputs.url }}"
username: "{{ inputs.user }}"
password: "{{ inputs.password }}"
trustServerCertificate: true
fetchType: NONE
allowFailure: true
sql: "{{ fromJson(item.value).resize }}"
- id: after_state
type: io.kestra.plugin.jdbc.sqlserver.Query
description: Read the size, MAXSIZE, used space, growth and real headroom back
for every file the grow touched, whatever the outcome.
url: "{{ inputs.url }}"
username: "{{ inputs.user }}"
password: "{{ inputs.password }}"
trustServerCertificate: true
fetchType: FETCH
sql: "{{ render(vars.measure_sql) }}"
- id: state_log
type: io.kestra.plugin.core.log.Log
message: >-
Before: {{ fromJson(outputs.targets.values.plan) |
jq('map("\(.db)/\(.logical) used=\(.used)MB
size=\(.size)MB max=\(if .max == -1 then "unlimited" else
"\(.max)MB" end) headroom=\(.headroom)MB") | join("; ")')
| first }}. After: {{ outputs.after_state.rows |
jq('map("\(.database_name)/\(.logical_name)
used=\(.used_mb)MB size=\(.size_mb)MB max=\(if
.max_size_mb == -1 then "unlimited" else
"\(.max_size_mb)MB" end) headroom=\(.headroom_mb)MB
growth=\(if .is_percent_growth == 1 then
"\(.growth_setting)pct" else "\(.growth_setting)MB" end)")
| join("; ")') | first }}.
- id: reverify
type: io.kestra.plugin.core.output.OutputValues
description: Count the touched files whose real headroom is still below the
floor. This read trusts the actual volume free space, so a
grow the disk could not satisfy can never report success.
values:
still_count: "{{ outputs.after_state.rows | jq('[.[] | select(.still_at_risk ==
1)] | length') | first }}"
still_list: "{{ outputs.after_state.rows | jq('[.[] | select(.still_at_risk ==
1) | \"\\(.database_name)/\\(.logical_name)
headroom=\\(.headroom_mb)MB\"] | join(\", \")') | first
}}"
- id: verify_result
type: io.kestra.plugin.core.flow.If
condition: "{{ (outputs.reverify.values.still_count | number) > 0 }}"
then:
- id: remediation_failed
type: io.kestra.plugin.core.execution.Fail
errorMessage: "Still short of headroom after the grow: {{
outputs.reverify.values.still_list }}. The ALTER
DATABASE MODIFY FILE could not add space. Either the
volume is full so the pre-grow failed or MAXSIZE is
still below the size the file needs. Free space on the
volume or move the file to a bigger disk, then run
again."
else:
- id: remediated
type: io.kestra.plugin.core.log.Log
message: "Raised MAXSIZE and pre-grew: {{ fromJson(outputs.targets.values.plan)
| jq('map(.logical) | join(\", \")') | first }}. Every
touched data file now has at least {{
inputs.min_headroom_mb }} MB of real headroom and a
fixed {{ inputs.filegrowth_mb }} MB growth increment."
else:
- id: only_report
type: io.kestra.plugin.core.log.Log
message: "Nothing to grow. The {{ outputs.targets.values.report_count }}
finding(s) are unlimited growth files on a near full
volume, which is a disk problem a file grow cannot fix.
Free space on the volume or move the files, then run
again."
else:
- id: declined
type: io.kestra.plugin.core.log.Log
message: "Approval was not given, so no file was grown. The findings stand: {{
outputs.audit.rows |
jq('map(\"\\(.database_name)/\\(.logical_name)
headroom=\\(.headroom_mb)MB [\\(.fix_action)]\") | join(\",
\")') | first }}."
else:
- id: clean
type: io.kestra.plugin.core.log.Log
message: >-
Nothing matched on {{ inputs.url }}: no ONLINE FULL or SIMPLE user
data file is within {{ inputs.min_headroom_mb }} MB of its ceiling,
over {{ inputs.used_pct_threshold }} percent of its MAXSIZE or on a
volume under {{ inputs.volume_free_floor_mb }} MB free. Nothing to
grow or report.
errors:
- id: alert_flow_failure
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{{ {'text': 'SQL Server data file space exhaustion guard failed on ' ~ inputs.url ~ ' (execution ' ~ execution.id ~ '). The audit could not run, the grow was rejected or a touched file still has too little headroom. Check the logs.'} | toJson }}
triggers:
- id: weekly
type: io.kestra.plugin.core.trigger.Schedule
description: Shipped disabled. Always runs in safe mode (audit only).
cron: "0 5 * * 0"
disabled: true
inputs:
auto_remediate: false
dry_run: true