def getDynDnsConfiguration(angelConfig):
    """
    fetches dyndns configuration from angel config, if unconfigured or wrongly configured,
    returns None.
    
    This method serves as a bridge, so we can re-use dyndnsc.getDynDnsClientForConfig().

    @param angelConfig: an AngelConfig instance
    @return: a dictionary with key value pair options
    """
    required_keys = {'protocol': 'dyndns', 'hostname': None }
    other_keys = {'key': None, 'userid': None, 'password': None, 'sleeptime': 60, 'method': 'webcheck'}
    for key in required_keys.keys():
        try:
            option = angelConfig.get('dyndns', key)
        except:
            # if a required key is missing, return None to disable dyndns explicitly
            getLogger().warn("dyndns config incomplete: missing key '%s'" % key)
            return None
        else:
            required_keys[key] = option
    for key in other_keys.keys():
        try:
            option = angelConfig.get('dyndns', key)
        except:
            # if an optional key is missing, ignore and use our default
            pass
        else:
            other_keys[key] = option

    # merge require and optional keys into one dictionary:
    for key in other_keys.keys():
        required_keys[key] = other_keys[key]
    return required_keys
def boot():
    from optparse import OptionParser
    bootInit()
    parser = OptionParser()
    parser.add_option("-d",
                      "--daemon",
                      dest="daemon",
                      help="daemon mode?",
                      default='')
    parser.add_option("-c",
                      "--config",
                      dest="config",
                      help="alternative config file",
                      default=None)
    parser.add_option("-l",
                      "--log",
                      dest="networklogging",
                      help="use network logging?",
                      action="store_true",
                      default=False)
    (options, dummyargs) = parser.parse_args()

    # setup/configure config system
    from angel_app.config.config import getConfig
    angelConfig = getConfig(options.config)
    postConfigInit()
    angelConfig.bootstrapping = False

    appname = "presenter"
    # setup/configure logging
    from angel_app.log import initializeLogging
    loghandlers = []  # default: no handlers, add as needed below
    if len(options.daemon) > 0:
        loghandlers.append('socket')
    else:
        if (options.networklogging):
            loghandlers.append('socket')
        else:
            loghandlers.append('console')
            if angelConfig.getboolean('common', 'desktopnotification'):
                loghandlers.append('growl')
    if 'socket' not in loghandlers:  # if there is no network logging, then log at least to file:
        loghandlers.append('file')
    initializeLogging(appname, loghandlers)

    if angelConfig.get(appname, 'enable') == False:
        from angel_app.log import getLogger
        getLogger().info(
            "%s process is disabled in the configuration, quitting." % appname)
        sys.exit(0)

    if len(options.daemon) > 0:
        from angel_app.proc import daemonizer
        daemonizer.startstop(action=options.daemon,
                             stdout=appname + '.stdout',
                             stderr=appname + '.stderr',
                             pidfile=appname + '.pid')

    return options
 def handleLogRecord(self, record):
     dummylogger = logging.getLogger(record.name)
     # N.B. EVERY record gets logged. This is because Logger.handle
     # is normally called AFTER logger-level filtering. If you want
     # to do filtering, do it at the client end to save wasting
     # cycles and network bandwidth!
     #print record
     #logger.handle(record)
     getLogger(record.name).handle(record)
def getCallLaterDynDnsClientForAngelConfig(angelConfig, callLaterMethod,
                                           logger):
    """
    factory method to instantiate and initialize a complete and working dyndns client for 
    use in the reactor loop.
    
    @param config: a dictionary with configuration pairs
    @return: None or a valid object for use with reactor.callLater()  
    """

    # no need to expose this class globally
    class CallLaterDynDnsClient(object):
        "Minimal class to handle all of the dyndns logic using callbacks started from the reactor loop"

        def __init__(self, dyndnsclient, callLaterMethod, sleeptime):
            """
            @param dyndnsclient: a dyndnsclient object
            @param callLaterMethod: the twisted reactors callLater method
            @param sleeptime: how long to wait until callLater (secs)
            """
            self.sleeptime = sleeptime
            self.client = dyndnsclient
            self.callLaterMethod = callLaterMethod
            # do an initial synchronization:
            self.client.sync()

        def check(self):
            "this will make the dyndns client check its state and also insert an additional callLater timer"
            self.client.check()
            self.callLaterMethod(self.sleeptime, self.check)

    # actual method
    try:
        dyndnsc.logger = logger
        config = getDynDnsConfiguration(angelConfig)
        if config is None:
            return None
        client = dyndnsc.getDynDnsClientForConfig(config)
        if not client is None:
            return CallLaterDynDnsClient(client, callLaterMethod,
                                         config['sleeptime'])
        else:
            return None
    except Exception, e:
        getLogger().error("Initializing dyndns client crashed", exc_info=e)
        return None
 def __init__(self):
     """
     Initialize internal process dictionary, set some defaults and
     get a logger object.
     """
     self.procDict = {}
     self.startendedprocessdelay = 5 # number of seconds to delay the restarting of an ended process
     self.log = getLogger("ExternalProcessManager")
