Example #1
0
    def test_getconfig(self):
        values = config.getconfig(self.mockinifile)
        self.assertEquals(2, len(values.keys()))
        self.assert_(values.has_key('section1'))
        self.assert_(values.has_key('section2'))

        self.assertEquals(values['section1']['foo1'], 'bar1')
        self.assertEquals(values['section1']['foo2'], 'bar2')
        self.assertEquals(values['section2']['foo4'], 'bar4')
        self.assertFalse(values['section2'].has_key('foo3'))
Example #2
0
def test_getconfig(mockinifile):
    values = config.getconfig(mockinifile)
    assert 2 == len(values.keys())
    assert 'section1' in values
    assert 'section2' in values

    assert values['section1']['foo1'] == 'bar1'
    assert values['section1']['foo2'] == 'bar2'
    assert values['section2']['foo4'] == 'bar4'
    assert 'foo3' not in values['section2']
Example #3
0
    def test_getconfig(self):
        values = config.getconfig(self.mockinifile)
        self.assertEquals(2, len(values.keys()))
        self.assert_('section1' in values)
        self.assert_('section2' in values)

        self.assertEquals(values['section1']['foo1'], 'bar1')
        self.assertEquals(values['section1']['foo2'], 'bar2')
        self.assertEquals(values['section2']['foo4'], 'bar4')
        self.assertFalse('foo3' in values['section2'])
Example #4
0
"""Django configuration wrapper around the NAV configuration files"""

from nav.config import read_flat_config, getconfig
from nav.db import get_connection_parameters
import nav.buildconf
import nav.path
import sys
import os

try:
    nav_config = read_flat_config('nav.conf')
except IOError:
    nav_config = {}

try:
    webfront_config = getconfig('webfront/webfront.conf',
                                configfolder=nav.path.sysconfdir)
except IOError:
    webfront_config = {}

DEBUG = nav_config.get('DJANGO_DEBUG',
                       'False').upper() in ('TRUE', 'YES', 'ON')
TEMPLATE_DEBUG = DEBUG

# Admins
ADMINS = (('NAV Administrator', nav_config.get('ADMIN_MAIL',
                                               'root@localhost')), )
MANAGERS = ADMINS

# Database / ORM configuration
try:
    _host, _port, _name, _user, _password = get_connection_parameters('django')
