read_conf.py
3.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
from opensipkd.tcp.connection import join_ip_port
try:
from configparser import (
ConfigParser,
NoOptionError,
)
except ImportError:
from ConfigParser import (
ConfigParser,
NoOptionError,
)
listen_ports = []
ip_conf = {}
name_conf = {}
allowed_ips = []
web = {}
def get_conf(ip, port):
key = join_ip_port(ip, port)
return ip_conf[key]
def get_web_port():
return 'port' in web and web['port']
def get_str(conf, section, option, default):
try:
return conf.get(section, option)
except NoOptionError:
return default
def get_boolean(conf, section, option, default):
try:
return conf.getboolean(section, option)
except NoOptionError:
return default
def get_int(conf, section, option, default):
try:
return conf.getint(section, option)
except NoOptionError:
return default
MSG_DUPLICATE = 'IP {ip} port {port} ganda. Perbaiki konfigurasi.'
def validate_ip_port(ip_port):
if ip_port in ip_conf:
cfg = ip_conf[ip_port]
msg = MSG_DUPLICATE.format(ip=cfg['ip'], port=cfg['port'])
raise Exception(msg)
def get_module_object(name):
module_obj = __import__(name)
sub_obj = None
for sub in name.split('.')[1:]:
if sub_obj:
sub_obj = getattr(sub_obj, sub)
else:
sub_obj = getattr(module_obj, sub)
return sub_obj
def get_streamer_class(name):
obj = get_module_object('opensipkd.streamer.' + name)
return obj.Streamer
def read_conf(conf_file):
conf = ConfigParser()
conf.read(conf_file)
for section in conf.sections():
if section == 'web':
web['port'] = conf.getint(section, 'port')
continue
if section.find('host_') < 0:
continue
try:
active = conf.getboolean(section, 'active')
except NoOptionError:
active = True
if not active:
continue
ip = conf.get(section, 'ip')
port = conf.getint(section, 'port')
ip_port = join_ip_port(ip, port)
validate_ip_port(ip_port)
cfg = dict()
cfg['ip'] = ip
cfg['port'] = port
cfg['name'] = name = section.split('_')[1]
cfg['streamer'] = get_str(conf, section, 'streamer', 'none')
cfg['streamer_cls'] = get_streamer_class(cfg['streamer'])
cfg['module'] = get_str(conf, section, 'module', 'opensipkd.iso8583.network')
cfg['module_obj'] = get_module_object(cfg['module'])
cfg['ip'] = conf.get(section, 'ip')
cfg['port'] = conf.getint(section, 'port')
cfg['listen'] = get_boolean(conf, section, 'listen', True)
cfg['echo'] = get_boolean(conf, section, 'echo', not cfg['listen'])
cfg['timeout'] = get_int(conf, section, 'timeout', 60)
if cfg['listen']:
if port not in listen_ports:
listen_ports.append(port)
if ip not in allowed_ips:
allowed_ips.append(ip)
ip_conf[ip_port] = name_conf[name] = dict(cfg)