def cleanupLeases(): db = DummySession() try: db = SessionLoader() Leases = db.query(dSIPLeases).filter( datetime.now() >= dSIPLeases.expiration).all() for Lease in Leases: # Remove the entry in the Subscribers table db.query(Subscribers).filter(Subscribers.id == Lease.sid).delete( synchronize_session=False) # Remove the entry in the Gateway table db.query(Gateways).filter(Gateways.gwid == Lease.gwid).delete( synchronize_session=False) # Remove the entry in the Lease table db.delete(Lease) db.commit() except Exception as ex: debugException(ex) db.rollback() db.flush() finally: db.close()
def createValidEngine(uri_list): """ Create DB engine if connection is valid Attempts each uri in the list until a valid connection is made :param uri_list: list of connection uri's :return: DB engine object :raise: SQLAlchemyError if all connections fail """ errors = [] for conn_uri in uri_list: try: db_engine = create_engine(conn_uri, echo=True, pool_recycle=10, isolation_level="READ UNCOMMITTED", connect_args={"connect_timeout": 5}) # test connection _ = db_engine.connect() # conn good return it return db_engine except Exception as ex: errors.append(ex) # we failed to return good connection raise exceptions if settings.DEBUG: for ex in errors: debugException(ex, log_ex=False, print_ex=True, showstack=False) try: raise sql_exceptions.SQLAlchemyError(errors) except: raise Exception(errors)
def createValidEngine(uri_list): """ Create DB engine if connection is valid Attempts each uri in the list until a valid connection is made This method uses a singleton pattern and returns db_engine if created :param uri_list: list of connection uri's :return: DB engine object :raise: SQLAlchemyError if all connections fail """ if 'db_engine' in globals(): return globals()['db_engine'] errors = [] for conn_uri in uri_list: try: db_engine = create_engine(conn_uri, echo=True, pool_recycle=300, pool_size=10, isolation_level="READ UNCOMMITTED", connect_args={"connect_timeout": 5}) # test connection _ = db_engine.connect() # conn good return it return db_engine except Exception as ex: errors.append(ex) # we failed to return good connection raise exceptions if settings.DEBUG: for ex in errors: debugException(ex) try: raise sql_exceptions.SQLAlchemyError(errors) except: raise Exception(errors)
def sendCdrReport(gwgroupid): db = DummySession() try: db = SessionLoader() now = datetime.now() cdr_info = db.query(dSIPCDRInfo).filter( dSIPCDRInfo.gwgroupid == gwgroupid).first() generateCDRS(gwgroupid=gwgroupid, type='csv', email=True, dtfilter=cdr_info.last_sent) cdr_info.last_sent = now db.commit() except Exception as ex: debugException(ex) db.rollback() db.flush() finally: db.close()
import settings from shared import IO, debugException, hostToIP if settings.KAM_DB_TYPE == "mysql": try: import MySQLdb as db_driver except ImportError: try: import _mysql as db_driver except ImportError: try: import pymysql as db_driver except ImportError: raise except Exception as ex: if settings.DEBUG: debugException(ex, log_ex=False, print_ex=True, showstack=False) raise class Gateways(object): """ Schema for dr_gateways table\n Documentation: `dr_gateways table <https://kamailio.org/docs/db-tables/kamailio-db-5.1.x.html#gen-db-dr-gateways>`_ """ def __init__(self, name, ip_addr, strip, prefix, type, gwgroup=None): self.description = "name:" + name if gwgroup is not None: self.description += ",gwgroup:" + gwgroup self.address = ip_addr self.strip = strip
from util.security import AES_CTR if settings.KAM_DB_TYPE == "mysql": try: import MySQLdb as db_driver except ImportError: try: import _mysql as db_driver except ImportError: try: import pymysql as db_driver except ImportError: raise except Exception as ex: if settings.DEBUG: debugException(ex) raise class Gateways(object): """ Schema for dr_gateways table\n Documentation: `dr_gateways table <https://kamailio.org/docs/db-tables/kamailio-db-5.1.x.html#gen-db-dr-gateways>`_\n Allowed address types: SIP URI, IP address or DNS domain name\n The address field can be a full SIP URI, partial URI, or only host; where host portion is an IP or FQDN """ def __init__(self, name, address, strip, prefix,
def sendEmail(recipients, text_body, html_body=None, subject=settings.MAIL_DEFAULT_SUBJECT, sender=settings.MAIL_DEFAULT_SENDER, data=None, attachments=[]): """ Send an Email asynchronously to recipients :param recipients: list :param text_body: str :param html_body: str :param subject: str :param sender: str :param data: dict :param attachments: list :return: None """ try: if data is not None: text_body += "\r\n\n" for key, value in data.items(): text_body += "{}: {}\n".format(key, value) text_body += "\n" # print("Creating email") msg_root = MIMEMultipart('alternative') msg_root['From'] = sender msg_root['To'] = ", ".join(recipients) msg_root['Subject'] = subject msg_root.preamble = "|-------------------MULTIPART_BOUNDARY-------------------|\n" # print("Adding text body to email") msg_root.attach(MIMEText(text_body, 'plain')) if html_body is not None and html_body != "": # print("Adding html body to email") msg_root.attach(MIMEText(html_body, 'html')) if len(attachments) > 0: # print("Adding attachments to email") for file in attachments: with open(file, 'rb') as fp: msg_attachments = MIMEBase('application', "octet-stream") msg_attachments.set_payload(fp.read()) encoders.encode_base64(msg_attachments) msg_attachments.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file)) msg_root.attach(msg_attachments) # check environ vars if in debug mode if settings.DEBUG: settings.MAIL_USERNAME = os.getenv('MAIL_USERNAME', settings.MAIL_USERNAME) settings.MAIL_PASSWORD = os.getenv('MAIL_PASSWORD', settings.MAIL_PASSWORD) # need to decrypt password if isinstance(settings.MAIL_PASSWORD, bytes): mailpass = AES_CTR.decrypt(settings.MAIL_PASSWORD).decode('utf-8') else: mailpass = settings.MAIL_PASSWORD # print("sending email") with smtplib.SMTP(settings.MAIL_SERVER, settings.MAIL_PORT) as server: server.connect(settings.MAIL_SERVER, settings.MAIL_PORT) server.ehlo() if settings.MAIL_USE_TLS: server.starttls() server.ehlo() server.login(settings.MAIL_USERNAME, mailpass) msg_root_str = msg_root.as_string() server.sendmail(sender, recipients, msg_root_str) server.quit() except Exception as ex: debugException(ex)