Example #5
0
def main():
    args = parse_args()

    # Set config defaults
    global defaults
    defaults = {
        'username': buildconf.nav_user,
        'delay': '30',
        'delayfactor': '1.5',
        'maxdelay': '3600',
        'retrylimit': '5',
        'retrylimitaction': 'ignore',
        'exit_on_permanent_error': 'yes',
        'autocancel': '0',
        'mailwarnlevel': 'ERROR',
        'mailserver': 'localhost',
        'mailaddr': nav.config.read_flat_config('nav.conf')['ADMIN_MAIL'],
        'fromaddr': nav.config.read_flat_config('nav.conf')[
            'DEFAULT_FROM_EMAIL'],
    }

    # Read config file
    global config
    config = getconfig(configfile, defaults)

    # Set variables
    global delay, failed
    failed = 0
    delay = int(config['main']['delay'])
    maxdelay = int(config['main']['maxdelay'])
    delayfactor = float(config['main']['delayfactor'])
    retrylimit = int(config['main']['retrylimit'])
    retrylimitaction = config['main']['retrylimitaction'].strip()
    retryvars = {
        'maxdelay': maxdelay,
        'delayfactor': delayfactor,
        'retrylimit': retrylimit,
        'retrylimitaction': retrylimitaction
    }

    username = config['main']['username']
    autocancel = config['main']['autocancel']
    mailwarnlevel = logging.getLevelName(config['main']['mailwarnlevel'])
    mailserver = config['main']['mailserver']
    mailaddr = config['main']['mailaddr']
    fromaddr = config['main']['fromaddr']

    # Drop privileges if running as root
    if os.geteuid() == 0:
        try:
            nav.daemon.switchuser(username)
        except nav.daemon.DaemonError as error:
            print(error, file=sys.stderr)
            sys.exit(
                "Run as root or %s. Try `%s --help' for more information." % (
                 username, sys.argv[0]))

    # Initialize logging
    global logger
    logger = logging.getLogger('nav.smsd')
    nav.logs.init_stderr_logging()
    if not loginitsmtp(mailwarnlevel, mailaddr, fromaddr, mailserver):
        sys.exit('Failed to init SMTP logging.')

    # First log message
    logger.info('Starting smsd.')

    # Set custom loop delay
    if args.delay:
        setdelay(args.delay)

    # Ignore unsent messages
    if args.cancel:
        queue = nav.smsd.navdbqueue.NAVDBQueue()
        ignored_count = queue.cancel()
        logger.info("All %d unsent messages ignored.", ignored_count)
        sys.exit(0)

    if args.delayfactor:
        retryvars['delayfactor'] = args.delayfactor
    if args.maxdelay:
        retryvars['maxdelay'] = args.maxdelay
    if args.limit:
        retryvars['retrylimit'] = args.limit
    if args.action:
        retryvars['retrylimitaction'] = args.action

    # Let the dispatcherhandler take care of our dispatchers
    try:
        dh = nav.smsd.dispatcher.DispatcherHandler(config)
    except PermanentDispatcherError as error:
        logger.critical("Dispatcher configuration failed. Exiting. (%s)", error)
        sys.exit(1)

    # Send test message (in other words: test the dispatcher)
    if args.test or args.TEST:
        text = args.message or "This is a test message from NAV smsd."

        if args.test:
            msg = [(0, text, 0)]
            try:
                (sms, sent, ignored, smsid) = dh.sendsms(args.test, msg)
            except DispatcherError as error:
                logger.critical("Sending failed. Exiting. (%s)", error)
                sys.exit(1)

            logger.info("SMS sent. Dispatcher returned reference %d.", smsid)

        elif args.TEST and args.uid:
            queue = nav.smsd.navdbqueue.NAVDBQueue()
            rowsinserted = queue.inserttestmsgs(args.uid, args.TEST, text)
            if rowsinserted:
                logger.info("SMS put in queue. %d row(s) inserted.",
                            rowsinserted)
            else:
                logger.info("SMS not put in queue.")

        sys.exit(0)

    # Check if already running
    try:
        nav.daemon.justme(pidfile)
    except nav.daemon.DaemonError as error:
        logger.error(error)
        sys.exit(1)

    # Daemonize
    if not args.foreground:
        try:
            nav.daemon.daemonize(pidfile, stderr=open(logfile, "a"))
        except nav.daemon.DaemonError as error:
            logger.error(error)
            sys.exit(1)

        logger.info('smsd now running in daemon mode')
        # Reopen log files on SIGHUP
        logger.debug('Adding signal handler for reopening log files on SIGHUP.')
        signal.signal(signal.SIGHUP, signalhandler)
    else:
        nav.daemon.writepidfile(pidfile)

    # Exit on SIGTERM/SIGINT
    signal.signal(signal.SIGTERM, signalhandler)
    signal.signal(signal.SIGINT, signalhandler)

    # Initialize queue
    # NOTE: If we're initalizing a queue with a DB connection before
    # daemonizing we've experienced that the daemon dies silently upon trying
    # to use the DB connection after becoming a daemon
    queue = nav.smsd.navdbqueue.NAVDBQueue()

    # Automatically cancel unsent messages older than a given interval
    if autocancel != '0':
        ignored_count = queue.cancel(autocancel)
        logger.info("%d unsent messages older than '%s' autocanceled.",
                    ignored_count, autocancel)

    # Loop forever
    while True:
        logger.debug("Starting loop.")

        # Queue: Get users with unsent messages
        users = queue.getusers('N')

        logger.info("Found %d user(s) with unsent messages.", len(users))

        # Loop over cell numbers
        for user in users:
            # Queue: Get unsent messages for a user ordered by severity desc
            msgs = queue.getusermsgs(user, 'N')
            logger.info("Found %d unsent message(s) for %s.", len(msgs), user)

            # Dispatcher: Format and send SMS
            try:
                (sms, sent, ignored, smsid) = dh.sendsms(user, msgs)
            except PermanentDispatcherError as error:
                logger.critical("Sending failed permanently. Exiting. (%s)",
                                error)
                sys.exit(1)
            except DispatcherError as error:
                try:
                    # Dispatching failed. Backing off.
                    backoff(delay, error, retryvars)

                    break  # End this run
                except:
                    logger.exception("")
                    raise
            except Exception as error:
                logger.exception("Unknown exception: %s", error)

            logger.info("SMS sent to %s.", user)

            if failed:
                resetdelay()
                failed = 0
                logger.debug("Resetting delay and number of failed runs.")

            for msgid in sent:
                queue.setsentstatus(msgid, 'Y', smsid)
            for msgid in ignored:
                queue.setsentstatus(msgid, 'I', smsid)
            logger.info("%d messages were sent and %d ignored.",
                        len(sent), len(ignored))

        # Sleep a bit before the next run
        logger.debug("Sleeping for %d seconds.", delay)
        time.sleep(delay)