def dance(options):
    from angel_app.config import config
    AngelConfig = config.getConfig()
    providerport = AngelConfig.getint("provider", "listenPort")
    repository = AngelConfig.get("common", "repository")

    from angel_app.resource.local.external import resource
    root = resource.External(repository)

    from twisted.web2 import server
    from twisted.web2 import channel
    from twisted.internet import reactor
    if AngelConfig.getboolean("provider", "useIPv6"):
        from angel_app.ipv6 import reactor as ignored
    site = server.Site(root)
    getLogger().growl("User", "ETERNITY SERVICE",
                      "Started serving on port %s." % providerport)
    reactor.listenTCP(providerport, channel.HTTPFactory(site), 50)
    getLogger().info("Listening on port %d and serving content from %s" %
                     (providerport, repository))

    # initial test version to integrate a dyndns client into the provider loop
    dyndnsclient = getCallLaterDynDnsClientForAngelConfig(
        AngelConfig,
        callLaterMethod=reactor.callLater,
        logger=getLogger('dyndns'))
    if not dyndnsclient is None:
        reactor.callLater(1, dyndnsclient.check)
    reactor.run()
    getLogger().info("Quit")
def getCallLaterDynDnsClientForAngelConfig(angelConfig, callLaterMethod, logger):
    """
    factory method to instantiate and initialize a complete and working dyndns client for 
    use in the reactor loop.
    
    @param config: a dictionary with configuration pairs
    @return: None or a valid object for use with reactor.callLater()  
    """
    # no need to expose this class globally 
    class CallLaterDynDnsClient(object):
        "Minimal class to handle all of the dyndns logic using callbacks started from the reactor loop"
        def __init__(self, dyndnsclient, callLaterMethod, sleeptime):
            """
            @param dyndnsclient: a dyndnsclient object
            @param callLaterMethod: the twisted reactors callLater method
            @param sleeptime: how long to wait until callLater (secs)
            """
            self.sleeptime = sleeptime
            self.client = dyndnsclient 
            self.callLaterMethod = callLaterMethod
            # do an initial synchronization:
            self.client.sync()
    
        def check(self):
            "this will make the dyndns client check its state and also insert an additional callLater timer"
            self.client.check()
            self.callLaterMethod(self.sleeptime, self.check)

    # actual method
    try:
        dyndnsc.logger = logger
        config = getDynDnsConfiguration(angelConfig)
        if config is None:
            return None
        client = dyndnsc.getDynDnsClientForConfig(config)
        if not client is None:
            return CallLaterDynDnsClient(client, callLaterMethod, config['sleeptime'])
        else:
            return None
    except Exception, e:
        getLogger().error("Initializing dyndns client crashed", exc_info = e)
        return None 
def boot():
    from optparse import OptionParser
    bootInit()
    parser = OptionParser()
    parser.add_option("-d", "--daemon", dest="daemon", help="daemon mode?", default='')
    parser.add_option("-c", "--config", dest="config", help="alternative config file", default=None)
    parser.add_option("-l", "--log", dest="networklogging", help="use network logging?", action="store_true", default=False)
    (options, dummyargs) = parser.parse_args()

    # setup/configure config system
    from angel_app.config.config import getConfig
    angelConfig = getConfig(options.config)
    postConfigInit()
    angelConfig.bootstrapping = False

    appname = "presenter"
    # setup/configure logging
    from angel_app.log import initializeLogging
    loghandlers = [] # default: no handlers, add as needed below
    if len(options.daemon) > 0:
        loghandlers.append('socket')
    else:
        if (options.networklogging):
            loghandlers.append('socket')
        else:
            loghandlers.append('console')
            if angelConfig.getboolean('common', 'desktopnotification'):
                loghandlers.append('growl')
    if 'socket' not in loghandlers: # if there is no network logging, then log at least to file:
        loghandlers.append('file')
    initializeLogging(appname, loghandlers)

    if angelConfig.get(appname, 'enable') == False:
        from angel_app.log import getLogger
        getLogger().info("%s process is disabled in the configuration, quitting." % appname)
        sys.exit(0)

    if len(options.daemon) > 0:
        from angel_app.proc import daemonizer
        daemonizer.startstop(action=options.daemon, stdout=appname+'.stdout', stderr=appname+'.stderr', pidfile=appname+'.pid')

    return options
