-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathreplicate-data.py
More file actions
executable file
·346 lines (317 loc) · 14.1 KB
/
replicate-data.py
File metadata and controls
executable file
·346 lines (317 loc) · 14.1 KB
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
#!/bin/python
# -*- coding: utf-8 -*-
"""
Replicating Data from one Zabbix server to another
This script should run as a cronjob every minute or however you like.
It uses flock to make sure that only one instance is running at a time,
so it still works fine when it sometimes need a long time to replicate after
adding hosts or connection outages.
It replicates item+trigger configs and the item data from one zabbix
server (the primary) to another one (the replica).
It requests the config/data via the Zabbix API (so needs a user/login
who has the necessary read rights etc) and writes the config also
via API (needing a write user on that one), while using the Zabbix
Sender Protocol for the data replication into the replica
The hostnames to be replicated must be configured in a json config file,
it then tries to replicate all items and triggers of it. Configuration
replication is done if it was not possible to send all data successfully
(thus assuming missing items on the replica as the cause).
It adds a replication.timestamp item to keep track of when the replication
was done successfully the last time. This script also provides a trigger
for this item and makes all replicated triggers dependent on this.
All replicated items are configured as "Zabbix Trapper Items" in the replica
to make it possible to use the Zabbix Sender Protocol for them.
"""
import argparse
import fcntl
import json
import pprint
import os
import sys
import time
from pyzabbix import ZabbixAPI
from pyzabbix import ZabbixMetric
from pyzabbix import ZabbixSender
config_file = "/vagrant/replica/example-config.json"
def get_timestamp(zbx, hostname, config):
""" This method should get the timestamp of the last successful
replication of the given host. It must be checked if it exists already,
because if this is the first time a host shall be replicated, the host
is not yet created. In that case, the timestamp is used as defined by
the initial_time variable to start with data from a certain period """
now_time = int(time.time())
item = zbx.item.get(filter={
"host": hostname,
"name": config["timestamp_item"]["name"]})
if len(item) == 0:
# item is not yet existing, needs to be created and last time is 0
create_or_update_item(zbx, hostname, config["timestamp_item"], config)
# we only want to replace hostname in the copy
trigger = config["timestamp_trigger"].copy()
trigger["expression"] = trigger["expression"].replace("HOSTNAME",
hostname)
create_or_update_trigger(zbx, hostname, trigger)
last_time = now_time - config["initial_history"]
else:
itemid = item[0]['itemid']
history = zbx.history.get(itemids=itemid,
sortorder="DESC",
sortfield='clock',
limit=1)
if len(history) == 0:
# first replication - item exists, but did never receive any data
last_time = now_time - config["initial_history"]
else:
last_time = history[0]['value']
return last_time, now_time
def send_timestamp(sender, hostname, itemname, timestamp):
""" When the data was completely replicated, the timestamp of
the replication is send to the Zabbix replica """
metrics = []
m = ZabbixMetric(hostname, itemname, timestamp)
metrics.append(m)
sender.send(metrics)
def replicate_hostdata(primary,
replica,
sender,
hostname,
last_time,
now_time,
config):
""" This method replicates all data for one host in a given timeframe.
If it should not be possible to send all items, this method calls the
config replication to make it possible the next time """
print "INFO: Replicating Data for " + hostname
pp = pprint.PrettyPrinter(indent=4)
try:
with open(os.path.join(config["map_dir"],
hostname + ".json"),
"r") as f:
item_map = json.loads(f.read())
except:
# when no config exists for that host, create it new
item_map = replicate_hostconfig(primary, replica, hostname, config)
float_values = [key for key, val in item_map.items()
if val["valtype"] == "0"]
char_values = [key for key, val in item_map.items()
if val["valtype"] == "1"]
unsigned_values = [key for key, val in item_map.items()
if val["valtype"] == "3"]
text_values = [key for key, val in item_map.items()
if val["valtype"] == "4"]
metrics = []
if len(float_values) > 0:
item_history = primary.history.get(itemids=float_values,
time_from=last_time,
time_till=now_time,
history="0")
for metric in item_history:
m = ZabbixMetric(hostname,
item_map[metric["itemid"]]['key'],
metric['value'],
int(metric['clock']))
metrics.append(m)
if len(char_values) > 0:
item_history = primary.history.get(itemids=char_values,
time_from=last_time,
time_till=now_time,
history="1")
for metric in item_history:
m = ZabbixMetric(hostname,
item_map[metric["itemid"]]['key'],
metric['value'],
int(metric['clock']))
metrics.append(m)
if len(unsigned_values) > 0:
item_history = primary.history.get(itemids=unsigned_values,
time_from=last_time,
time_till=now_time,
history="3")
for metric in item_history:
m = ZabbixMetric(hostname,
item_map[metric["itemid"]]['key'],
metric['value'],
int(metric['clock']))
metrics.append(m)
if len(text_values) > 0:
item_history = primary.history.get(itemids=text_values,
time_from=last_time,
time_till=now_time,
history="4")
for metric in item_history:
m = ZabbixMetric(hostname,
item_map[metric["itemid"]]['key'],
metric['value'],
int(metric['clock']))
metrics.append(m)
response = sender.send(metrics)
pp.pprint(response)
if response.failed > 0:
print "WARN: Replication of Data not successful"
# sending of items failed
# try to update the config and try to send again
item_map = replicate_hostconfig(primary, replica, hostname, config)
else:
send_timestamp(sender,
hostname,
config["timestamp_item"]["name"],
now_time)
print "INFO: Replication of Data successful"
def replicate_hostconfig(primary, replica, hostname, config):
""" This method replicates item and trigger configs for the
given hostname from primary to replica server.
It converts all items to "Zabbix Trapper" type and additionally
adds a dependency to the replication trigger to all triggers"""
print "INFO: Replicating Config for " + hostname
items_raw = primary.item.get(filter={"host": hostname})
items = []
item_map = {}
for raw in items_raw:
clean = {
"key_": raw["key_"],
"name": raw["name"],
"type": 2,
"value_type": raw["value_type"],
"description": raw["description"],
"history": raw["history"],
"status": raw["status"],
"trends": raw["trends"]
}
items.append(clean)
item_map[raw["itemid"]] = {"key": raw["key_"],
"valtype": raw["value_type"]}
for item in items:
create_or_update_item(replica, hostname, item, config)
# replicate trigger configs
triggers_raw = primary.trigger.get(filter={"host": hostname},
expandExpression=True,
sortfield="triggerid",
selectDependencies="extend")
triggers = []
for raw in triggers_raw:
clean = {
"comments": raw["comments"],
"description": raw["description"],
"expression": raw["expression"],
"priority": raw["priority"],
"status": raw["status"],
"type": raw["type"],
"recovery_mode": raw["recovery_mode"],
"recovery_expression": raw["recovery_expression"],
"correlation_mode": raw["correlation_mode"],
"manual_close": raw["manual_close"]
}
clean["dep_names"] = [config["timestamp_trigger"]["description"]]
for dep in raw["dependencies"]:
clean["dep_names"].append(dep["description"])
triggers.append(clean)
for trigger in triggers:
r = create_or_update_trigger(replica, hostname, trigger)
with open(os.path.join(config["map_dir"], hostname + ".json"), "w") as f:
f.write(json.dumps(item_map))
return item_map
def create_host(replica, hostname, config):
""" This method simply creates a new host on the replica server """
host = {
"host": hostname,
"groups": config["groups"],
"interfaces": config["interfaces"]
}
replica.host.create(host)
def create_or_update_item(replica, hostname, item, config):
""" This method checks if an item already exists on the replica
and either creates or updates it as it is defined on the primary """
hostid = replica.get_id("host", hostname)
if hostid is None:
create_host(replica, hostname, config)
hostid = replica.get_id("host", hostname)
item["hostid"] = hostid
items_raw = replica.item.get(filter={"host": hostname,
"key_": item["key_"]})
if len(items_raw) == 0:
itemid = None
else:
itemid = items_raw[0]["itemid"]
pp = pprint.PrettyPrinter(indent=4)
if itemid is None:
print "Creating: " + item["key_"]
result = replica.item.create(item)
else:
print "Updating: " + item["key_"]
item["itemid"] = itemid
result = replica.item.update(item)
def create_or_update_trigger(replica, hostname, trigger):
""" This method checks if a trigger already exists on the replica
and either creates or updates it as it is defined on the primary """
result = replica.trigger.get(
filter={"host": hostname,
"description": trigger["description"]})
dep_ids = []
dependencies = trigger.pop("dep_names", [])
for dep in dependencies:
r = replica.trigger.get(filter={"host": hostname, "description": dep})
if len(r) == 1:
dep_ids.append({"triggerid": r[0]["triggerid"]})
trigger["dependencies"] = dep_ids
pp = pprint.PrettyPrinter(indent=4)
if len(result) == 1:
trigger["triggerid"] = result[0]["triggerid"]
print "Updating: " + trigger["description"]
pp.pprint(replica.trigger.update(trigger))
else:
print "Creating: " + trigger["description"]
pp.pprint(replica.trigger.create(trigger))
def zabbix_login(zabbixurl, user, password):
""" This method is reponsible for the login to zabbix """
zbx = ZabbixAPI(zabbixurl, user=user, password=password)
return zbx
def main():
# parse parameters
# create zabbix communication objects
parser = argparse.ArgumentParser()
parser.add_argument("config_file", help="replica configuration file")
parser.add_argument("-r",
"--replicate-config",
help=("Force a replication of the full item/trigger"
"configuration from one server to another"),
action="store_true")
args = parser.parse_args()
# load config from file
with open(args.config_file, "r") as f:
config = json.loads(f.read())
# make sure only one instance is running per config file
fh = open(os.path.realpath(__file__), 'r')
try:
fcntl.flock(fh, fcntl.LOCK_EX | fcntl.LOCK_NB)
except:
print "Already one instance running"
os._exit(0)
# get important values from config
primary = zabbix_login(config["primary"]["url"],
config["primary"]["user"],
config["primary"]["password"])
replica = zabbix_login(config["replica"]["url"],
config["replica"]["user"],
config["replica"]["password"])
sender = ZabbixSender(config["replica"]["ip"],
int(config["replica"]["port"]))
pp = pprint.PrettyPrinter(indent=4)
# explicitly perform config replication
if args.replicate_config:
for hostname in config["replication_hosts"]:
item_map = replicate_hostconfig(primary, replica, hostname, config)
pp.pprint(item_map)
# perform data replication and if necessary config replication
for hostname in config["replication_hosts"]:
last_time, now_time = get_timestamp(replica,
hostname,
config)
replicate_hostdata(primary,
replica,
sender,
hostname,
last_time,
now_time,
config)
if __name__ == "__main__":
main()