Example #6
0
        'delay': '30',
        'delayfactor': '1.5',
        'maxdelay': '3600',
        'retrylimit': '5',
        'retrylimitaction': 'ignore',
        'exit_on_permanent_error': 'yes',
        'autocancel': '0',
        'loglevel': 'INFO',
        'mailwarnlevel': 'ERROR',
        'mailserver': 'localhost',
        'mailaddr': nav.config.read_flat_config('nav.conf')['ADMIN_MAIL']
    }

    # Read config file
    global config
    config = getconfig(configfile, defaults)

    # Set variables
    global delay, failed
    failed = 0
    delay = int(config['main']['delay'])
    maxdelay = int(config['main']['maxdelay'])
    delayfactor = float(config['main']['delayfactor'])
    retrylimit = int(config['main']['retrylimit'])
    retrylimitaction = config['main']['retrylimitaction'].strip()
    retryvars = {
        'maxdelay': maxdelay,
        'delayfactor': delayfactor,
        'retrylimit': retrylimit,
        'retrylimitaction': retrylimitaction
    }
Example #7
0
import os
import sys
import copy

import django
from django.utils.log import DEFAULT_LOGGING

from nav.config import (NAV_CONFIG, getconfig, find_config_dir)
from nav.db import get_connection_parameters
import nav.buildconf

ALLOWED_HOSTS = ['*']

_config_dir = find_config_dir()
try:
    _webfront_config = getconfig('webfront/webfront.conf')
except (IOError, OSError):
    _webfront_config = {}

DEBUG = NAV_CONFIG.get('DJANGO_DEBUG',
                       'False').upper() in ('TRUE', 'YES', 'ON')

# Copy Django's default logging config, but modify it to enable HTML e-mail
# part for improved debugging:
LOGGING = copy.deepcopy(DEFAULT_LOGGING)
_handlers = LOGGING.get('handlers', {})
_mail_admin_handler = _handlers.get('mail_admins', {})
_mail_admin_handler['include_html'] = True

# Admins
ADMINS = (('NAV Administrator', NAV_CONFIG.get('ADMIN_MAIL',
Example #8
0
import django
from django.utils.log import DEFAULT_LOGGING

from nav.config import read_flat_config, getconfig
from nav.db import get_connection_parameters
import nav.buildconf

ALLOWED_HOSTS = ['*']

try:
    nav_config = read_flat_config('nav.conf')
except IOError:
    nav_config = {'SECRET_KEY': 'Very bad default value'}

try:
    webfront_config = getconfig('webfront/webfront.conf',
                                configfolder=nav.buildconf.sysconfdir)
except IOError:
    webfront_config = {}

DEBUG = nav_config.get('DJANGO_DEBUG', 'False').upper() in ('TRUE', 'YES', 'ON')

# Copy Django's default logging config, but modify it to enable HTML e-mail
# part for improved debugging:
LOGGING = copy.deepcopy(DEFAULT_LOGGING)
_handlers = LOGGING.get('handlers', {})
_mail_admin_handler = _handlers.get('mail_admins', {})
_mail_admin_handler['include_html'] = True

# Admins
ADMINS = (
    ('NAV Administrator', nav_config.get('ADMIN_MAIL', 'root@localhost')),
Example #9
0
        'maxdelay': '3600',
        'retrylimit': '5',
        'retrylimitaction': 'ignore',
        'exit_on_permanent_error': 'yes',
        'autocancel': '0',
        'loglevel': 'INFO',
        'mailwarnlevel': 'ERROR',
        'mailserver': 'localhost',
        'mailaddr': nav.config.read_flat_config('nav.conf')['ADMIN_MAIL'],
        'fromaddr':
        nav.config.read_flat_config('nav.conf')['DEFAULT_FROM_EMAIL'],
    }

    # Read config file
    global config
    config = getconfig(configfile, defaults)

    # Set variables
    global delay, failed
    failed = 0
    delay = int(config['main']['delay'])
    maxdelay = int(config['main']['maxdelay'])
    delayfactor = float(config['main']['delayfactor'])
    retrylimit = int(config['main']['retrylimit'])
    retrylimitaction = config['main']['retrylimitaction'].strip()
    retryvars = {
        'maxdelay': maxdelay,
        'delayfactor': delayfactor,
        'retrylimit': retrylimit,
        'retrylimitaction': retrylimitaction
    }
Example #10
0
"""Django configuration wrapper around the NAV configuration files"""

from nav.config import read_flat_config, getconfig
from nav.db import get_connection_parameters
import nav.buildconf
import nav.path
import sys
import os

try:
    nav_config = read_flat_config('nav.conf')
except IOError:
    nav_config = {}

try:
    webfront_config = getconfig('webfront/webfront.conf',
                                configfolder=nav.path.sysconfdir)
except IOError:
    webfront_config = {}

DEBUG = nav_config.get('DJANGO_DEBUG', 'False').upper() in ('TRUE', 'YES', 'ON')
TEMPLATE_DEBUG = DEBUG

# Admins
ADMINS = (
    ('NAV Administrator', nav_config.get('ADMIN_MAIL', 'root@localhost')),
)
MANAGERS = ADMINS

# Database / ORM configuration
try:
    _host, _port, _name, _user, _password = get_connection_parameters('django')