def getDynDnsConfiguration(angelConfig):
    """
    fetches dyndns configuration from angel config, if unconfigured or wrongly configured,
    returns None.
    
    This method serves as a bridge, so we can re-use dyndnsc.getDynDnsClientForConfig().

    @param angelConfig: an AngelConfig instance
    @return: a dictionary with key value pair options
    """
    required_keys = {'protocol': 'dyndns', 'hostname': None}
    other_keys = {
        'key': None,
        'userid': None,
        'password': None,
        'sleeptime': 60,
        'method': 'webcheck'
    }
    for key in required_keys.keys():
        try:
            option = angelConfig.get('dyndns', key)
        except:
            # if a required key is missing, return None to disable dyndns explicitly
            getLogger().warn("dyndns config incomplete: missing key '%s'" %
                             key)
            return None
        else:
            required_keys[key] = option
    for key in other_keys.keys():
        try:
            option = angelConfig.get('dyndns', key)
        except:
            # if an optional key is missing, ignore and use our default
            pass
        else:
            other_keys[key] = option

    # merge require and optional keys into one dictionary:
    for key in other_keys.keys():
        required_keys[key] = other_keys[key]
    return required_keys
def dance(options):
    from angel_app.config import config
    AngelConfig = config.getConfig()
    providerport = AngelConfig.getint("provider", "listenPort")
    repository = AngelConfig.get("common", "repository")

    from angel_app.resource.local.external import resource
    root = resource.External(repository)

    from twisted.web2 import server
    from twisted.web2 import channel
    from twisted.internet import reactor
    if AngelConfig.getboolean("provider", "useIPv6"):
        from angel_app.ipv6 import reactor as ignored
    site = server.Site(root)
    getLogger().growl("User", "ETERNITY SERVICE", "Started serving on port %s." % providerport)
    reactor.listenTCP(providerport, channel.HTTPFactory(site), 50) 
    getLogger().info("Listening on port %d and serving content from %s" % (providerport, repository))

    # initial test version to integrate a dyndns client into the provider loop
    dyndnsclient = getCallLaterDynDnsClientForAngelConfig(AngelConfig, callLaterMethod = reactor.callLater, logger = getLogger('dyndns'))
    if not dyndnsclient is None:
        reactor.callLater(1, dyndnsclient.check)
    reactor.run()
    getLogger().info("Quit")
def dance(options):
    """
    This method encapsulates all calls that are not framework related, e.g.
    the actual angel-app ;-)
    Also, it contains the hooks to events in the Twisted reactor.
    """
    from angel_app.logserver import startLoggingServer
    from angel_app.proc.procmanager import startProcesses 
    from angel_app.log import getLogger
    from twisted.internet import reactor
    log = getLogger(__name__)
    startLoggingServer()
    log.debug('logging server started')
    startProcesses(options.procsToStart)
    log.growl("User", "NODE ACTIVATED", "Launching sub-processes.")
    reactor.run()
    log.info("Quit")
def dance(options):
    from angel_app.log import getLogger
    from angel_app.config import config
    from angel_app.maintainer import client
    from angel_app.admin import initializeRepository

    log = getLogger("maintainer")

    log.debug("initializing repository")
    if not initializeRepository.initializeRepository():
        log.warn("Going to quit because initializeRepository failed.")
        return 1

    angelConfig = config.getConfig()
    repository = angelConfig.get("common", "repository")
    log.info("starting maintenance loop at '%s'" % repository)
    log.growl("User", "MAINTENANCE PROCESS", "Started.")
    try:
        client.maintenanceLoop()
    except Exception, e:
        log.critical("An exception occurred in the maintenance loop", exc_info = e)
        log.growl("User", "MAINTENANCE PROCESS", "Crash.")
        return -1
