move logging to ztdnslib.py
[0tDNS.git] / src / ztdnslib.py
blobdc5460233c568fa4bee3f955c9f2f533dd3b081a
1 import yaml
2 import psycopg2
3 import os
4 import fcntl
6 db_config_path = '/etc/0tdns/db_connection_config.yml'
7 logfile = '/var/log/0tdns.log'
9 def get_ztdns_config():
10 return yaml.safe_load(open(db_config_path, 'r'))
12 def start_db_connection(config):
13 connection = psycopg2.connect(user=config['user'], password=config['password'],
14 host=config['host'], port=config['port'],
15 database=config['database'])
16 # we might later decide that each user of start_db_connection()
17 # should set it themselves - but for now, set it here
18 connection.autocommit = True
19 return connection
21 # we'll use it for setting SNAT
22 # https://stackoverflow.com/questions/166506/finding-local-ip-addresses-using-pythons-stdlib
23 def get_default_host_address(remote_address):
24 import socket
25 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
26 s.connect((remote_address, 80))
27 hostaddr = s.getsockname()[0]
28 s.close()
29 return hostaddr
31 def log(msg):
32 msg = bytearray(msg + '\n', "UTF-8")
33 fd = os.open(logfile, os.O_APPEND | os.O_WRONLY | os.O_CREAT)
34 try:
35 fcntl.flock(fd, fcntl.LOCK_EX)
36 os.write(fd, msg)
37 fcntl.flock(fd, fcntl.LOCK_UN)
38 finally:
39 os.close(fd)