| 1 |
from astconfigparser import MultiOrderedConfigParser |
| 2 |
|
| 3 |
try: |
| 4 |
import pymysql as MySQLdb |
| 5 |
MySQLdb.install_as_MySQLdb() |
| 6 |
except ImportError: |
| 7 |
|
| 8 |
|
| 9 |
import MySQLdb |
| 10 |
|
| 11 |
import traceback |
| 12 |
|
| 13 |
class SqlConfigParser(MultiOrderedConfigParser): |
| 14 |
|
| 15 |
_tablename = "sippeers" |
| 16 |
|
| 17 |
def __init__(self,tablename="sippeers"): |
| 18 |
self._tablename=tablename |
| 19 |
MultiOrderedConfigParser.__init__(self) |
| 20 |
|
| 21 |
def connect(self, user, password, host, port, database): |
| 22 |
self.cnx = MySQLdb.connect(user=user,passwd=password,host=host,port=int(port),db=database) |
| 23 |
|
| 24 |
def read(self, filename, sect=None): |
| 25 |
MultiOrderedConfigParser.read(self, filename, sect) |
| 26 |
|
| 27 |
cursor = self.cnx.cursor(cursorclass=MySQLdb.cursors.DictCursor) |
| 28 |
cursor.execute("SELECT * from `" + MySQLdb.escape_string(self._tablename) + "`") |
| 29 |
rows = cursor.fetchall() |
| 30 |
|
| 31 |
for row in rows: |
| 32 |
sect = self.add_section(row['name']) |
| 33 |
for key in row: |
| 34 |
if (row[key] != None): |
| 35 |
for elem in str(row[key]).split(";"): |
| 36 |
sect[key] = elem |
| 37 |
|
| 38 |
|
| 39 |
def write_dicts(self, config_file, mdicts): |
| 40 |
"""Write the contents of the mdicts to the specified config file""" |
| 41 |
for section, sect_list in mdicts.iteritems(): |
| 42 |
|
| 43 |
for sect in sect_list: |
| 44 |
sql = "INSERT INTO " |
| 45 |
if (sect.get('type')[0] == "endpoint"): |
| 46 |
sql += "ps_endpoints " |
| 47 |
elif (sect.get('type')[0] == "aor" and section != "sbc"): |
| 48 |
sql += "ps_aors " |
| 49 |
elif (sect.get('type')[0] == "identify"): |
| 50 |
sql += "ps_endpoint_id_ips" |
| 51 |
else: |
| 52 |
continue |
| 53 |
|
| 54 |
sql += " SET `id` = " + "\"" + MySQLdb.escape_string(section) + "\"" |
| 55 |
for key, val_list in sect.iteritems(): |
| 56 |
if key == "type": |
| 57 |
continue |
| 58 |
|
| 59 |
|
| 60 |
key_val = " `" + key + "`" |
| 61 |
key_val += " = " + "\"" + MySQLdb.escape_string(";".join(val_list)) + "\"" |
| 62 |
sql += "," |
| 63 |
sql += key_val |
| 64 |
|
| 65 |
config_file.write("%s;\n" % (sql)) |
| 66 |
|
| 67 |
def write(self, config_file): |
| 68 |
"""Write configuration information out to a file""" |
| 69 |
try: |
| 70 |
self.write_dicts(config_file, self._sections) |
| 71 |
except: |
| 72 |
print("Could not open file " + config_file + " for writing") |
| 73 |
traceback.print_exc() |