Beispiel #13
0
def dance(options):
    from angel_app.log import getLogger
    from angel_app.config import config
    from angel_app.maintainer import client
    from angel_app.admin import initializeRepository

    log = getLogger("maintainer")

    log.debug("initializing repository")
    if not initializeRepository.initializeRepository():
        log.warn("Going to quit because initializeRepository failed.")
        return 1

    angelConfig = config.getConfig()
    repository = angelConfig.get("common", "repository")
    log.info("starting maintenance loop at '%s'" % repository)
    log.growl("User", "MAINTENANCE PROCESS", "Started.")
    try:
        client.maintenanceLoop()
    except Exception, e:
        log.critical("An exception occurred in the maintenance loop",
                     exc_info=e)
        log.growl("User", "MAINTENANCE PROCESS", "Crash.")
        return -1
def dance(options):
    from angel_app.log import getLogger
    from angel_app.config import config
    AngelConfig = config.getConfig()
    port = AngelConfig.getint("presenter","listenPort")
    interface = AngelConfig.get("presenter","listenInterface")
    repository = AngelConfig.get("common","repository")

    from angel_app.resource.local.internal.resource import Crypto
    Crypto.rootDirectory = repository
    root = Crypto(repository)

    from twisted.web2 import server
    from twisted.web2 import channel
    from twisted.internet import reactor
    site = server.Site(root)
    reactor.listenTCP(port, channel.HTTPFactory(site), 50, interface)
    getLogger().info('Listening on IP %s port %d and serving content from %s', interface, port, repository)
    getLogger().growl("User", "ETERNITY FILE SYSTEM", "Available on port %s." % port)
    reactor.run()
    getLogger().info("Quit")
def dance(options):
    from angel_app.log import getLogger
    from angel_app.config import config
    AngelConfig = config.getConfig()
    port = AngelConfig.getint("presenter", "listenPort")
    interface = AngelConfig.get("presenter", "listenInterface")
    repository = AngelConfig.get("common", "repository")

    from angel_app.resource.local.internal.resource import Crypto
    Crypto.rootDirectory = repository
    root = Crypto(repository)

    from twisted.web2 import server
    from twisted.web2 import channel
    from twisted.internet import reactor
    site = server.Site(root)
    reactor.listenTCP(port, channel.HTTPFactory(site), 50, interface)
    getLogger().info('Listening on IP %s port %d and serving content from %s',
                     interface, port, repository)
    getLogger().growl("User", "ETERNITY FILE SYSTEM",
                      "Available on port %s." % port)
    reactor.run()
    getLogger().info("Quit")
Beispiel #16
0
import wx

from angel_app.log import getLogger
from angel_app.gui.statusbar import StatusLog

log = getLogger(__name__)

_ = wx.GetTranslation

class PrefsPanel(wx.Panel):
    def __init__(self, parent, statuslog):
        wx.Panel.__init__(self, parent)

        self.parent = parent
        self.statuslog = statuslog

        self.app = wx.GetApp()
 
        vboxMain = wx.BoxSizer(wx.VERTICAL)

        hboxCfgFile = wx.BoxSizer(wx.HORIZONTAL)
        hboxCfgFile.Add(wx.StaticText(self, -1, _("Using configuration file: ")), proportion = 0, flag = wx.ALIGN_CENTER, border = 0)
        hboxCfgFile.Add(wx.StaticText(self, -1, self.app.config.getConfigFilename()), proportion = 0, flag = wx.ALIGN_CENTER, border = 0)
        vboxMain.Add(hboxCfgFile, proportion = 0, flag = wx.ALL | wx.ALIGN_CENTER, border = 4)

        ######################
        # Network
        ######################
        panelNetworkSettings = wx.Panel(self, -1)
        sbSizerNetwork = wx.StaticBoxSizer(wx.StaticBox(panelNetworkSettings, -1, _("Network")), wx.VERTICAL)
        panelNetworkSettings.SetSizer(sbSizerNetwork)
"""
This module contains code for running the subprocesses in a separate thread.
In our case mainly useful in combination with the GUI, which has to control the master process,
but needs to stay responsive.
"""

import os
import sys
import signal
import time
import threading
import subprocess

from angel_app.log import getLogger

log = getLogger(__name__)


class SubprocessThread(threading.Thread):
    """
    Class for running an external process in its own thread.
    """
    def __init__(self, args=None):
        """
        Instantiate the subprocess thread and define the external command.
        
        @param args: list of strings passed to subprocess.Popen()
        """
        super(SubprocessThread, self).__init__()
        self.proc = None
        self.args = args
 def __init__(self):
     self.log = getLogger(self.__class__.__name__)