forked from robbrucks/zabbix-postgresql-auto-partitioning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinstall_partitioning.sh
executable file
·229 lines (199 loc) · 8.44 KB
/
install_partitioning.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
#!/bin/bash
dbname=zabbix
dbowner=zabbix
#####################################################################
# install_partitioning.sh
# Sets up Automatic PostgreSQL partitioning for Zabbix history and trend tables
#
# Adapted From:
# https://www.zabbix.org/wiki/Docs/howto/zabbix2_postgresql_autopartitioning
#
# - Must be run as DB super-user
#
# Defaults:
# "history*" tables: daily partitions ("day")
# "trends*" tables: monthly partitions ("month")
#
# You can change the defaults further down in section "add_partition_triggers"
#
# Settings available:
# "day" - create daily partitions
# "month" - create monthly partitions
#
#####################################################################
main () {
echo '================================================================'
date +"%Y-%m-%d %H:%M:%S %Z"
echo "Logging to: ${logfile}"
echo "Settings:"
echo " dbname=${dbname}"
echo " dbowner=${dbowner}"
create_partition_schema || exit 1
create_trigger_function || exit 1
create_cleanup_function || exit 1
add_partition_triggers || exit 1
}
create_partition_schema () {
echo 'create_partition_schema ----------------------------------------'
date +"%Y-%m-%d %H:%M:%S %Z"
psql -Xe -v ON_ERROR_STOP=on ${dbname} <<EOF
CREATE SCHEMA partitions
AUTHORIZATION ${dbowner};
EOF
rc=$?
if [[ $rc -eq 0 ]]; then
echo "=============================="
echo " Schema successfully created."
echo "=============================="
fi
return $rc
}
# create this trigger function owned by postgres
create_trigger_function () {
echo 'create_trigger_function ----------------------------------------'
date +"%Y-%m-%d %H:%M:%S %Z"
psql -Xe -v ON_ERROR_STOP=on ${dbname} <<"EOF"
CREATE OR REPLACE FUNCTION zbx_part_trigger_func() RETURNS trigger AS
$BODY$
DECLARE
prefix text := 'partitions';
timeformat text;
selector text;
_interval interval;
tablename text;
startdate text;
enddate text;
create_table_part text;
create_index_part text;
BEGIN
BEGIN
selector = TG_ARGV[0];
IF selector = 'day' THEN
timeformat := 'YYYY_MM_DD';
ELSIF selector = 'month' THEN
timeformat := 'YYYY_MM';
ELSE
RAISE EXCEPTION 'zbx_part_trigger_func: Specify "day" or "month" for interval selector instead of "%"', selector;
END IF;
_interval := '1 ' || selector;
tablename := TG_TABLE_NAME || '_p' || to_char(to_timestamp(NEW.clock), timeformat);
EXECUTE 'INSERT INTO ' || quote_ident(prefix) || '.' || quote_ident(tablename) || ' SELECT ($1).*' USING NEW;
RETURN NULL;
/* trap when table partition does not yet exist: create the table partition and then insert */
EXCEPTION
WHEN undefined_table THEN
startdate := extract(epoch FROM date_trunc(selector, to_timestamp(NEW.clock)));
enddate := extract(epoch FROM date_trunc(selector, to_timestamp(NEW.clock) + _interval ));
create_table_part := 'CREATE TABLE IF NOT EXISTS ' || quote_ident(prefix) || '.' || quote_ident(tablename)
|| ' (CHECK ((clock >= ' || quote_literal(startdate)
|| ' AND clock < ' || quote_literal(enddate)
|| '))) INHERITS (' || TG_TABLE_NAME || ')';
create_index_part := 'CREATE INDEX IF NOT EXISTS ' || quote_ident(tablename)
|| '_1 on ' || quote_ident(prefix) || '.' || quote_ident(tablename) || '(itemid,clock)';
EXECUTE create_table_part;
EXECUTE create_index_part;
--insert it again
EXECUTE 'INSERT INTO ' || quote_ident(prefix) || '.' || quote_ident(tablename) || ' SELECT ($1).*' USING NEW;
RETURN NULL;
END;
/* trap race condition where a parallel thread beat us creating the table partition: re-try the original insert */
EXCEPTION
WHEN duplicate_table THEN
EXECUTE 'INSERT INTO ' || quote_ident(prefix) || '.' || quote_ident(tablename) || ' SELECT ($1).*' USING NEW;
RETURN NULL;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
EOF
rc=$?
if [[ $rc -eq 0 ]]; then
echo "=================================================="
echo " Partition Trigger Function Successfully Created."
echo "=================================================="
fi
return $rc
}
# create this cleanup function owned by postgres
create_cleanup_function () {
echo 'create_cleanup_function ----------------------------------------'
date +"%Y-%m-%d %H:%M:%S %Z"
psql -Xe -v ON_ERROR_STOP=on ${dbname} <<"EOF"
CREATE OR REPLACE FUNCTION zbx_part_cleanup_func(retention_age interval, partition_interval text) RETURNS text AS
$BODY$
DECLARE
result record;
prefix text := 'partitions';
table_ts_len integer;
table_ts timestamp;
min_ts timestamp;
BEGIN
IF partition_interval NOT IN ('day','month') THEN
RAISE EXCEPTION 'Please specify "day" or "month" for partition_interval instead of "%"', partition_interval;
END IF;
IF retention_age < ('1 ' || partition_interval)::interval THEN
RAISE EXCEPTION 'Retention age "%" cannot be less than "1 %"', retention_age, partition_interval;
END IF;
min_ts := date_trunc('day', NOW() - retention_age);
RAISE NOTICE 'Dropping "%" partitions older than "%" (created before %)', partition_interval, retention_age, min_ts;
FOR result IN SELECT * FROM pg_tables WHERE schemaname = quote_ident(prefix) LOOP
table_ts_len := length(substring(result.tablename from '[0-9_]*$'));
table_ts := to_timestamp(substring(result.tablename from '[0-9_]*$'), 'YYYY_MM_DD');
IF ( table_ts_len = 10 AND partition_interval = 'day' )
OR ( table_ts_len = 7 AND partition_interval = 'month' ) THEN
IF table_ts < min_ts THEN
RAISE NOTICE ' Dropping partition table %.%', quote_ident(prefix), quote_ident(result.tablename);
EXECUTE 'DROP TABLE ' || quote_ident(prefix) || '.' || quote_ident(result.tablename) || ';';
END IF;
END IF;
END LOOP;
RETURN 'OK';
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
EOF
rc=$?
if [[ $rc -eq 0 ]]; then
echo "=================================================="
echo " Partition Cleanup Function Successfully Created."
echo "=================================================="
fi
return $rc
}
add_partition_triggers () {
echo 'add_partition_triggers -----------------------------------------'
date +"%Y-%m-%d %H:%M:%S %Z"
psql -Xe -v ON_ERROR_STOP=on ${dbname} <<EOF
SET ROLE ${dbowner};
CREATE TRIGGER zbx_partition_trg BEFORE INSERT ON history FOR EACH ROW EXECUTE PROCEDURE zbx_part_trigger_func('day');
CREATE TRIGGER zbx_partition_trg BEFORE INSERT ON history_uint FOR EACH ROW EXECUTE PROCEDURE zbx_part_trigger_func('day');
CREATE TRIGGER zbx_partition_trg BEFORE INSERT ON history_str FOR EACH ROW EXECUTE PROCEDURE zbx_part_trigger_func('day');
CREATE TRIGGER zbx_partition_trg BEFORE INSERT ON history_text FOR EACH ROW EXECUTE PROCEDURE zbx_part_trigger_func('day');
CREATE TRIGGER zbx_partition_trg BEFORE INSERT ON history_log FOR EACH ROW EXECUTE PROCEDURE zbx_part_trigger_func('day');
CREATE TRIGGER zbx_partition_trg BEFORE INSERT ON trends FOR EACH ROW EXECUTE PROCEDURE zbx_part_trigger_func('month');
CREATE TRIGGER zbx_partition_trg BEFORE INSERT ON trends_uint FOR EACH ROW EXECUTE PROCEDURE zbx_part_trigger_func('month');
EOF
rc=$?
if [[ $rc -eq 0 ]]; then
echo "=========================================="
echo " Partition Triggers Successfully Created."
echo "=========================================="
fi
return $rc
}
#########
# SETUP #
#########
abspath=`cd ${0%/*};pwd` # get absolute path of script directory
logdir=${abspath}/logs # set log directory under script directory
logfile=${logdir}/install_partitioning.$(date "+%Y-%m-%d_%H.%M").log
# create log subdirectory if does not exist
if [[ ! -d ${logdir} ]]; then
mkdir -p ${logdir}
if [[ $? -ne 0 ]]; then
echo "ERROR: unable to create log directory \"${logdir}\"" >&2
exit 2
fi
fi
main 2>&1 | tee -a ${logfile}