[Asterisk-code-review] contrib/script/sip to pjsip: add support for realtime (asterisk[13])

Jenkins2 asteriskteam at digium.com
Fri Feb 16 10:16:41 CST 2018


Jenkins2 has submitted this change and it was merged. ( https://gerrit.asterisk.org/6813 )

Change subject: contrib/script/sip_to_pjsip: add support for realtime
......................................................................

contrib/script/sip_to_pjsip: add support for realtime

Add a new script that can read from legacy realtime peers & generate
an sql file for populating pjsip endpoints, identify, and aor records.

ASTERISK-27348 #close

Change-Id: Idd3d7968a3c9c3ee7936d21acbdaf001b429bf65
---
M contrib/scripts/sip_to_pjsip/sip_to_pjsip.py
A contrib/scripts/sip_to_pjsip/sip_to_pjsql.py
A contrib/scripts/sip_to_pjsip/sqlconfigparser.py
3 files changed, 151 insertions(+), 1 deletion(-)

Approvals:
  Joshua Colp: Looks good to me, but someone else must approve
  Matthew Fredrickson: Looks good to me, approved
  Jenkins2: Approved for Submit



diff --git a/contrib/scripts/sip_to_pjsip/sip_to_pjsip.py b/contrib/scripts/sip_to_pjsip/sip_to_pjsip.py
index eb3aab3..2fb5fc5 100755
--- a/contrib/scripts/sip_to_pjsip/sip_to_pjsip.py
+++ b/contrib/scripts/sip_to_pjsip/sip_to_pjsip.py
@@ -1163,7 +1163,7 @@
     map specific sections from sip.conf into it.
     Returns the new pjsip.conf object once completed
     """
-    pjsip = astconfigparser.MultiOrderedConfigParser()
+    pjsip = sip.__class__()
     non_mappings[filename] = astdicts.MultiOrderedDict()
     nmapped = non_mapped(non_mappings[filename])
     if not include:
diff --git a/contrib/scripts/sip_to_pjsip/sip_to_pjsql.py b/contrib/scripts/sip_to_pjsip/sip_to_pjsql.py
new file mode 100755
index 0000000..d93bca5
--- /dev/null
+++ b/contrib/scripts/sip_to_pjsip/sip_to_pjsql.py
@@ -0,0 +1,81 @@
+#!/usr/bin/python
+
+from sip_to_pjsip import cli_options
+from sip_to_pjsip import convert
+import sip_to_pjsip
+import optparse
+
+
+import sqlconfigparser
+
+
+def write_pjsip(filename, pjsip, non_mappings):
+    """
+    Write pjsip.sql file to disk
+    """
+    try:
+        with open(filename, 'wt') as fp:
+            pjsip.write(fp)
+
+    except IOError:
+        print "Could not open file ", filename, " for writing"
+
+def cli_options():
+    """
+    Parse command line options and apply them. If invalid input is given,
+    print usage information
+
+    """
+    global user
+    global password
+    global host
+    global port
+    global database
+    global table
+
+    usage = "usage: %prog [options] [input-file [output-file]]\n\n" \
+        "Converts the chan_sip configuration input-file to mysql output-file.\n" \
+        "The input-file defaults to 'sip.conf'.\n" \
+        "The output-file defaults to 'pjsip.sql'."
+    parser = optparse.OptionParser(usage=usage)
+    parser.add_option('-u', '--user', dest='user', default="root",
+                      help='mysql username')
+    parser.add_option('-p', '--password', dest='password', default="root",
+                      help='mysql password')
+    parser.add_option('-H', '--host', dest='host', default="127.0.0.1",
+                      help='mysql host ip')
+    parser.add_option('-P', '--port', dest='port', default="3306",
+                      help='mysql port number')
+    parser.add_option('-D', '--database', dest='database', default="asterisk",
+                      help='mysql port number')
+    parser.add_option('-t', '--table', dest='table', default="sippeers",
+                      help='name of sip realtime peers table')
+
+    options, args = parser.parse_args()
+
+    user = options.user
+    password = options.password
+    host = options.host
+    port = options.port
+    database = options.database
+    table = options.table
+
+    sip_filename = args[0] if len(args) else 'sip.conf'
+    pjsip_filename = args[1] if len(args) == 2 else 'pjsip.sql'
+
+    return sip_filename, pjsip_filename
+
+if __name__ == "__main__":
+    sip_filename, pjsip_filename = cli_options()
+    sip = sqlconfigparser.SqlConfigParser(table)
+    sip_to_pjsip.sip = sip
+    sip.connect(user,password,host,port,database)
+    print 'Please, report any issue at:'
+    print '    https://issues.asterisk.org/'
+    print 'Reading', sip_filename
+    sip.read(sip_filename)
+    print 'Converting to PJSIP realtime sql...'
+    pjsip, non_mappings = convert(sip, pjsip_filename, dict(), False)
+    print 'Writing', pjsip_filename
+    write_pjsip(pjsip_filename, pjsip, non_mappings)
+
diff --git a/contrib/scripts/sip_to_pjsip/sqlconfigparser.py b/contrib/scripts/sip_to_pjsip/sqlconfigparser.py
new file mode 100644
index 0000000..e87224f
--- /dev/null
+++ b/contrib/scripts/sip_to_pjsip/sqlconfigparser.py
@@ -0,0 +1,69 @@
+from astconfigparser import MultiOrderedConfigParser
+
+import MySQLdb
+import traceback
+
+class SqlConfigParser(MultiOrderedConfigParser):
+
+    _tablename = "sippeers"
+
+    def __init__(self,tablename="sippeers"):
+        self._tablename=tablename
+        MultiOrderedConfigParser.__init__(self)
+
+    def connect(self, user, password, host, port, database):
+        self.cnx = MySQLdb.connect(user=user,passwd=password,host=host,port=int(port),db=database)
+
+    def read(self, filename, sect=None):
+        MultiOrderedConfigParser.read(self, filename, sect)
+        # cursor = self.cnx.cursor(dictionary=True)
+        cursor = self.cnx.cursor(cursorclass=MySQLdb.cursors.DictCursor)
+        cursor.execute("SELECT * from `" + MySQLdb.escape_string(self._tablename) + "`")
+        rows = cursor.fetchall()
+
+        for row in rows:
+            sect = self.add_section(row['name'])
+            for key in row:
+                if (row[key] != None):
+                    for elem in str(row[key]).split(";"):
+                        sect[key] = elem
+                    #sect[key] = str(row[key]).split(";")
+
+    def write_dicts(self, config_file, mdicts):
+        """Write the contents of the mdicts to the specified config file"""
+        for section, sect_list in mdicts.iteritems():
+            # every section contains a list of dictionaries
+            for sect in sect_list:
+                sql = "INSERT INTO "
+                if (sect.get('type')[0] == "endpoint"):
+                    sql += "ps_endpoints "
+                elif (sect.get('type')[0] == "aor" and section != "sbc"):
+                    sql += "ps_aors "
+                elif (sect.get('type')[0] == "identify"):
+                    sql += "ps_endpoint_id_ips"
+                else:
+                    continue
+
+                sql += " SET `id` = " + "\"" + MySQLdb.escape_string(section) + "\""
+                for key, val_list in sect.iteritems():
+                    if key == "type":
+                        continue
+                    # every value is also a list
+
+                    key_val = " `" + key + "`"
+                    key_val += " = " + "\"" + MySQLdb.escape_string(";".join(val_list)) + "\""
+                    sql += ","
+                    sql += key_val
+
+                config_file.write("%s;\n" % (sql))
+
+    def write(self, config_file):
+        """Write configuration information out to a file"""
+        try:
+            self.write_dicts(config_file, self._sections)
+        except Exception,e:
+                print "Could not open file ", config_file, " for writing"
+                traceback.print_exc()
+
+
+

-- 
To view, visit https://gerrit.asterisk.org/6813
To unsubscribe, visit https://gerrit.asterisk.org/settings

Gerrit-Project: asterisk
Gerrit-Branch: 13
Gerrit-MessageType: merged
Gerrit-Change-Id: Idd3d7968a3c9c3ee7936d21acbdaf001b429bf65
Gerrit-Change-Number: 6813
Gerrit-PatchSet: 4
Gerrit-Owner: Torrey Searle <tsearle at gmail.com>
Gerrit-Reviewer: Jenkins2
Gerrit-Reviewer: Joshua Colp <jcolp at digium.com>
Gerrit-Reviewer: Matthew Fredrickson <creslin at digium.com>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.digium.com/pipermail/asterisk-code-review/attachments/20180216/624f4d94/attachment.html>


More information about the asterisk-code-review mailing list