Beispiel #1
0
def init(filename=None):
    from consys.common import daemonise
    from consys.common import configuration

    config = configuration.register_section('log', 
        {
            'syslog': 'boolean(default=False)',
            'logdir': 'path(default=None)',
        })

    if config['logdir'] is not None:
        logpath = os.path.join(config['logdir'], filename)
        file_formatter = logging.Formatter(fmt='%(asctime)s [%(name)s] -- %(message)s')
        log_file = logging.handlers.RotatingFileHandler(logpath,
                        maxBytes=1024*64, backupCount=3)
        log_file.setLevel(logging.DEBUG)
        log_file.setFormatter(file_formatter)
        _root_log.addHandler(log_file)
        daemonise.preserve_handle(log_file.stream)
    
    if config['syslog']:
        syslog_formatter = logging.Formatter(fmt='[%(name)s]: %(message)s')
        log_syslog = logging.handlers.SysLogHandler(b'/dev/log')
        log_syslog.setLevel(logging.INFO)
        log_syslog.setFormatter(syslog_formatter)
        _root_log.addHandler(log_syslog)
    
    _root_log.info('Logging started')

    # Set up twisted to use generic logging
    from twisted.python import log as twisted_log
    twisted_log.PythonLoggingObserver().start()
Beispiel #2
0
from __future__ import unicode_literals

import signal

from consys.common import log
from consys.common import configuration
from consys.common import daemonise

_log = log.getLogger(__name__)

_config = configuration.register_section(None,
    {
        'client-pid-file': 'path(default=/var/run/consys-client.pid)',
    })

def run():
    try:
        log.init('client.log')

        context = daemonise.getContext(
            pidfile = _config['client-pid-file'],
            signal_map = {
                signal.SIGUSR1: 'terminate',
                signal.SIGHUP: configuration.reload,
            },
        )

        _log.debug('Entering running context...')
        with context:
            _log.info('Configuration file: {0}'.format(configuration.filename()))
            _log.info('Initializing ConSys client daemon...')
Beispiel #3
0
from __future__ import unicode_literals

from urlparse import urlparse

from notify.all import Signal
from twistar.registry import Registry
from twistar.dbobject import DBObject
from twistar.dbconfig.base import InteractionBase

from twisted.enterprise import adbapi

from consys.common import log
from consys.common import configuration, app

_config = configuration.register_section('server-persistence', 
    {
        'db-url': 'string(default=sqlite:///data/server.db)',
    })

_log = log.getLogger(__name__)

def _handle_sqlite(parsed_url):
    return ('sqlite3', {
            'database': parsed_url.path[1:],
            'check_same_thread': False,
            })

_drivers = {'sqlite': _handle_sqlite}

Base = DBObject

