├── .gitignore
├── requirements.txt
├── icons
├── Cloud24.png
├── Cloud48.png
├── Cloud64.png
├── Cloud96.png
├── Cloud128.png
├── Router128.png
├── Router24.png
├── Router48.png
├── Router64.png
├── Router96.png
├── Switch128.png
├── Switch24.png
├── Switch48.png
├── Switch64.png
├── Switch96.png
├── Workstation128.png
├── Workstation24.png
├── Workstation48.png
├── Workstation64.png
└── Workstation96.png
├── mapimgs
└── test.png
├── fonts
└── DejaVuSansMono.ttf
├── template
├── userparameter_weathermap.conf
└── weathermap.xml
├── TODO
├── starter.py
├── mapcfgs
├── example.yaml
└── example.cfg
├── tests
└── test_map.py
├── weathermap.py
├── zabbix.py
├── README.md
├── converter.py
├── mapping.py
├── config.py
└── LICENSE
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea/
2 | __pycache__/
3 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | Pillow
2 | py-zabbix
3 | ruamel.yaml==0.14.12
4 |
--------------------------------------------------------------------------------
/icons/Cloud24.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Prototype-X/Zabbix-Network-Weathermap/HEAD/icons/Cloud24.png
--------------------------------------------------------------------------------
/icons/Cloud48.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Prototype-X/Zabbix-Network-Weathermap/HEAD/icons/Cloud48.png
--------------------------------------------------------------------------------
/icons/Cloud64.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Prototype-X/Zabbix-Network-Weathermap/HEAD/icons/Cloud64.png
--------------------------------------------------------------------------------
/icons/Cloud96.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Prototype-X/Zabbix-Network-Weathermap/HEAD/icons/Cloud96.png
--------------------------------------------------------------------------------
/mapimgs/test.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Prototype-X/Zabbix-Network-Weathermap/HEAD/mapimgs/test.png
--------------------------------------------------------------------------------
/icons/Cloud128.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Prototype-X/Zabbix-Network-Weathermap/HEAD/icons/Cloud128.png
--------------------------------------------------------------------------------
/icons/Router128.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Prototype-X/Zabbix-Network-Weathermap/HEAD/icons/Router128.png
--------------------------------------------------------------------------------
/icons/Router24.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Prototype-X/Zabbix-Network-Weathermap/HEAD/icons/Router24.png
--------------------------------------------------------------------------------
/icons/Router48.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Prototype-X/Zabbix-Network-Weathermap/HEAD/icons/Router48.png
--------------------------------------------------------------------------------
/icons/Router64.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Prototype-X/Zabbix-Network-Weathermap/HEAD/icons/Router64.png
--------------------------------------------------------------------------------
/icons/Router96.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Prototype-X/Zabbix-Network-Weathermap/HEAD/icons/Router96.png
--------------------------------------------------------------------------------
/icons/Switch128.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Prototype-X/Zabbix-Network-Weathermap/HEAD/icons/Switch128.png
--------------------------------------------------------------------------------
/icons/Switch24.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Prototype-X/Zabbix-Network-Weathermap/HEAD/icons/Switch24.png
--------------------------------------------------------------------------------
/icons/Switch48.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Prototype-X/Zabbix-Network-Weathermap/HEAD/icons/Switch48.png
--------------------------------------------------------------------------------
/icons/Switch64.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Prototype-X/Zabbix-Network-Weathermap/HEAD/icons/Switch64.png
--------------------------------------------------------------------------------
/icons/Switch96.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Prototype-X/Zabbix-Network-Weathermap/HEAD/icons/Switch96.png
--------------------------------------------------------------------------------
/fonts/DejaVuSansMono.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Prototype-X/Zabbix-Network-Weathermap/HEAD/fonts/DejaVuSansMono.ttf
--------------------------------------------------------------------------------
/icons/Workstation128.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Prototype-X/Zabbix-Network-Weathermap/HEAD/icons/Workstation128.png
--------------------------------------------------------------------------------
/icons/Workstation24.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Prototype-X/Zabbix-Network-Weathermap/HEAD/icons/Workstation24.png
--------------------------------------------------------------------------------
/icons/Workstation48.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Prototype-X/Zabbix-Network-Weathermap/HEAD/icons/Workstation48.png
--------------------------------------------------------------------------------
/icons/Workstation64.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Prototype-X/Zabbix-Network-Weathermap/HEAD/icons/Workstation64.png
--------------------------------------------------------------------------------
/icons/Workstation96.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Prototype-X/Zabbix-Network-Weathermap/HEAD/icons/Workstation96.png
--------------------------------------------------------------------------------
/template/userparameter_weathermap.conf:
--------------------------------------------------------------------------------
1 | UserParameter=weathermap.update.upload[*],/opt/Zabbix-Network-Weathermap/starter.py $1
2 | UserParameter=weathermap.update.only[*],/opt/Zabbix-Network-Weathermap/starter.py $1
3 | UserParameter=weathermap.scan.file[*],/opt/Zabbix-Network-Weathermap/starter.py $1
4 | UserParameter=weathermap.scan.map[*],/opt/Zabbix-Network-Weathermap/starter.py $1
5 |
--------------------------------------------------------------------------------
/TODO:
--------------------------------------------------------------------------------
1 | todo write tests for all classes !!!
2 | todo logging for all classes, detail logging
3 | todo add new option fontsize in section [node-] ?
4 | todo add new option fontsize in section [link-] ?
5 | todo add new option fontsize in section [table] ?
6 | todo arg -a --all ?
7 | todo NOTE: link optional parameters: name1, name2, bandwidth, width, copy
8 | todo NOTE: node optional parameters: label, icon
9 | todo render map if errors occured -/+
10 |
--------------------------------------------------------------------------------
/starter.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | # __author__ = 'maximus'
4 | import time
5 | import sys
6 | import subprocess
7 |
8 |
9 | def main():
10 | start_time = time.time()
11 | cli = ['/opt/Zabbix-Network-Weathermap/weathermap.py']
12 | cli.extend(sys.argv[1:])
13 | subprocess.call(cli)
14 | latency = round(time.time() - start_time, 3)
15 | print(latency)
16 |
17 | if __name__ == '__main__':
18 | main()
19 |
--------------------------------------------------------------------------------
/mapcfgs/example.yaml:
--------------------------------------------------------------------------------
1 | %YAML 1.2
2 | ---
3 | map:
4 | name: example
5 | bgcolor: ''
6 | fontsize: 10
7 | width: 1200
8 | height: 800
9 | zabbix:
10 | url: http://zabbix.example.ru
11 | login: admin
12 | password: admin
13 | table:
14 | show: true
15 | x: 1100
16 | y: 100
17 | palette:
18 | - '#908C8C'
19 | - '#FFFFFF'
20 | - '#8000FF'
21 | - '#0000FF'
22 | - '#00EAEA'
23 | - '#00FF00'
24 | - '#FFFF00'
25 | - '#FF9933'
26 | - '#FF0000'
27 | link:
28 | bandwidth: 100
29 | width: 10
30 | node-Router:
31 | name: Русские буквы
32 | label: R1
33 | icon: Router64.png
34 | x: 625
35 | y: 225
36 | node-Router2:
37 | name: ''
38 | label: R2
39 | icon: Router64.png
40 | x: 625
41 | y: 225
42 | node-Switch:
43 | name: ''
44 | label: SW1
45 | icon: Switch64.png
46 | x: 75
47 | y: 375
48 | node-Switch2:
49 | name: ''
50 | label: SW2
51 | icon: Switch64.png
52 | x: 75
53 | y: 375
54 | link-1:
55 | node1: node-Router
56 | node2: node-Switch
57 | name1: ''
58 | name2: ''
59 | width: 15
60 | hostname: Router
61 | itemin: ifHCInOctets[ge-0/0/0]
62 | itemout: ifHCOutOctets[ge-0/0/0]
63 | link-2:
64 | node1: node-Router2
65 | node2: node-Switch2
66 | name1: ''
67 | name2: ''
68 | bandwidth: 1000
69 | hostname: Router2
70 | itemin: ifHCInOctets[ge-0/0/1]
71 | itemout: ifHCOutOctets[ge-0/0/1]
72 | ...
73 |
--------------------------------------------------------------------------------
/mapcfgs/example.cfg:
--------------------------------------------------------------------------------
1 | [zabbix]
2 | url = http://zabbix.example.ru
3 | login = admin
4 | password = admin
5 |
6 | [map]
7 | name = example
8 | #default transparent
9 | bgcolor =
10 | fontsize = 10
11 | width = 1200
12 | height = 800
13 |
14 | [table]
15 | show = 1
16 | x = 1100
17 | y = 100
18 |
19 | [palette]
20 | 6 = #FFFF00
21 | 4 = #00EAEA
22 | 2 = #8000FF
23 | 8 = #FF0000
24 | 1 = #FFFFFF
25 | 0 = #908C8C
26 | 7 = #FF9933
27 | 3 = #0000FF
28 | 5 = #00FF00
29 |
30 | [link]
31 | #default arrow width
32 | width = 10
33 | #default bandwidth in Mbps
34 | bandwidth = 100
35 |
36 | [node-Router]
37 | name = Русские буквы
38 | label = R1
39 | icon = Router64.png
40 | x = 625
41 | y = 225
42 |
43 | [node-Switch]
44 | name =
45 | label = SW1
46 | icon = Switch64.png
47 | x = 75
48 | y = 375
49 |
50 | [node-Router2]
51 | name =
52 | label = R2
53 | icon = Router64.png
54 | x = 625
55 | y = 225
56 |
57 | [node-Switch2]
58 | name =
59 | label = SW2
60 | icon = Switch64.png
61 | x = 75
62 | y = 375
63 |
64 | [link-1]
65 | node1 = node-Router
66 | node2 = node-Switch
67 | name1 =
68 | name2 =
69 | width = 15
70 | hostname = Router
71 | itemin = ifHCInOctets[ge-0/0/0]
72 | itemout = ifHCOutOctets[ge-0/0/0]
73 |
74 | [link-2]
75 | node1 = node-Router2
76 | node2 = node-Switch2
77 | name1 =
78 | name2 =
79 | bandwidth = 1000
80 | hostname = Router2
81 | itemin = ifHCInOctets[ge-0/0/1]
82 | itemout = ifHCOutOctets[ge-0/0/1]
83 |
--------------------------------------------------------------------------------
/tests/test_map.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | # __author__ = 'maximus'
4 |
5 | from unittest import TestCase
6 | from mapping import Map, Node, Table, Link
7 | import os
8 | import hashlib
9 | import warnings
10 |
11 |
12 | class TestMap(TestCase):
13 |
14 | def setUp(self):
15 | self.hash = '43228a6d34e15561dcb179a9e4388489e4634093348a57f34801a12fd548f203'
16 | self.root_path = str(os.path.dirname(os.path.abspath(__file__))).replace('tests', '')
17 | self.font_path = self.root_path + 'fonts'
18 | self.font_path_fn = self.root_path + 'fonts/DejaVuSansMono.ttf'
19 | self.icon_path = self.root_path + 'icons'
20 | self.cfg_path = self.root_path + 'mapcfgs'
21 | self.img_path = self.root_path + 'mapimgs'
22 |
23 | a = Node(self.font_path_fn, self.icon_path, x=300, y=30, label='host-A', icon='Router96.png')
24 | b = Node(self.font_path_fn, self.icon_path, x=750, y=30, label='host-B', icon='Router96.png')
25 | c = Node(self.font_path_fn, self.icon_path, x=30, y=750, label='host C', icon='Router96.png')
26 | d = Node(self.font_path_fn, self.icon_path, x=750, y=750, label='HOST-D', icon='Router96.png')
27 | e = Node(self.font_path_fn, self.icon_path, x=400, y=400, label='host-E', icon='Router96.png')
28 |
29 | link_a = Link(self.font_path_fn, a, e, bandwidth=1000, width=10)
30 | link_a.data(in_bps=0, out_bps=123345123)
31 | link_b = Link(self.font_path_fn, b, e, bandwidth=100, width=15)
32 | link_b.data(in_bps=54123456, out_bps=114987654)
33 | link_c = Link(self.font_path_fn, c, e, bandwidth=10000)
34 | link_c.data(in_bps=841123456, out_bps=5147987654)
35 | link_d = Link(self.font_path_fn, d, e, bandwidth=100, width=15)
36 | link_d.data(in_bps=73456852, out_bps=987654)
37 | link_e = Link(self.font_path_fn, a, b, bandwidth=100, width=15)
38 | link_e.data(in_bps=73456852, out_bps=987654)
39 |
40 | table = Table(self.font_path_fn, x=700, y=350, dt=False)
41 | self.new_map = Map([link_a, link_b, link_c, link_d, link_e], [a, b, c, d, e], table=table, len_x=800, len_y=800)
42 |
43 | def test_map(self):
44 | warnings.simplefilter("ignore", ResourceWarning)
45 | self.new_map.do()
46 | # new_map.show()
47 | self.new_map.save_img(self.img_path + '/test.png')
48 | self.assertEqual(self.hash, hashlib.sha256(open(self.img_path + '/test.png', 'rb').read()).hexdigest())
49 | # self.fail()
50 |
51 | if __name__ == '__main__':
52 | TestMap()
53 |
--------------------------------------------------------------------------------
/weathermap.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | # __author__ = 'maximus'
4 |
5 | import argparse
6 | import logging
7 | import os
8 | import sys
9 |
10 | from config import ConfigLoader, ConfigCreate
11 | from zabbix import ZabbixAgent
12 |
13 |
14 | class WeathermapCLI(object):
15 | def __init__(self):
16 | self.root_path = str(os.path.dirname(os.path.abspath(__file__)))
17 | self.font_path = self.root_path + '/fonts'
18 | self.font_path_fn = self.root_path + '/fonts/DejaVuSansMono.ttf'
19 | self.icon_path = self.root_path + '/icons'
20 | self.cfg_path = self.root_path + '/mapcfgs'
21 | self.img_path = self.root_path + '/mapimgs'
22 |
23 | self.parser = argparse.ArgumentParser(conflict_handler='resolve', description='Network weathermap for Zabbix')
24 | self.parser.add_argument('-v', '--version', action='store_true', help='show version')
25 | self.parser.add_argument('-h', '--help', action='help', help='show help')
26 | self.parser.add_argument('-d', '--debug', action='store_true', help='Enable debug mode')
27 |
28 | self.parser.add_argument('-m', '--map', nargs='+', action='store', type=str, help='Config file names')
29 | self.parser.add_argument('-i', '--img', action='store', type=str, help='Image path')
30 | self.parser.add_argument('-u', '--upload', action='store_true', help='Image upload to zabbix')
31 |
32 | self.parser.add_argument('-c', '--cfg', action='store', type=str, help='Config path')
33 | # self.parser.add_argument('-a', '--all', action='store_true', help='all')
34 |
35 | self.parser.add_argument('-s', '--scan', nargs='+', action='store', type=str, help='Map names in Zabbix')
36 | self.parser.add_argument('-f', '--file', action='store_true', help='Zabbix authentication from map config file')
37 | self.parser.add_argument('-z', '--zabbix', action='store', type=str, help='Zabbix server url')
38 | self.parser.add_argument('-l', '--login', action='store', type=str, help='Login')
39 | self.parser.add_argument('-p', '--pwd', action='store', help='Password')
40 |
41 | self.args = self.parser.parse_args()
42 | self._cfg_logging()
43 |
44 | if not vars(self.args):
45 | self.parser.print_help()
46 | sys.exit()
47 |
48 | if self.args.version:
49 | print('Network weathermap 1.1.5')
50 | sys.exit()
51 |
52 | if self.args.map:
53 | self._map_img()
54 | elif self.args.scan and self.args.zabbix and self.args.login and self.args.pwd:
55 | self._map_scan()
56 | elif self.args.scan and self.args.file:
57 | self._map_scan_cfg()
58 | else:
59 | self.parser.print_help()
60 | sys.exit()
61 |
62 | def _map_scan(self):
63 | if self.args.cfg:
64 | self.cfg_path = self.args.cfg
65 | for map_n in self.args.scan:
66 | zbx = ZabbixAgent(self.args.zabbix, self.args.login, self.args.pwd)
67 | map_data = zbx.scan_map(map_n)
68 | scan_map = ConfigCreate(map_data, zbx)
69 | scan_map.create()
70 | scan_map.check_map(self.cfg_path)
71 | scan_map.save(self.cfg_path)
72 |
73 | del zbx, scan_map, map_data
74 |
75 | def _map_scan_cfg(self):
76 | if self.args.cfg:
77 | self.cfg_path = self.args.cfg
78 | for map_n in self.args.scan:
79 | cfg = ConfigLoader(self.cfg_path + '/' + map_n + '.yaml')
80 | map_data = cfg.zbx.scan_map(map_n)
81 | scan_map = ConfigCreate(map_data, cfg.zbx)
82 | scan_map.create()
83 | scan_map.check_map(self.cfg_path)
84 | scan_map.save(self.cfg_path)
85 |
86 | del cfg, scan_map, map_data
87 |
88 | def _map_img(self):
89 | if self.args.cfg:
90 | self.cfg_path = self.args.cfg
91 | if self.args.img:
92 | self.img_path = self.args.img
93 | for map_fn in self.args.map:
94 | cfg = ConfigLoader(self.cfg_path + '/' + map_fn)
95 | map_obj = cfg.create_map(self.font_path_fn, self.icon_path)
96 | map_obj.do()
97 | # map_obj.show()
98 | map_obj.save_img(self.img_path + '/' + map_fn[:-5] + '.png')
99 |
100 | if self.args.upload:
101 | cfg.upload(self.img_path + '/' + map_fn[:-5] + '.png')
102 |
103 | del cfg, map_obj
104 |
105 | def _cfg_logging(self):
106 | """
107 | Configure logging output format.
108 | """
109 | if self.args.debug:
110 | loglevel = logging.DEBUG
111 | else:
112 | loglevel = logging.INFO
113 | logformat = '[%(asctime)s] [%(name)s:%(levelname)s] - %(message)s'
114 | logging.basicConfig(level=loglevel, format=logformat, datefmt='%d/%m/%Y %H:%M:%S')
115 |
116 |
117 | def main():
118 | WeathermapCLI()
119 |
120 | if __name__ == '__main__':
121 | main()
122 |
--------------------------------------------------------------------------------
/zabbix.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | # __author__ = 'maximus'
4 |
5 | import logging
6 | from pyzabbix import ZabbixAPI
7 | import base64
8 |
9 | log = logging.getLogger(__name__)
10 |
11 |
12 | class ZbxException(Exception):
13 | def __init__(self, message):
14 | self.message = message
15 |
16 |
17 | class ZabbixAgent(object):
18 |
19 | def __init__(self, url, login, password):
20 | self.url = url
21 | self.login = login
22 | self.password = password
23 | self.zbx_api = ZabbixAPI(url=url, use_authenticate=False, user=login, password=password)
24 | log.debug('Object ZabbixAgent created')
25 | log.debug('API ver. %s', self.api_ver())
26 |
27 | def get_item_data(self, hostname, item):
28 | reply = self.zbx_api.host.get(filter={'name': hostname}, output='shorten')
29 | if not reply:
30 | raise ZbxException("hostname: {} not found".format(hostname))
31 | hostid = reply[0]['hostid']
32 | log.debug('hostID %s', hostid)
33 |
34 | item_data = self.zbx_api.item.get(filter={'hostid': hostid, 'key_': item}, output=['lastvalue'])
35 | log.debug('itemID %s', hostid)
36 | if not item_data:
37 | raise ZbxException('item: {} not found'.format(item))
38 |
39 | if len(item_data) > 1:
40 | raise ZbxException('return items expected one item')
41 | return int(item_data[0]['lastvalue'])
42 |
43 | def get_item_data2(self, hostname, item_in, item_out):
44 | reply = self.zbx_api.host.get(filter={'name': hostname}, output='shorten')
45 | if not reply:
46 | raise ZbxException("hostname: {} not found".format(hostname))
47 | hostid = reply[0]['hostid']
48 | log.debug('hostID %s', hostid)
49 |
50 | if '+' in item_in:
51 | item_in_split = list(map(str.strip, item_in.split('+')))
52 | item_in_data = self.zbx_api.item.get(filter={'hostid': hostid, 'key_': item_in_split[0]}, output=['lastvalue'])
53 | for item_in_elem in item_in_split[1:]:
54 | item_in_data[0]['lastvalue'] = str(int(item_in_data[0]['lastvalue']) + int(self.zbx_api.item.get(filter={'hostid': hostid, 'key_': item_in_elem}, output=['lastvalue'])[0]['lastvalue']))
55 | else:
56 | item_in_data = self.zbx_api.item.get(filter={'hostid': hostid, 'key_': item_in}, output=['lastvalue'])
57 |
58 | log.debug('itemID %s', hostid)
59 | if not item_in_data:
60 | raise ZbxException('item: {} not found'.format(item_in))
61 |
62 | if '+' in item_out:
63 | item_out_split = list(map(str.strip, item_out.split('+')))
64 | item_out_data = self.zbx_api.item.get(filter={'hostid': hostid, 'key_': item_out_split[0]}, output=['lastvalue'])
65 | for item_out_elem in item_out_split[1:]:
66 | item_out_data[0]['lastvalue'] = str(int(item_out_data[0]['lastvalue']) + int(self.zbx_api.item.get(filter={'hostid': hostid, 'key_': item_out_elem}, output=['lastvalue'])[0]['lastvalue']))
67 | else:
68 | item_out_data = self.zbx_api.item.get(filter={'hostid': hostid, 'key_': item_out}, output=['lastvalue'])
69 |
70 | log.debug('itemID %s', hostid)
71 | if not item_in_data:
72 | raise ZbxException('item: {} not found'.format(item_out))
73 |
74 | if len(item_in_data) > 1:
75 | raise ZbxException('return items expected one item: {}'.format(item_in_data))
76 |
77 | if len(item_out_data) > 1:
78 | raise ZbxException('return items expected one item: {}'.format(item_out_data))
79 |
80 | return int(item_in_data[0]['lastvalue']), int(item_out_data[0]['lastvalue'])
81 |
82 | def api_ver(self):
83 | return self.zbx_api.api_version()
84 |
85 | def scan_map(self, map_name):
86 | map_data = self.zbx_api.map.get(filter={'name': map_name},
87 | selectSelements=['elements', 'selementid', 'elementtype', 'iconid_off',
88 | 'x', 'y'],
89 | selectLinks=['selementid1', 'selementid2', 'linkid']
90 | )
91 | if not map_data:
92 | raise ZbxException('map: {} not found'.format(map_name))
93 |
94 | if len(map_data) > 1:
95 | raise ZbxException('return maps expected one map')
96 | return map_data[0]
97 |
98 | def scan_map_all(self):
99 | maps_data = self.zbx_api.map.get(selectSelements=['elementid', 'selementid', 'elementtype', 'iconid_off',
100 | 'x', 'y'],
101 | selectLinks=['selementid1', 'selementid2', 'linkid'])
102 | if not maps_data:
103 | raise ZbxException('maps not found')
104 |
105 | if len(maps_data) > 1:
106 | raise ZbxException('return maps expected one map')
107 | return maps_data
108 |
109 | def get_hostname(self, hostid):
110 | hostname = self.zbx_api.host.get(hostids=hostid, output=['host'])
111 |
112 | if not hostname:
113 | raise ZbxException('hostname not found')
114 |
115 | if len(hostname) > 1:
116 | raise ZbxException('return hostnames expected one hostname')
117 |
118 | return hostname[0]['host']
119 |
120 | def get_mapname(self, mapid):
121 | mapname = self.zbx_api.map.get(sysmapids=mapid, output=['name'])
122 |
123 | if not mapname:
124 | raise ZbxException('map name not found')
125 |
126 | if len(mapname) > 1:
127 | raise ZbxException('return map names expected one map name')
128 |
129 | return mapname[0]['name']
130 |
131 | def get_triggername(self, triggerid):
132 | triggername = self.zbx_api.trigger.get(triggerid=triggerid, output=['description'])
133 |
134 | if not triggername:
135 | raise ZbxException('trigger name not found')
136 |
137 | if len(triggername) > 1:
138 | raise ZbxException('return trigger names expected one trigger name')
139 |
140 | return triggername[0]['description']
141 |
142 | def get_hostgroupname(self, groupid):
143 | hostgroupname = self.zbx_api.hostgroup.get(groupids=groupid, output=['name'])
144 |
145 | if not hostgroupname:
146 | raise ZbxException('hostgroup name not found')
147 |
148 | if len(hostgroupname) > 1:
149 | raise ZbxException('return hostgroup names expected one hostgroup name')
150 |
151 | return hostgroupname[0]['name']
152 |
153 | def get_imagename(self, imageid):
154 | imagename = self.zbx_api.image.get(imageids=imageid, output=['name'])
155 |
156 | if not imagename:
157 | raise ZbxException('image name not found')
158 |
159 | if len(imagename) > 1:
160 | raise ZbxException('return image names expected one image name')
161 |
162 | return imagename[0]['name']
163 |
164 | def image_to_zabbix(self, pathfn, zbx_img_name):
165 | with open(pathfn, 'rb') as img:
166 | b64img = base64.b64encode(img.read()).decode()
167 | image_data = self.zbx_api.image.get(filter={'name': zbx_img_name})
168 | if not image_data:
169 | self.zbx_api.image.create(name=zbx_img_name, imagetype=2, image=b64img)
170 | else:
171 | self.zbx_api.image.update(imageid=image_data[0]['imageid'], image=b64img)
172 |
173 | def image_get(self, imageid):
174 | image_data = self.zbx_api.image.get(imageids=imageid, select_image=True)
175 | return image_data[0]['image']
176 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Zabbix-Network-Weathermap
2 |
3 | [](https://gitter.im/Prototype-X/Zabbix-Network-Weathermap?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
4 | [](https://landscape.io/github/Prototype-X/Zabbix-Network-Weathermap/master)
5 |
6 | Network weathermap for Zabbix like [Network Weathermap](http://network-weathermap.com)
7 |
8 | ### Screenshot ###
9 | 
10 |
11 | ### Features ###
12 | * Get source data from Zabbix
13 | * Generate YAML config from Zabbix map
14 | * Create image with map in PNG format
15 | * Upload image to Zabbix
16 | * Support for map elements with the type: host, map, image
17 |
18 | ### Requrements ###
19 | * Zabbix 3.4 (I dont check backward compability with Zabbix 3.0 - 3.2)
20 | * Python 3.4.3 and above
21 | * libs: Pillow, py-zabbix, ruamel.yaml
22 |
23 | ### Install ###
24 | ```bash
25 | sudo apt-get install python3-pip python-pip python3-pil
26 | sudo pip3 install py-zabbix
27 | sudo pip3 install ruamel.yaml==0.14.12
28 | unzip Zabbix-Network-Weathermap.zip -d /opt
29 | chown -R zabbix:zabbix /opt/Zabbix-Network-Weathermap/*
30 | chmod a+x /opt/Zabbix-Network-Weathermap/starter.py
31 | chmod a+x /opt/Zabbix-Network-Weathermap/weathermap.py
32 | cp /opt/Zabbix-Network-Weathermap/template/userparameter_weathermap.conf /etc/zabbix/zabbix_agentd.d/
33 | ```
34 | * Copy /template/userparemeter_weathermap.conf to /etc/zabbix/zabbix_agentd.d/ and reload zabbix-agent
35 | * Import template /template/weathermap.xml to zabbix
36 | * Add Template Weathermap to host where use zabbix agent (for example use host zabbix server)
37 | * Create new user with permissions Zabbix Admin
38 | * User must have read-only or read-write access to hosts and hosts groups present in map
39 | * Go to Zabbix -> Configuration -> Template Weathermap -> Macros:
40 |
41 | {$SCANFILE} - When map config exist. If you change map remove host or change position host, configuration will be updated in accordance with changes on the map.
42 |
43 | {$SCANMAP} - First time scan map, config file not exist. Create file with map configuration.
44 |
45 | {$UPDATE} - Only create image, like old style Network Weathermap.
46 |
47 | {$UPLOAD} - Create and upload image to Zabbix.
48 |
49 | * Check Zabbix -> Configuration -> Hosts -> Host with Weathermap template -> Applications -> Weathermap -> Items -> Status
50 |
51 | * Create file with map configuration:
52 |
53 | weathermap.py -s mapname1 mapnameN -z http://zabbix.example.com -l admin -p admin
54 | OR
55 |
56 | Zabbix -> Template Weathermap -> Macros -> {$SCANMAP} -> Value
57 |
58 | * Open file /opt/Zabbix-Network-Weathermap/mapcfgs/mapname1.yaml and set hostname and itemin, itemout. If you set visible name, then use visible name instead hostname.
59 |
60 | ```yaml
61 | link-1:
62 | node1: node-Router
63 | node2: node-Switch
64 | name1: R1
65 | name2: SW1
66 | width: 15
67 | hostname: Router
68 | #itemin/itemout = item key
69 | itemin: ifHCInOctets[ge-0/0/0]
70 | itemout: ifHCOutOctets[ge-0/0/0]
71 | ```
72 |
73 | * Create map image and upload it to Zabbix:
74 |
75 | weathermap.py -m mapname1.yaml -u
76 | OR
77 |
78 | Zabbix -> Template Weathermap -> Macros -> {$UPLOAD} -> Value
79 |
80 | * Set Zabbix -> Monitoring -> Maps -> mapname1 -> Properties -> Background image -> mapname1
81 |
82 |
83 | ### Scripts note ###
84 |
85 | Default path:
86 |
87 | **/opt/Zabbix-Network-Weathermap/mapcfgs - map config dir**
88 |
89 | **/opt/Zabbix-Network-Weathermap/mapimgs - map images dir**
90 |
91 | **/opt/Zabbix-Network-Weathermap/icons - map icons dir**
92 |
93 |
94 | usage: weathermap.py [-v] [-h] [-d] [-m MAP [MAP ...]] [-i IMG] [-u] [-c CFG] [-s SCAN [SCAN ...]] [-f]
95 | [-z ZABBIX] [-l LOGIN] [-p PWD]
96 |
97 | Network weathermap for Zabbix
98 |
99 | optional arguments:
100 | -v, --version show version
101 | -h, --help show help
102 | -d, --debug Enable debug mode
103 | -m MAP [MAP ..], --map MAP [MAP ..] Config file names
104 | -i IMG, --img IMG Image path
105 | -u, --upload Image upload to zabbix
106 | -c CFG, --cfg CFG Config path
107 | -s SCAN [SCAN ..], --scan SCAN [SCAN ..] Map names in Zabbix
108 | -f, --file Zabbix authentication from map config file
109 | -z ZABBIX, --zabbix ZABBIX Zabbix server url
110 | -l LOGIN, --login LOGIN Login
111 | -p PWD, --pwd PWD Password
112 |
113 | # Examples:
114 | # When map config exist. If you change map remove host or change position host,
115 | # configuration will be updated in accordance with changes on the map.
116 | weathermap.py -s mapname1 mapnameN -f
117 |
118 | # First time scan map, config file not exist. Create file with map configuration.
119 | weathermap.py -s mapname1 mapnameN -z http://zabbix.example.ru -l login -p password
120 |
121 | # Only create image, like old style Network Weathermap.
122 | weathermap.py -m mapname1.yaml mapnameN.yaml -i /var/www/weather
123 |
124 | # Create and upload image to Zabbix.
125 | weathermap.py -m mapname1.yaml mapnameN.yaml -u
126 |
127 | **starter.py** run weathermap.py and return execution time.
128 |
129 | For auto update image or rescan map you can use cron, systemd or Template Weathermap.
130 |
131 | ### Map config ###
132 | ```yaml
133 | %YAML 1.2
134 | ---
135 | map:
136 | name: mapname1
137 | bgcolor: '' #background RGB color, default transparent
138 | fontsize: 10
139 | width: 1200
140 | height: 800
141 | zabbix:
142 | url: http://zabbix.example.com
143 | login: admin
144 | password: admin
145 | table: # show legend and date time
146 | show: true
147 | x: 1100
148 | y: 100
149 | palette: # RGB color arrow
150 | - '#908C8C'
151 | - '#FFFFFF'
152 | - '#8000FF'
153 | - '#0000FF'
154 | - '#00EAEA'
155 | - '#00FF00'
156 | - '#FFFF00'
157 | - '#FF9933'
158 | - '#FF0000'
159 | link: # default settings link
160 | bandwidth: 100 # in Mbits/s
161 | width: 10 # width arrow in pixels
162 | node-Router:
163 | name: Символы # Get from Zabbix
164 | label: R1 # For old style Network Weathermap, draw label
165 | icon: Router64.png # For old style Network Weathermap, draw icon, if path not exist, use defaults
166 | x: 625
167 | y: 225
168 | node-Router2:
169 | name: ''
170 | label: R2
171 | icon: Router64.png
172 | x: 625
173 | y: 225
174 | node-Switch:
175 | name: ''
176 | label: SW1
177 | icon: Switch64.png
178 | x: 75
179 | y: 375
180 | node-Switch2:
181 | name: ''
182 | label: SW2
183 | icon: Switch64.png
184 | x: 75
185 | y: 375
186 | link-1:
187 | node1: node-Router
188 | node2: node-Switch
189 | name1: '' # For human readability, get from zabbix
190 | name2: '' # For human readability, get from zabbix
191 | width: 15 # Override default settings in link
192 | hostname: Router
193 | itemin: ifHCInOctets[ge-0/0/0]
194 | itemout: ifHCOutOctets[ge-0/0/0]
195 | link-2:
196 | node1: node-Router2
197 | node2: node-Switch2
198 | name1: ''
199 | name2: ''
200 | bandwidth: 1000 # Override default settings in link
201 | hostname: Router2
202 | itemin: ifHCInOctets[ge-0/0/1]
203 | itemout: ifHCOutOctets[ge-0/0/1]
204 | ...
205 | ```
206 | Option copy type bool, copy link and nodes in new config, when link and nodes not exist in zabbix map
207 | ```yaml
208 | link-lyonlz7x:
209 | node1: node-nridx7c0
210 | node2: node-uwf443jw
211 | name1: net1
212 | name2: net2
213 | copy: true
214 | hostname: R10
215 | itemin: ifHCOutOctets[1/6]
216 | itemout: ifHCInOctets[1/6]
217 | ```
218 | ### Notice ###
219 |
220 | Zabbix 3.4.x do not refresh background image on map. [FIX!](https://github.com/Prototype-X/Zabbix-Network-Weathermap/issues/26#issuecomment-362691241)
221 |
222 | Zabbix API performance is low. Zabbix agent run weathermap.py. Weathermap.py can be terminated by timeout, set in
223 | zabbix_agentd.conf.
224 |
225 | Decision:
226 |
227 | 1. Increase the timeout for example: zabbix_agentd.conf set Timeout=10
228 |
229 | 2. One item to one map in Template Weathermap
230 |
231 | 3. Use cron to run the scripts
232 |
233 | If you need convert from old style config to YAML format, use **converter.py**
234 |
235 | user@pc:~$ converter.py /path-to-old-style-cfg/map.cfg
236 | user@pc:~$ ls /path-to-old-style-cfg
237 | map.cfg
238 | map.yaml
239 |
240 | For a better look of map, set the link type a dot and color like background.
241 |
242 | [](https://gitter.im/Prototype-X/Zabbix-Network-Weathermap?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
243 |
--------------------------------------------------------------------------------
/template/weathermap.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 3.0
4 | 2016-04-14T13:18:11Z
5 |
6 |
7 | Templates
8 |
9 |
10 |
11 |
12 | Template Weathermap
13 | Template Weathermap
14 |
15 |
16 |
17 | Templates
18 |
19 |
20 |
21 |
22 | Weathermap
23 |
24 |
25 |
26 | -
27 | weather scan file
28 | 0
29 |
30 | 0
31 |
32 | weathermap.scan.file[{$SCANFILE}]
33 | 3600
34 | 90
35 | 365
36 | 0
37 | 0
38 |
39 | sec
40 | 0
41 |
42 |
43 | 0
44 | 0
45 |
46 | 0
47 |
48 | 1
49 |
50 |
51 |
52 | 0
53 | 0
54 |
55 |
56 |
57 |
58 |
59 | Scan map, config file exist. Zabbix auth from config file.
60 | 0
61 |
62 |
63 | Weathermap
64 |
65 |
66 |
67 |
68 |
69 | -
70 | weather scan map
71 | 0
72 |
73 | 0
74 |
75 | weathermap.scan.map[{$SCANMAP}]
76 | 3600
77 | 90
78 | 365
79 | 1
80 | 0
81 |
82 | sec
83 | 0
84 |
85 |
86 | 0
87 | 0
88 |
89 | 0
90 |
91 | 1
92 |
93 |
94 |
95 | 0
96 | 0
97 |
98 |
99 |
100 |
101 |
102 | First scan map, config file not exist. Zabbix auth from cli (-z http://zabbix.example.ru -l admin -p admin)
103 | 0
104 |
105 |
106 | Weathermap
107 |
108 |
109 |
110 |
111 |
112 | -
113 | weather update
114 | 0
115 |
116 | 0
117 |
118 | weathermap.update.only[{$UPDATE}]
119 | 60
120 | 90
121 | 365
122 | 0
123 | 0
124 |
125 | sec
126 | 0
127 |
128 |
129 | 0
130 | 0
131 |
132 | 0
133 |
134 | 1
135 |
136 |
137 |
138 | 0
139 | 0
140 |
141 |
142 |
143 |
144 |
145 | Create image path (-i /var/www/weather).
146 | 0
147 |
148 |
149 | Weathermap
150 |
151 |
152 |
153 |
154 |
155 | -
156 | weather upload
157 | 0
158 |
159 | 0
160 |
161 | weathermap.update.upload[{$UPLOAD}]
162 | 60
163 | 90
164 | 365
165 | 0
166 | 0
167 |
168 | sec
169 | 0
170 |
171 |
172 | 0
173 | 0
174 |
175 | 0
176 |
177 | 1
178 |
179 |
180 |
181 | 0
182 | 0
183 |
184 |
185 |
186 |
187 |
188 | Create and upload image in Zabbix
189 | 0
190 |
191 |
192 | Weathermap
193 |
194 |
195 |
196 |
197 |
198 |
199 |
200 |
201 |
202 | {$SCANFILE}
203 | -s mapname1 mapnameN -f
204 |
205 |
206 | {$SCANMAP}
207 | -s mapname1 mapnameN -z http://zabbix.example.ru -l admin -p admin
208 |
209 |
210 | {$UPDATE}
211 | -m mapname1.yaml mapnameN.yaml -i /var/www/weather
212 |
213 |
214 | {$UPLOAD}
215 | -m mapname1.yaml mapnameN.yaml -u
216 |
217 |
218 |
219 |
220 |
221 |
222 |
223 |
224 | Weather load
225 | 900
226 | 200
227 | 0.0000
228 | 100.0000
229 | 1
230 | 1
231 | 0
232 | 1
233 | 0
234 | 0.0000
235 | 0.0000
236 | 0
237 | 0
238 | 0
239 | 0
240 |
241 |
242 | 0
243 | 1
244 | 00CC00
245 | 0
246 | 2
247 | 0
248 | -
249 | Template Weathermap
250 | weathermap.update.upload[{$UPLOAD}]
251 |
252 |
253 |
254 | 1
255 | 1
256 | 0000DD
257 | 0
258 | 2
259 | 0
260 | -
261 | Template Weathermap
262 | weathermap.scan.file[{$SCANFILE}]
263 |
264 |
265 |
266 |
267 |
268 |
269 |
--------------------------------------------------------------------------------
/converter.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | # __author__ = 'maximus'
4 |
5 | import argparse
6 | import configparser
7 | import logging
8 | import ruamel.yaml as yaml3ed
9 | from collections import OrderedDict
10 | import sys
11 | import os
12 | # from mapping import Palette, Singleton
13 |
14 | log = logging.getLogger(__name__)
15 |
16 |
17 | class Singleton(type):
18 | _instances = {}
19 |
20 | def __call__(cls, *args, **kwargs):
21 | if cls not in cls._instances:
22 | cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
23 | return cls._instances[cls]
24 |
25 |
26 | class Palette(metaclass=Singleton): # noqa
27 | def __init__(self):
28 | self.palette = ['#908C8C', '#FFFFFF', '#8000FF', '#0000FF', '#00EAEA', '#00FF00', '#FFFF00', '#FF9933',
29 | '#FF0000']
30 | self.palette_default = ('#908C8C', '#FFFFFF', '#8000FF', '#0000FF', '#00EAEA', '#00FF00', '#FFFF00',
31 | '#FF9933', '#FF0000')
32 | log.debug('Object singleton Palette created')
33 |
34 | def reset(self):
35 | self.palette = list(self.palette_default)
36 |
37 |
38 | class ConfigException(Exception):
39 | def __init__(self, message):
40 | self.message = message
41 |
42 | # def __str__(self):
43 | # return str(self.message).format(self.error)
44 |
45 |
46 | class ConfigTemplateYaml(metaclass=Singleton):
47 | """ This is config template. DO NOT MODIFY THIS OBJECT."""
48 |
49 | def __init__(self):
50 | self.template = {'zabbix': {'url': str(), 'login': str(), 'password': str()},
51 | 'map': {'name': str(), 'bgcolor': str(), 'fontsize': 10, 'width': int(), 'height': int()},
52 | 'table': {'show': False, 'x': int(), 'y': int()},
53 | 'link': {'width': 10, 'bandwidth': 100},
54 | 'palette': Palette().palette,
55 | 'node-': {'name': str(), 'label': str(), 'icon': str(), 'x': int(), 'y': int()},
56 | 'link-': {'node1': str(), 'node2': str(), 'name1': str(), 'name2': str(), 'copy': '0',
57 | 'hostname': str(), 'itemin': str(), 'itemout': str(), 'width': int(),
58 | 'bandwidth': int()}
59 | }
60 | log.debug('Object singleton ConfigTemplateYaml created')
61 |
62 |
63 | class ConfigTemplate(object):
64 | """ This is config template dict. DO NOT MODIFY THIS OBJECT."""
65 | def __init__(self):
66 | self.base = {'zabbix': {'url': str(), 'login': str(), 'password': str()},
67 | 'map': {'name': str(), 'bgcolor': str(), 'fontsize': '10', 'width': int(), 'height': int()},
68 | 'table': {'show': False, 'x': int(), 'y': int()},
69 | 'link': {'width': 10, 'bandwidth': 100},
70 | 'palette': {'0': '#908C8C', '1': '#FFFFFF', '2': '#8000FF',
71 | '3': '#0000FF', '4': '#00EAEA',
72 | '5': '#00FF00', '6': '#FFFF00',
73 | '7': '#FF9933', '8': '#FF0000'}
74 | }
75 |
76 | self.node = {'name': str(), 'label': str(), 'icon': str(), 'x': int(), 'y': int()}
77 | self.link = {'node1': str(), 'node2': str(), 'name1': str(), 'name2': str(), 'copy': '0', 'hostname': str(),
78 | 'itemin': str(), 'itemout': str(), 'width': int(), 'bandwidth': int()}
79 | log.debug('Object ConfigTemplate created')
80 |
81 |
82 | class ConfigLoader(object):
83 | def __init__(self, path_cfg):
84 | self.config = configparser.ConfigParser()
85 | if self.config.read(path_cfg):
86 | self.config.read(path_cfg)
87 | else:
88 | raise ConfigException('file not found: {0}'.format(path_cfg))
89 | self.obj_nodes = {}
90 | self.obj_links = {}
91 | self.template = ConfigTemplate()
92 | self.cfg_dict = {}
93 | self.zbx = None
94 | log.debug('Object ConfigLoader created')
95 |
96 | def load(self):
97 |
98 | base = self.template.base.copy()
99 | node = self.template.node.copy()
100 | link = self.template.link.copy()
101 |
102 | for section in base.keys():
103 | if not self.config.has_section(section):
104 | raise ConfigException('section [{0}] is not present in the config'.format(section))
105 |
106 | for option in base[section]:
107 | if not self.config.has_option(section, option):
108 | raise ConfigException('The option: {0} is missing in section: [{1}]'.format(option, section))
109 | else:
110 | base[section][option] = self.config[section][option]
111 |
112 | for name in self.config.sections():
113 | if 'node-' in name:
114 | for option in node:
115 | if not self.config.has_option(name, option):
116 | raise ConfigException('The option: {0} is missing in section: [{1}]'.format(option, name))
117 | else:
118 | node[option] = self.config[name][option]
119 | self.obj_nodes[name] = None
120 | base[name] = node.copy()
121 | node = node.fromkeys(node)
122 |
123 | if 'link-' in name:
124 | for option in link:
125 | try:
126 | link[option] = self.config[name][option]
127 | except (configparser.NoOptionError, KeyError):
128 | if option == 'width':
129 | link['width'] = self.config['link']['width']
130 | elif option == 'bandwidth':
131 | link['bandwidth'] = self.config['link']['bandwidth']
132 | elif option == 'copy':
133 | pass
134 | elif not self.config.has_option(name, option):
135 | raise ConfigException('The option: {0} is missing in section: [{1}]'
136 | .format(option, name))
137 | if link['hostname'] and link['itemin'] and link['itemout']:
138 | self.obj_links[name] = None
139 | base[name] = link.copy()
140 | link = link.fromkeys(link)
141 | log.debug('Config dict: %s', base)
142 | self.cfg_dict = base.copy()
143 |
144 | del base
145 | del node
146 | del link
147 | self.fix_types_dict()
148 | # print(self.cfg_dict)
149 | return self.cfg_dict
150 |
151 | def fix_types_dict(self):
152 | for section in self.cfg_dict:
153 | if section == 'map':
154 | self.cfg_dict[section]['fontsize'] = int(self.cfg_dict[section]['fontsize'])
155 | self.cfg_dict[section]['width'] = int(self.cfg_dict[section]['width'])
156 | self.cfg_dict[section]['height'] = int(self.cfg_dict[section]['height'])
157 | if section == 'table':
158 | self.cfg_dict[section]['show'] = bool(self.cfg_dict[section]['show'])
159 | self.cfg_dict[section]['x'] = int(self.cfg_dict[section]['x'])
160 | self.cfg_dict[section]['y'] = int(self.cfg_dict[section]['y'])
161 | if section == 'link':
162 | self.cfg_dict[section]['bandwidth'] = int(self.cfg_dict[section]['bandwidth'])
163 | self.cfg_dict[section]['width'] = int(self.cfg_dict[section]['width'])
164 | if 'node-' in section:
165 | self.cfg_dict[section]['x'] = int(self.cfg_dict[section]['x'])
166 | self.cfg_dict[section]['y'] = int(self.cfg_dict[section]['y'])
167 | try:
168 | self.cfg_dict[section]['label']
169 | except KeyError:
170 | continue
171 |
172 | try:
173 | self.cfg_dict[section]['icon']
174 | except KeyError:
175 | continue
176 |
177 | if not self.cfg_dict[section]['label']:
178 | del self.cfg_dict[section]['label']
179 |
180 | if not self.cfg_dict[section]['icon']:
181 | del self.cfg_dict[section]['icon']
182 |
183 | if 'link-' in section:
184 | try:
185 | self.cfg_dict[section]['copy']
186 | except KeyError:
187 | continue
188 | if isinstance(self.cfg_dict[section]['copy'], str):
189 | self.cfg_dict[section]['copy'] = int(self.cfg_dict[section]['copy'])
190 | self.cfg_dict[section]['copy'] = bool(self.cfg_dict[section]['copy'])
191 | if not self.cfg_dict[section]['copy']:
192 | del self.cfg_dict[section]['copy']
193 |
194 | if self.cfg_dict[section].get('width'):
195 | self.cfg_dict[section]['width'] = int(self.cfg_dict[section]['width'])
196 | if int(self.cfg_dict[section]['width']) == int(self.cfg_dict['link']['width']):
197 | del self.cfg_dict[section]['width']
198 |
199 | if self.cfg_dict[section].get('bandwidth'):
200 | self.cfg_dict[section]['bandwidth'] = int(self.cfg_dict[section]['bandwidth'])
201 | if int(self.cfg_dict[section]['bandwidth']) == int(self.cfg_dict['link']['bandwidth']):
202 | del self.cfg_dict[section]['bandwidth']
203 |
204 |
205 | class ConfigConvert(object):
206 | def __init__(self, cfg_dict: dict):
207 | self.cfg_dict = cfg_dict
208 | self.template = ConfigTemplateYaml().template
209 | self.setup_yaml()
210 | self.palette_convert()
211 | log.debug('Object ConfigCreate created')
212 |
213 | def palette_convert(self):
214 | palette_new = list([self.cfg_dict['palette'][str(i)] for i in range(0, 9)])
215 | # print(palette_new)
216 | self.cfg_dict['palette'] = palette_new
217 |
218 | @staticmethod
219 | def setup_yaml():
220 | """ StackOverflow Driven Development
221 | http://stackoverflow.com/a/8661021 """
222 |
223 | def represent_dict_order(yaml_self, data):
224 | return yaml_self.represent_mapping('tag:yaml.org,2002:map', data.items())
225 |
226 | yaml3ed.add_representer(OrderedDict, represent_dict_order)
227 |
228 | @staticmethod
229 | def _dict_to_orderdict(cfg: dict) -> OrderedDict:
230 | cfg_order = OrderedDict()
231 | cfg_templ = OrderedDict([('map', ('name', 'bgcolor', 'fontsize', 'width', 'height')),
232 | ('zabbix', ('url', 'login', 'password')),
233 | ('table', ('show', 'x', 'y')),
234 | ('palette', None),
235 | ('link', ('bandwidth', 'width')),
236 | ('node-', ('name', 'label', 'icon', 'x', 'y')),
237 | ('link-', ('node1', 'node2', 'name1', 'name2', 'copy', 'width', 'bandwidth',
238 | 'hostname', 'itemin', 'itemout'))
239 | ])
240 |
241 | for cfg_sect in cfg_templ:
242 |
243 | if cfg_sect == 'node-':
244 | for node in sorted([node for node in cfg.keys() if cfg_sect in node]):
245 | cfg_order[node] = OrderedDict()
246 | for cfg_opt in cfg_templ[cfg_sect]:
247 | if cfg_opt == 'icon' and cfg_opt not in cfg[node]:
248 | continue
249 | if cfg_opt == 'label' and cfg_opt not in cfg[node]:
250 | continue
251 | cfg_order[node][cfg_opt] = cfg[node][cfg_opt]
252 | continue
253 |
254 | if cfg_sect == 'link-':
255 | for link in sorted([link for link in cfg.keys() if cfg_sect in link]):
256 | cfg_order[link] = OrderedDict()
257 | for cfg_opt in cfg_templ[cfg_sect]:
258 | if cfg_opt == 'copy' and cfg_opt not in cfg[link]:
259 | continue
260 | if cfg_opt == 'width' and cfg_opt not in cfg[link]:
261 | continue
262 | if cfg_opt == 'bandwidth' and cfg_opt not in cfg[link]:
263 | continue
264 | cfg_order[link][cfg_opt] = cfg[link][cfg_opt]
265 | continue
266 |
267 | cfg_order[cfg_sect] = OrderedDict()
268 | if cfg_sect == 'palette':
269 | cfg_order[cfg_sect] = cfg[cfg_sect]
270 | continue
271 |
272 | for cfg_opt in cfg_templ[cfg_sect]:
273 | if cfg_sect == 'map' and cfg_opt == 'bgcolor' and cfg_opt not in cfg[cfg_sect]:
274 | continue
275 | cfg_order[cfg_sect][cfg_opt] = cfg[cfg_sect][cfg_opt]
276 | # print(cfg_order)
277 | return cfg_order
278 |
279 | def save(self, path: str):
280 | cfg = self._dict_to_orderdict(self.cfg_dict)
281 | with open(path[:-3] + 'yaml', 'w') as cfg_file:
282 | try:
283 | yaml3ed.dump(cfg, cfg_file, explicit_start=True, explicit_end=True,
284 | default_flow_style=False, allow_unicode=True, version=(1, 2),
285 | indent=2)
286 | except yaml3ed.YAMLError as exc:
287 | print(exc)
288 |
289 |
290 | def main():
291 | # root_path = str(os.path.dirname(os.path.abspath(__file__)))
292 | parser = argparse.ArgumentParser(conflict_handler='resolve', description='Convert to yaml')
293 | parser.add_argument('cfg', action='store', type=str, help='Old style config file')
294 | args = parser.parse_args()
295 | if args.cfg:
296 | cfg_dict = ConfigLoader(args.cfg).load()
297 | cfg_yaml = ConfigConvert(cfg_dict)
298 | cfg_yaml.save(args.cfg)
299 | else:
300 | sys.exit()
301 |
302 | if __name__ == '__main__':
303 | main()
304 |
--------------------------------------------------------------------------------
/mapping.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | # __author__ = 'maximus'
4 |
5 | from PIL import Image, ImageDraw, ImageFont
6 | from datetime import datetime
7 | import math
8 | import os
9 | import logging
10 |
11 | log = logging.getLogger(__name__)
12 |
13 |
14 | class Singleton(type):
15 | _instances = {}
16 |
17 | def __call__(cls, *args, **kwargs):
18 | if cls not in cls._instances:
19 | cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
20 | return cls._instances[cls]
21 |
22 |
23 | class Palette(metaclass=Singleton): # noqa
24 | def __init__(self):
25 | self.palette = ['#908C8C', '#FFFFFF', '#8000FF', '#0000FF', '#00EAEA', '#00FF00', '#FFFF00', '#FF9933',
26 | '#FF0000']
27 | self.palette_default = ('#908C8C', '#FFFFFF', '#8000FF', '#0000FF', '#00EAEA', '#00FF00', '#FFFF00',
28 | '#FF9933', '#FF0000')
29 | log.debug('Object singleton Palette created')
30 |
31 | def reset(self):
32 | self.palette = list(self.palette_default)
33 |
34 |
35 | class Table(object):
36 | def __init__(self, fontfile, x=0, y=0, palette=Palette().palette_default, fontsize=12, dt=True):
37 | self.x = x
38 | self.y = y
39 | self.width_palet = 30
40 | self.height_palet = 20
41 | self.yt = y + self.height_palet
42 | self.indent_x = 5
43 | self.indent_y = 3
44 | self.palette = palette
45 | self.text_label = 'Traffic Load'
46 | self.rect_xy = []
47 | self.table_xy()
48 | self.text = ('0-0%', '0-1%', '1-10%', '10-25%', '25-40%', '40-55%', '55-70%', '70-85%', '85-100%')
49 | self.fontfile = fontfile
50 | self.fontcolor = 'black'
51 | self.fontsize = fontsize
52 | self.font = ImageFont.truetype(self.fontfile, size=self.fontsize)
53 | self.dt = dt
54 | self.dt_obj = None
55 | self.date_now = None
56 | self.time_now = None
57 | log.debug('Object Table created')
58 |
59 | def table_xy(self):
60 | for i in range(0, 11):
61 | x1 = self.x + self.indent_x
62 | y1 = self.yt + self.indent_y + self.height_palet * i
63 | x2 = self.x + self.indent_x + self.width_palet
64 | y2 = self.yt + self.height_palet * (i + 1)
65 | self.rect_xy.append((x1, y1, x2, y2))
66 |
67 | def draw_table(self, draw):
68 | draw.rectangle((self.x, self.y, self.rect_xy[8][2] + 60, self.rect_xy[8][3] + 5), outline='black', fill='white')
69 | draw.text((self.x + 5, self.y + 5), self.text_label, fill='black', font=self.font)
70 |
71 | for i in range(0, 9):
72 | draw.rectangle(self.rect_xy[i], fill=self.palette[i], outline=self.palette[i])
73 | draw.text((self.rect_xy[i][2] + 2, self.rect_xy[i][1] + 2), self.text[i], fill='black', font=self.font)
74 | if self.dt:
75 | self.draw_datetime(draw)
76 |
77 | def draw_datetime(self, draw):
78 | self.dt_obj = datetime.now()
79 | self.date_now = datetime.strftime(self.dt_obj, "%d.%m.%Y")
80 | self.time_now = datetime.strftime(self.dt_obj, "%H:%M:%S")
81 | draw.rectangle((self.x, self.rect_xy[9][1] + 5, self.rect_xy[10][2] + 60,
82 | self.rect_xy[10][3] + 5), outline='black', fill='white')
83 | draw.text((self.rect_xy[9][0] + 14, self.rect_xy[9][1] + 8), self.time_now, fill='black', font=self.font)
84 | draw.text((self.rect_xy[10][0] + 8, self.rect_xy[10][1] + 4), self.date_now, fill='black', font=self.font)
85 | log.debug('Object Table draw')
86 |
87 |
88 | class Label(object):
89 | def __init__(self, fontfile, bgcolor='white', fontcolor='black', fontsize=10, outline='black', label=None,
90 | point=None):
91 | self.outline = outline
92 | self.bgcolor = bgcolor
93 | self.fontcolor = fontcolor
94 | self.fontsize = fontsize
95 | self.fontfile = fontfile
96 | self.font = ImageFont.truetype(self.fontfile, size=self.fontsize)
97 | self.name = str(label)
98 | self.points = [0, 0, 0, 0]
99 | self.point_name = [0, 0]
100 | self.font_width = {8: 6, 10: 7.4, 12: 8, 14: 9, 16: 11, 18: 12, 20: 13}
101 |
102 | try:
103 | self.font_width[self.fontsize]
104 | except KeyError:
105 | self.fontsize = 10
106 |
107 | if point:
108 | self.label_xy(point)
109 | log.debug('Object Label created')
110 |
111 | def label_xy(self, point):
112 | """font_dict = {fontsize:symbol width}
113 | symbol height = fontsize
114 | :param point: coordinates where label show"""
115 | count = len(self.name)
116 | if count:
117 | self.points[0] = int(point[0] - count * self.font_width[self.fontsize] / 2 + 1)
118 | self.points[1] = int(point[1] - self.fontsize/2)
119 | self.points[2] = int(point[0] + count * self.font_width[self.fontsize] / 2 - 1)
120 | self.points[3] = int(point[1] + self.fontsize/2 + 1)
121 | self.point_name[0] = self.points[0] + 2
122 | self.point_name[1] = self.points[1]
123 |
124 |
125 | class Node(object):
126 | """ Node (device) on a map"""
127 | def __init__(self, fontfile, icon_path, x=0, y=0, label=None, icon=None, fontsize=10):
128 | self.x = x
129 | self.y = y
130 | self.icon = icon
131 | self.icon_path = icon_path
132 | self.icon_point = None
133 | self.label_obj = None
134 | if label:
135 | self.label_obj = Label(label=label, point=[x, y], fontfile=fontfile, fontsize=fontsize)
136 | if self.icon:
137 | self.icon_point = self.icon_xy()
138 | log.debug('Object Node created')
139 |
140 | def icon_xy(self):
141 | if os.path.isfile(self.icon_path + '/' + self.icon):
142 | im = Image.open(self.icon_path + '/' + self.icon)
143 | else:
144 | im = Image.open(self.icon)
145 | width, height = im.size
146 | x = int(self.x - width/2)
147 | y = int(self.y - height/2)
148 | im.close()
149 | return [x, y]
150 |
151 |
152 | class Link(object):
153 | """ A line between two Nodes. The line contains two arrows: one for an input
154 | value and one for an output value"""
155 | def __init__(self, fontfile, node_a, node_b, bandwidth=1000, width=5, palette=Palette().palette_default,
156 | fontsize=10):
157 | self.node_a = node_a
158 | self.node_b = node_b
159 | self.fontfile = fontfile
160 | self.fontsize = fontsize
161 | self.bandwidth = bandwidth
162 | self.width = float(width)
163 | self.palette = palette
164 | self.input_points = self._get_input_arrow_points()
165 | self.output_points = self._get_output_arrow_points()
166 | self.incolor = None
167 | self.outcolor = None
168 | self.in_label = None
169 | self.out_label = None
170 | log.debug('Object Link created')
171 |
172 | @staticmethod
173 | def _middle(x, y):
174 | """ Return a middle point coordinate between 2 given points """
175 | return int(x+(y-x)/2)
176 |
177 | @staticmethod
178 | def _new_x(a, b, x, y):
179 | """ Calculate "x" coordinate """
180 | return int(math.cos(math.atan2(y, x) + math.atan2(b, a))*math.sqrt(x*x+y*y))
181 |
182 | @staticmethod
183 | def _new_y(a, b, x, y):
184 | """ Calculate "y" coordinate """
185 | return int(math.sin(math.atan2(y, x) + math.atan2(b, a))*math.sqrt(x*x+y*y))
186 |
187 | def data(self, in_bps=0000, out_bps=749890567):
188 | in_kps = in_bps/1000
189 | out_kps = out_bps/1000
190 | self._fill_arrow(in_kps, out_kps)
191 | in_name, out_name = self._name(in_kps, out_kps)
192 | in_point = self._get_input_label_point()
193 | out_point = self._get_output_label_point()
194 | self.in_label = Label(self.fontfile, label=in_name, point=in_point, fontsize=self.fontsize)
195 | self.out_label = Label(self.fontfile, label=out_name, point=out_point, fontsize=self.fontsize)
196 |
197 | @staticmethod
198 | def _name(in_kps, out_kps):
199 | if 0 <= in_kps <= 999:
200 | in_label = str(round(in_kps, 2)) + 'K'
201 |
202 | elif 999 < in_kps <= 999999:
203 | in_mps = in_kps/1000
204 | in_label = str(round(in_mps, 2)) + 'M'
205 |
206 | elif in_kps > 999999:
207 | in_gps = in_kps/1000000
208 | in_label = str(round(in_gps, 2)) + 'G'
209 |
210 | else:
211 | in_label = 'ERR'
212 |
213 | if 0 <= out_kps <= 999:
214 | out_label = str(round(out_kps, 2)) + 'K'
215 |
216 | elif 999 < out_kps <= 999999:
217 | out_mps = out_kps/1000
218 | out_label = str(round(out_mps, 2)) + 'M'
219 |
220 | elif out_kps > 999999:
221 | out_gps = out_kps/1000000
222 | out_label = str(round(out_gps, 2)) + 'G'
223 |
224 | else:
225 | out_label = 'ERR'
226 |
227 | return in_label, out_label
228 |
229 | def _fill_arrow(self, in_kps, out_kps):
230 | switch = ((0, 0, 1), (1, 1, 2), (2, 2, 10), (3, 10, 25), (4, 25, 40), (5, 40, 55), (6, 55, 70), (7, 70, 85),
231 | (8, 85, 100), (8, 100, 100000))
232 |
233 | in_percent = math.ceil(in_kps / (self.bandwidth * 10))
234 | out_percent = math.ceil(out_kps / (self.bandwidth * 10))
235 | for sw in switch:
236 | if in_percent in range(sw[1], sw[2]):
237 | self.incolor = self.palette[sw[0]]
238 | if out_percent in range(sw[1], sw[2]):
239 | self.outcolor = self.palette[sw[0]]
240 |
241 | def _get_arrow_points(self, x1, y1, x2, y2, width):
242 | """
243 | Calculate points of an arrow
244 | @param x1: x of first point
245 | @param y1: y of first point
246 | @param x2: x of second point
247 | @param y2: y of second point
248 | @param width: width of arrow
249 | """
250 | points = [(x1+self._new_x(x2 - x1, y2 - y1, 0, width),
251 | y1+self._new_y(x2 - x1, y2 - y1, 0, width)),
252 |
253 | (x2+self._new_x(x2 - x1, y2 - y1, -4 * width, width),
254 | y2+self._new_y(x2 - x1, y2 - y1, -4 * width, width)),
255 |
256 | (x2+self._new_x(x2 - x1, y2 - y1, -4 * width, 2 * width),
257 | y2+self._new_y(x2 - x1, y2 - y1, -4 * width, 2 * width)),
258 |
259 | (x2, y2),
260 |
261 | (x2+self._new_x(x2 - x1, y2 - y1, -4 * width, -2 * width),
262 | y2+self._new_y(x2 - x1, y2 - y1, -4 * width, -2 * width)),
263 |
264 | (x2+self._new_x(x2 - x1, y2 - y1, -4 * width, -width),
265 | y2+self._new_y(x2 - x1, y2 - y1, -4 * width, -width)),
266 |
267 | (x1+self._new_x(x2 - x1, y2 - y1, 0, -width),
268 | y1+self._new_y(x2 - x1, y2 - y1, 0, -width))]
269 | return points
270 |
271 | def _get_input_label_point(self):
272 | label_x = self._middle(self.node_a.x, self._middle(self.node_a.x, self.node_b.x))
273 | label_y = self._middle(self.node_a.y, self._middle(self.node_a.y, self.node_b.y))
274 | return [label_x, label_y]
275 |
276 | def _get_input_arrow_points(self):
277 | """
278 | Calculating points of the input arrow
279 | """
280 | points = self._get_arrow_points(
281 | self.node_a.x,
282 | self.node_a.y,
283 | self._middle(self.node_a.x, self.node_b.x),
284 | self._middle(self.node_a.y, self.node_b.y),
285 | self.width,
286 | )
287 | return points
288 |
289 | def _get_output_label_point(self):
290 | label_x = self._middle(self.node_b.x, self._middle(self.node_b.x, self.node_a.x))
291 | label_y = self._middle(self.node_b.y, self._middle(self.node_b.y, self.node_a.y))
292 | return [label_x, label_y]
293 |
294 | def _get_output_arrow_points(self):
295 | """
296 | Calculating points of the output arrow
297 | """
298 | points = self._get_arrow_points(
299 | self.node_b.x,
300 | self.node_b.y,
301 | self._middle(self.node_b.x, self.node_a.x),
302 | self._middle(self.node_b.y, self.node_a.y),
303 | self.width,
304 | )
305 | return points
306 |
307 |
308 | class Map(object):
309 | def __init__(self, links, nodes, table=None, len_x=800, len_y=800, bgcolor=None, ):
310 | # Link instance
311 | self.bgcolor = bgcolor
312 | self.links = links
313 | self.table = table
314 | self.nodes = nodes
315 | self.image = self.create_image(len_x, len_y)
316 | self.draw = ImageDraw.Draw(self.image)
317 | log.debug('Object Map created')
318 |
319 | def create_image(self, x, y):
320 | """ Create a new image with a white background
321 | :param y: size image y
322 | :param x: size image x
323 | """
324 | img = Image.new("RGBA", (x, y), self.bgcolor)
325 | return img
326 |
327 | def _draw_polygon(self, points, color):
328 | """
329 | Draw the polygon (the arrow) for giving points
330 | @param points: list of points
331 | @param color: inside color of polygon (arrow)
332 | """
333 |
334 | self.draw.polygon(points, fill=color, outline='black')
335 |
336 | def _draw_label(self, label):
337 | self.draw.rectangle(label.points, fill=label.bgcolor, outline=label.outline)
338 | self.draw.text((label.point_name[0:2]), label.name, fill=label.fontcolor,
339 | font=label.font)
340 |
341 | def _draw_icon(self, icon, icon_point):
342 | if os.path.isfile(str(os.path.dirname(os.path.abspath(__file__))) + '/icons/' + icon):
343 | im = Image.open(str(os.path.dirname(os.path.abspath(__file__))) + '/icons/' + icon)
344 | else:
345 | im = Image.open(icon)
346 | im.convert("RGBA")
347 | self.image.paste(im, (icon_point[0], icon_point[1]), mask=im)
348 | im.close()
349 |
350 | def draw_arrows(self):
351 | for link in self.links:
352 | # draw input arrow
353 | self._draw_polygon(link.input_points, link.incolor)
354 | # draw output arrow
355 | self._draw_polygon(link.output_points, link.outcolor)
356 | log.debug('Draw arrows')
357 |
358 | def draw_labels(self):
359 | """ Draw labels method"""
360 | if self.nodes:
361 | for node in self.nodes:
362 | if node.label_obj:
363 | self._draw_label(node.label_obj)
364 | if self.links:
365 | for link in self.links:
366 | self._draw_label(link.in_label)
367 | self._draw_label(link.out_label)
368 | log.debug('Draw labels')
369 |
370 | def draw_icons(self):
371 | if self.nodes is not None:
372 | for node in self.nodes:
373 | if node.icon:
374 | self._draw_icon(node.icon, node.icon_point)
375 | log.debug('Draw icons')
376 |
377 | def do(self):
378 | if self.table:
379 | self.table.draw_table(self.draw)
380 | self.draw_arrows()
381 | self.draw_icons()
382 | self.draw_labels()
383 |
384 | def show(self):
385 | self.image.show()
386 |
387 | def save_img(self, path=str()):
388 | """
389 | Save the image to the file path
390 | @param path: path to the file
391 | """
392 | self.image.save(path, "PNG")
393 | log.debug('save img {}'.format(path))
394 | self.image.close()
395 |
--------------------------------------------------------------------------------
/config.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | # __author__ = 'maximus'
4 |
5 | import ruamel.yaml as yaml3ed
6 | from collections import OrderedDict
7 | import os
8 | import logging
9 | from zabbix import ZabbixAgent
10 | from mapping import Node, Link, Map, Table, Palette, Singleton
11 | from PIL import Image
12 | import base64
13 | import random
14 | from io import BytesIO
15 |
16 | log = logging.getLogger(__name__)
17 |
18 |
19 | class ConfigException(Exception):
20 | def __init__(self, message):
21 | self.message = message
22 |
23 | # def __str__(self):
24 | # return str(self.message).format(self.error)
25 |
26 |
27 | class ConfigTemplate(metaclass=Singleton): # noqa
28 | """ This is config template. DO NOT MODIFY THIS OBJECT."""
29 |
30 | def __init__(self):
31 | self.template = {'zabbix': {'url': str(), 'login': str(), 'password': str()},
32 | 'map': {'name': str(), 'bgcolor': str(), 'fontsize': 10, 'width': int(), 'height': int()},
33 | 'table': {'show': False, 'x': int(), 'y': int()},
34 | 'link': {'width': 10, 'bandwidth': 100},
35 | 'palette': Palette().palette,
36 | 'node-': {'name': str(), 'label': str(), 'icon': str(), 'x': int(), 'y': int()},
37 | 'link-': {'node1': str(), 'node2': str(), 'name1': str(), 'name2': str(), 'copy': 0,
38 | 'hostname': str(), 'itemin': str(), 'itemout': str(), 'width': int(),
39 | 'bandwidth': int()}
40 | }
41 | log.debug('Object singleton ConfigTemplate created')
42 |
43 |
44 | class ConfigLoader(object):
45 | def __init__(self, path_cfg: str):
46 |
47 | self.template = ConfigTemplate().template
48 | self.cfg_dict = {}
49 | self.obj_nodes = {}
50 | self.obj_links = {}
51 | self.zbx = None
52 | self.load(path_cfg)
53 | log.debug('Object ConfigLoader created')
54 |
55 | def load(self, path_cfg: str):
56 | with open(path_cfg, 'r') as stream:
57 | try:
58 | self.cfg_dict = yaml3ed.safe_load(stream)
59 | except yaml3ed.YAMLError as exc:
60 | print(exc)
61 | self.check()
62 | self.zbx = ZabbixAgent(self.cfg_dict['zabbix']['url'], self.cfg_dict['zabbix']['login'],
63 | self.cfg_dict['zabbix']['password'])
64 | log.debug('Config loaded')
65 |
66 | def check(self):
67 | for cfg_sect in self.template:
68 | if cfg_sect == 'node-':
69 | for node in sorted([node for node in self.cfg_dict.keys() if cfg_sect in node]):
70 | for cfg_opt in self.template[cfg_sect]:
71 | try:
72 | self.cfg_dict[node][cfg_opt]
73 | except KeyError:
74 | if cfg_opt == 'icon':
75 | # self.cfg_dict[node][cfg_opt] = str()
76 | continue
77 | if cfg_opt == 'label':
78 | # self.cfg_dict[node][cfg_opt] = str()
79 | continue
80 | raise ConfigException('The option: {0} is missing in section: [{1}]'
81 | .format(cfg_sect, cfg_opt))
82 |
83 | if cfg_sect == 'link-':
84 | for link in sorted([link for link in self.cfg_dict.keys() if cfg_sect in link]):
85 | for cfg_opt in self.template[cfg_sect]:
86 | try:
87 | self.cfg_dict[link][cfg_opt]
88 | except KeyError:
89 | if cfg_opt == 'copy':
90 | # self.cfg_dict[link][cfg_opt] = False
91 | continue
92 | if cfg_opt == 'width':
93 | # self.cfg_dict[link][cfg_opt] = int()
94 | continue
95 | if cfg_opt == 'bandwidth':
96 | # self.cfg_dict[link][cfg_opt] = int()
97 | continue
98 | raise ConfigException('The option: {0} is missing in section: [{1}]'
99 | .format(cfg_sect, cfg_opt))
100 |
101 | if cfg_sect == 'palette':
102 | if len(self.cfg_dict[cfg_sect]) != 9:
103 | raise ConfigException('Error in section {0}, number elements not equal 9'.format(cfg_sect))
104 | continue
105 |
106 | for cfg_opt in self.template[cfg_sect]:
107 | try:
108 | self.cfg_dict[cfg_sect][cfg_opt]
109 | except KeyError:
110 | # if cfg_sect == 'map' and cfg_opt == 'bgcolor':
111 | # self.cfg_dict[cfg_sect][cfg_opt] = str()
112 | if cfg_sect == 'link-' or cfg_sect == 'node-':
113 | continue
114 | raise ConfigException('The option: {0} is missing in section: [{1}]'.format(cfg_sect, cfg_opt))
115 | log.debug('Config check: Ok')
116 |
117 | def create_map(self, font_path_fn: str, icon_path: str):
118 | self.obj_nodes = {section: None for section in self.cfg_dict if 'node-' in section}
119 | self.obj_links = {section: None for section in self.cfg_dict if 'link-' in section}
120 | palette = self.cfg_dict['palette']
121 | fontsize = int(self.cfg_dict['map']['fontsize'])
122 |
123 | for node in self.obj_nodes.keys():
124 | x = int(self.cfg_dict[node]['x'])
125 | y = int(self.cfg_dict[node]['y'])
126 |
127 | if self.cfg_dict[node].get('label'):
128 | label = self.cfg_dict[node]['label']
129 | else:
130 | label = None
131 |
132 | if self.cfg_dict[node].get('icon'):
133 | icon = self.cfg_dict[node]['icon']
134 | else:
135 | icon = None
136 |
137 | self.obj_nodes[node] = (Node(font_path_fn, icon_path, x=x, y=y, label=label, icon=icon, fontsize=fontsize))
138 |
139 | for link in self.obj_links.keys():
140 | node1 = self.obj_nodes[self.cfg_dict[link]['node1']]
141 | node2 = self.obj_nodes[self.cfg_dict[link]['node2']]
142 |
143 | if self.cfg_dict[link].get('bandwidth'):
144 | bandwidth = self.cfg_dict[link]['bandwidth']
145 | else:
146 | bandwidth = self.cfg_dict['link']['bandwidth']
147 |
148 | if self.cfg_dict[link].get('width'):
149 | width = self.cfg_dict[link]['width']
150 | else:
151 | width = self.cfg_dict['link']['width']
152 |
153 | self.obj_links[link] = (Link(font_path_fn, node1, node2, bandwidth=bandwidth, width=width,
154 | palette=palette, fontsize=fontsize))
155 |
156 | hostname = self.cfg_dict[link]['hostname']
157 | item_in = self.cfg_dict[link]['itemin']
158 | item_out = self.cfg_dict[link]['itemout']
159 |
160 | if hostname and item_in and item_out:
161 | data_in, data_out = self.zbx.get_item_data2(hostname, item_in, item_out)
162 | self.obj_links[link].data(in_bps=data_in, out_bps=data_out)
163 | elif hostname and item_in:
164 | data_in = self.zbx.get_item_data(hostname, item_in)
165 | self.obj_links[link].data(in_bps=data_in, out_bps=0)
166 | elif hostname and item_out:
167 | data_out = self.zbx.get_item_data(hostname, item_out)
168 | self.obj_links[link].data(in_bps=0, out_bps=data_out)
169 | else:
170 | self.obj_links[link].data(in_bps=0, out_bps=0)
171 |
172 | if int(self.cfg_dict['table']['show']):
173 | table = Table(font_path_fn, x=int(self.cfg_dict['table']['x']), y=int(self.cfg_dict['table']['y']),
174 | palette=palette)
175 | else:
176 | table = None
177 |
178 | map_width = int(self.cfg_dict['map']['width'])
179 | map_height = int(self.cfg_dict['map']['height'])
180 | if self.cfg_dict['map']['bgcolor']:
181 | map_bgcolor = self.cfg_dict['map']['bgcolor']
182 | else:
183 | map_bgcolor = None
184 | map_obj = Map(self.obj_links.values(), self.obj_nodes.values(), table=table, len_x=map_width,
185 | len_y=map_height, bgcolor=map_bgcolor)
186 | return map_obj
187 |
188 | def upload(self, img_path_fn: str):
189 | self.zbx.image_to_zabbix(img_path_fn, self.cfg_dict['map']['name'])
190 |
191 |
192 | class ConfigCreate(object):
193 | def __init__(self, map_data: dict, zbx_agent: ZabbixAgent):
194 | self.zbx = zbx_agent
195 | self.map_data = map_data
196 | self.template = ConfigTemplate().template
197 | self.map_config = {}
198 | self.dict_call = [self.zbx.get_hostname, self.zbx.get_mapname,
199 | self.zbx.get_triggername, self.zbx.get_hostgroupname,
200 | self.zbx.get_imagename]
201 | self.cfg_loader_obj = None
202 | self.setup_yaml()
203 | log.debug('Object ConfigCreate created')
204 |
205 | @staticmethod
206 | def setup_yaml():
207 | """ StackOverflow Driven Development
208 | https://stackoverflow.com/a/31609484/4709370
209 | http://stackoverflow.com/a/8661021 """
210 |
211 | def represent_dict_order(yaml_self, data):
212 | return yaml_self.represent_mapping('tag:yaml.org,2002:map', data.items())
213 |
214 | yaml3ed.add_representer(OrderedDict, represent_dict_order)
215 |
216 | @staticmethod
217 | def random_label():
218 | return ''.join(random.SystemRandom().choice('abcdefgijklmnoprstuvwxyz1234567890') for _ in range(8))
219 |
220 | def create(self):
221 | elemid_dict = {}
222 | self.map_config['zabbix'] = {'url': self.zbx.url,
223 | 'login': self.zbx.login,
224 | 'password': self.zbx.password
225 | }
226 | self.map_config['map'] = {'name': self.map_data['name'],
227 | 'bgcolor': self.template['map']['bgcolor'],
228 | 'fontsize': self.template['map']['fontsize'],
229 | 'width': int(self.map_data['width']),
230 | 'height': int(self.map_data['height'])
231 | }
232 | self.map_config['table'] = {'show': self.template['table']['show'],
233 | 'x': int(self.map_data['width']) - 100,
234 | 'y': int(self.map_data['height']) - 300
235 | }
236 |
237 | self.map_config['palette'] = self.template['palette']
238 | self.map_config['link'] = self.template['link']
239 |
240 | for node in self.map_data['selements']:
241 | nodeid = node['selementid']
242 |
243 | if int(node['elementtype']) == 4:
244 | nodename = self.dict_call[int(node['elementtype'])](node['iconid_off'])
245 | elif int(node['elementtype']) == 3:
246 | nodename = self.dict_call[int(node['elementtype'])](node['elements'][0]['groupid'])
247 | elif int(node['elementtype']) == 2:
248 | nodename = self.dict_call[int(node['elementtype'])](node['elements'][0]['triggerid'])
249 | elif int(node['elementtype']) == 1:
250 | nodename = self.dict_call[int(node['elementtype'])](node['elements'][0]['sysmapid'])
251 | elif int(node['elementtype']) == 0:
252 | nodename = self.dict_call[int(node['elementtype'])](node['elements'][0]['hostid'])
253 |
254 | elemid_dict[node['selementid']] = nodename
255 |
256 | self.map_config['node-' + nodeid] = {'name': nodename, 'label': str(), 'icon': str()}
257 |
258 | image_b64code = self.zbx.image_get(node['iconid_off'])
259 | im = Image.open(BytesIO(base64.b64decode(image_b64code)))
260 | width, height = im.size
261 | self.map_config['node-' + nodeid] = {
262 | 'name': nodename,
263 | 'x': int(node['x']) + int(width // 2),
264 | 'y': int(node['y']) + int(height // 2)
265 | }
266 |
267 | for link in self.map_data['links']:
268 | self.map_config['link-' + link['linkid']] = {'node1': 'node-' + link['selementid2'],
269 | 'node2': 'node-' + link['selementid1'],
270 | 'name1': elemid_dict[link['selementid2']],
271 | 'name2': elemid_dict[link['selementid1']],
272 | 'hostname': str(),
273 | 'itemin': str(),
274 | 'itemout': str()
275 | }
276 | del elemid_dict
277 |
278 | @staticmethod
279 | def _dict_to_orderdict(cfg: dict) -> OrderedDict:
280 | cfg_order = OrderedDict()
281 | cfg_templ = OrderedDict([('map', ('name', 'bgcolor', 'fontsize', 'width', 'height')),
282 | ('zabbix', ('url', 'login', 'password')),
283 | ('table', ('show', 'x', 'y')),
284 | ('palette', None),
285 | ('link', ('bandwidth', 'width')),
286 | ('node-', ('name', 'label', 'icon', 'x', 'y')),
287 | ('link-', ('node1', 'node2', 'name1', 'name2', 'copy', 'width', 'bandwidth',
288 | 'hostname', 'itemin', 'itemout'))
289 | ])
290 |
291 | for cfg_sect in cfg_templ:
292 |
293 | if cfg_sect == 'node-':
294 | for node in sorted([node for node in cfg.keys() if cfg_sect in node]):
295 | cfg_order[node] = OrderedDict()
296 | for cfg_opt in cfg_templ[cfg_sect]:
297 | if cfg_opt == 'icon' and cfg_opt not in cfg[node]:
298 | continue
299 | if cfg_opt == 'label' and cfg_opt not in cfg[node]:
300 | continue
301 | cfg_order[node][cfg_opt] = cfg[node][cfg_opt]
302 | continue
303 |
304 | if cfg_sect == 'link-':
305 | for link in sorted([link for link in cfg.keys() if cfg_sect in link]):
306 | cfg_order[link] = OrderedDict()
307 | for cfg_opt in cfg_templ[cfg_sect]:
308 | if cfg_opt == 'copy' and cfg_opt not in cfg[link]:
309 | continue
310 | if cfg_opt == 'width' and cfg_opt not in cfg[link]:
311 | continue
312 | if cfg_opt == 'bandwidth' and cfg_opt not in cfg[link]:
313 | continue
314 | cfg_order[link][cfg_opt] = cfg[link][cfg_opt]
315 | continue
316 |
317 | cfg_order[cfg_sect] = OrderedDict()
318 | if cfg_sect == 'palette':
319 | cfg_order[cfg_sect] = cfg[cfg_sect]
320 | continue
321 |
322 | for cfg_opt in cfg_templ[cfg_sect]:
323 | if cfg_sect == 'map' and cfg_opt == 'bgcolor' and cfg_opt not in cfg[cfg_sect]:
324 | continue
325 | cfg_order[cfg_sect][cfg_opt] = cfg[cfg_sect][cfg_opt]
326 | return cfg_order
327 |
328 | def save(self, path: str):
329 | cfg = self._dict_to_orderdict(self.map_config)
330 | with open(path + '/' + self.map_data['name'] + '.yaml', 'w') as cfg_file:
331 | try:
332 | yaml3ed.dump(cfg, cfg_file, explicit_start=True, explicit_end=True,
333 | default_flow_style=False, allow_unicode=True, version=(1, 2))
334 | except yaml3ed.YAMLError as exc:
335 | print(exc)
336 |
337 | def check_map(self, old_cfg_path: str):
338 | old_cfg_path_fn = old_cfg_path + '/' + self.map_data['name'] + '.yaml'
339 | exist = os.path.exists(old_cfg_path_fn)
340 | if exist:
341 | self._compare(old_cfg_path_fn)
342 |
343 | def _compare(self, old_cfg_path_file: str):
344 |
345 | self.cfg_loader_obj = ConfigLoader(old_cfg_path_file)
346 | config_old = self.cfg_loader_obj.cfg_dict
347 |
348 | for section in [sect for sect in self.template.keys()
349 | if sect != 'zabbix' and sect != 'map' and sect != 'node-' and sect != 'link-']:
350 |
351 | if section == 'palette':
352 | self.map_config[section] = config_old[section]
353 | continue
354 |
355 | for option in self.template[section]:
356 | self.map_config[section][option] = config_old[section][option]
357 |
358 | for section in self.map_config:
359 | if 'node-' in section:
360 | if config_old.get(section):
361 | if config_old[section].get('label'):
362 | self.map_config[section]['label'] = config_old[section]['label']
363 | if config_old[section].get('icon'):
364 | self.map_config[section]['icon'] = config_old[section]['icon']
365 | if 'link-' in section:
366 | if config_old.get(section):
367 | self.map_config[section]['hostname'] = config_old[section]['hostname']
368 | self.map_config[section]['itemin'] = config_old[section]['itemin']
369 | self.map_config[section]['itemout'] = config_old[section]['itemout']
370 | if config_old[section].get('width'):
371 | self.map_config[section]['width'] = config_old[section]['width']
372 | if config_old[section].get('bandwidth'):
373 | self.map_config[section]['bandwidth'] = config_old[section]['bandwidth']
374 |
375 | for section in [link for link in config_old.keys() if 'link-' in link]:
376 |
377 | if config_old[section].get('copy'):
378 | new_section = 'link-' + self.random_label()
379 | node1_sect = config_old[section]['node1']
380 | node2_sect = config_old[section]['node2']
381 | node1_new_sect = 'node-' + self.random_label()
382 | node2_new_sect = 'node-' + self.random_label()
383 |
384 | self.map_config.update({new_section: dict()})
385 | for option in config_old[section]:
386 | if 'node1' in option:
387 | self.map_config[new_section][option] = node1_new_sect
388 | elif 'node2' in option:
389 | self.map_config[new_section][option] = node2_new_sect
390 | else:
391 | self.map_config[new_section][option] = config_old[section][option]
392 |
393 | self.map_config.update({node1_new_sect: dict()})
394 | self.map_config.update({node2_new_sect: dict()})
395 | for option in config_old[node1_sect]:
396 | self.map_config[node1_new_sect][option] = config_old[node1_sect][option]
397 | for option in config_old[node2_sect]:
398 | self.map_config[node2_new_sect][option] = config_old[node2_sect][option]
399 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------