ready = Signal()
Beispiel #4
0
@author: Nikita Ofitserov
'''

from __future__ import unicode_literals 

from twisted.conch import error
from twisted.conch.ssh import userauth, connection, keys
from twisted.internet import defer, protocol

from consys.common import log, network
from consys.common import configuration, app


_config = configuration.register_section('network', 
    {
        'server-string': 'string()',
        'server-public-key': 'path(default=keys/server.pub)',
    })

_log = log.getLogger(__name__)


class Credentials(object):
    ''' Simple username/password credentials. '''
    def __init__(self, username, password):
        self.username = username
        self.password = password


class ClientTransport(network.SSHClientTransport):
    def __init__(self, knownHostKey, deferred, onDisconnect, cred):
Beispiel #5
0
from __future__ import unicode_literals

import signal

from consys.common import log
from consys.common import configuration
from consys.common import daemonise

_log = log.getLogger(__name__)

_config = configuration.register_section(None,
    {
        'server-pid-file': 'path(default=/var/run/consys-server.pid)',
    })

def run():
    try:
        log.init('server.log')

        context = daemonise.getContext(
            pidfile = _config['server-pid-file'],
            signal_map = {
                signal.SIGUSR1: 'terminate',
                signal.SIGHUP: configuration.reload,
            },
        )

        _log.debug('Entering running context...')
        with context:
            _log.info('Configuration file: {0}'.format(configuration.filename()))
            _log.info('Initializing ConSys server daemon...')
Beispiel #6
0
import os

from twisted.conch.ssh import userauth, connection, keys
from twisted.internet import defer, protocol
from twisted.spread import pb

from consys.common import log
from consys.common import configuration, app
from consys.common import network
from consys.client import root

_config = configuration.register_section('network', 
    {
        'server-string': 'string()',
        'client-key': 'path(default=keys/client)',
        'server-public-key': 'path(default=keys/server.pub)',
        'client-user-name': 'string(default=terminal)',
    })

_log = log.getLogger(__name__)

class ClientTransport(network.SSHClientTransport):
    def __init__(self, knownHostKey, deferred, onDisconnect):
        network.SSHClientTransport.__init__(self, knownHostKey, deferred,
                                            onDisconnect, SSHConnection)

    def getAuthenticator(self, connection):
        username = _config['client-user-name'].encode('utf-8')
        return SimplePubkeyUserAuth(username, connection)
Beispiel #7
0
from twisted.conch.ssh import session, keys, factory, userauth, connection
from twisted.cred import portal
from twisted.cred.checkers import FilePasswordDB
from twisted.internet import reactor, protocol, endpoints
from twisted.python import components
from twisted.spread import pb

from consys.common import log
from consys.common import configuration, network, app

__all__ = ['on_startup', 'client_connected', 'client_disconnected']

_config = configuration.register_section('network',
     {
        'listen-string': 'string(default=tcp:2222)',
        'server-key': 'path(default=keys/server)',
        'client-public-key': 'path(default=keys/client.pub)',
        'client-user-name': 'string(default=terminal)',
        'user-auth-db': 'path(default=data/admins.txt)'
     })

_log = log.getLogger(__name__)

class ClientAvatar(avatar.ConchUser, pb.Root):
    CONNECT_DELAY = 0.25

    def __init__(self):
        avatar.ConchUser.__init__(self)
        self.terminalId = None
        self.rpcFactory = pb.PBServerFactory(self)
        self.connected = False
Beispiel #8
0
''' A generic scheduler for asynchronous processing.
@author: Nikita Ofitserov
'''

from __future__ import unicode_literals

import threading
from time import sleep

from consys.common import log
from consys.common import configuration

__all__ = ['schedule', 'Future']

_config = configuration.register_section('scheduler',
    {
        'thread-pool-size': 'integer(min=1, default=5)',
    })

_log = log.getLogger(__name__)

def schedule(self, task, args=()):
    '''Schedules the call and returns a future'''
    future = Future()
    self.pool.queueTask(task, args, future.set_result)
    return future
        
class Future:
    ''' A generic future value class '''
    
    def __init__(self):
        self.event = threading.Condition(threading.Lock())
Beispiel #9
0
Persistent storage support. Based on Shelve.
@author: Nikita Ofitserov
'''

from __future__ import unicode_literals

import shelve

from notify.all import Signal


from consys.common import log
from consys.common import configuration, app

_config = configuration.register_section('client-persistence', 
    {
        'db-file': 'path(default=data/client.db)',
    })

_log = log.getLogger(__name__)

ready = Signal()
'''Is emitted when the storage becomes available'''

storage = None
'''The storage dict-like object'''

def on_startup():
    global storage
    storage = shelve.open(_config['db-file'])
    ready()
Beispiel #10
0
'''
Manage desktop locking
@author: Nikita Ofitserov
'''

from twisted.internet.defer import inlineCallbacks
from twisted.spread import pb

from consys.common import log
from consys.common import configuration
from consys.client import dbus

_log = log.getLogger(__name__)

_config = configuration.register_section('locker', 
    {
        'use-plasma': 'boolean(default=true)',
    })

class Locker(pb.Referenceable):
    screensaver_path = (b'org.freedesktop.ScreenSaver', b'/ScreenSaver')
    plasma_overlay_path = (b'org.kde.plasma-overlay', b'/App')
    
    def __init__(self):
        object = dbus.session_bus().get_object(*self.screensaver_path)
        self.screensaver = object.get_interface(b'org.freedesktop.ScreenSaver')
        
    def lock(self):
        d = self.screensaver.call(b'Lock')
        def callback(retval):
            _log.debug('Screen locked')
        def errback(failure):