예제 #1
0
	def _read_config(self):
		# iterate over config dir
		configdir = '/etc/logcollector.d/'
		if os.path.exists(configdir):
			fnlist = os.listdir(configdir)
			for f in fnlist:
				fn = os.path.join(configdir, f)
				mode = os.stat(fn)[stat.ST_MODE]
				# fetch all files
				if not stat.S_ISDIR(mode):
					# read file
					fd = open(fn, 'r')
					content = fd.read()
					fd.close()
					# iterate over lines
					for line in content.splitlines():
						items = line.split('\t')
						if len(items) < 2:
							items.append('')

						# if file exists open file
						if items[0] and os.path.exists(items[0]):
							try:
								fd = open( items[0], 'rb' )
								self._config[ fd ] = { 'filename': items[0], 'serverdir': items[1], 'pos': -1 }
							except:
								debug( LOGERROR, 'ERROR: cannot open %s - ignoring file' % items[0])
		if len(self._config) == 0:
			debug( LOGERROR, 'ERROR: there is no file to read - please update config')
			sys.exit(1)
		else:
			notifier.timer_add( 50, notifier.Callback( self._check_new_data ) )
	def _timeout_connection(self, state):
		"""Closes the connection after a specified timeout"""
		state.time_remaining -= 1

		if state.time_remaining <= 0 and not state.requests and not state.session.has_active_module_processes():
			CORE.process('Connection timed out.')
			self._cleanup(state.socket)
		else:
			# count down the timer second-wise (in order to avoid problems when
			# changing the system time, e.g. via rdate)
			notifier.timer_add(1000, lambda: self._timeout_connection(state))
예제 #3
0
def died(pid, status):
    global output, lineno
    print ">>> process %d died" % pid, status

    if not output:
        print ">>> process %d produced NO output" % pid, status
    elif lineno and len(output) != lineno:
        print "NUMBERS OF LINES DO NOT MATCH!", len(output), lineno
        fd = open("ls_mismatch", "w")
        fd.write("\n".join(output))
        sys.exit(0)
    lineno = len(output)
    notifier.timer_add(100, run_ls)
예제 #4
0
def died( pid, status ):
	global output, lineno
	print ">>> process %d died" % pid, status

	if not output:
		print ">>> process %d produced NO output" % pid, status
	elif lineno and len( output ) != lineno:
		print 'NUMBERS OF LINES DO NOT MATCH!', len( output ), lineno
		fd = open( 'ls_mismatch', 'w' )
		fd.write( '\n'.join( output ) )
		sys.exit( 0 )
	lineno = len( output )
	notifier.timer_add( 100, run_ls )
예제 #5
0
    def _timer(self):
        """In order to avoid problems when the system time is changed (e.g.,
		via rdate), we register a timer event that counts down the session
		timeout second-wise."""
        # count down the remaining time
        if not self.__active_requests:
            self.__time_remaining -= 1

        if self.__time_remaining <= 0:
            # module has timed out
            self._timed_out()
        else:
            # count down the timer second-wise (in order to avoid problems when
            # changing the system time, e.g. via rdate)
            notifier.timer_add(1000, self._timer)
예제 #6
0
			def process_IN_MODIFY(self, event):
				if self.running:
					# remove running timer
					notifier.timer_remove(self.running)
				# add a timer which reloads UCR Variables in 10 seconds
				self.running = notifier.timer_add( 10000, self.process )
				return True
	def handle_request_exit(self, msg):
		"""Handles an EXIT request. If the request does not have an
		argument that contains a valid name of a running UMC module
		instance the request is returned as a bad request.

		If the request is valid it is passed on to the module
		process. Additionally a timer of 3000 milliseconds is
		started. After that amount of time the module process MUST have
		been exited itself. If not the UMC server will kill the module
		process.

		:param Request msg: UMCP request
		"""
		if len(msg.arguments) < 1:
			return self.handle_request_unknown(msg)

		module_name = msg.arguments[0]
		if module_name:
			if module_name in self.__processes:
				self.__processes[module_name].request(msg)
				CORE.info('Ask module %s to shutdown gracefully' % module_name)
				# added timer to kill away module after 3000ms
				cb = notifier.Callback(self._purge_child, module_name)
				self.__killtimer[module_name] = notifier.timer_add(3000, cb)
			else:
				CORE.info('Got EXIT request for a non-existing module %s' % module_name)
예제 #8
0
파일: session.py 프로젝트: B-Rich/smart
	def handle_request_exit( self, msg ):
		"""Handles an EXIT request. If the request does not have an
		argument that contains a valid name of a running UMC module
		instance the request is returned as a bad request.

		If the request is valid it is passed on to the module
		process. Additionally a timer of 3000 milliseconds is
		started. After that amount of time the module process MUST have
		been exited itself. If not the UMC server will kill the module
		process.

		:param Request msg: UMCP request
		"""
		if len( msg.arguments ) < 1:
			return self.handle_request_unknown( msg )

		module_name = msg.arguments[ 0 ]
		if module_name:
			if module_name in self.__processes:
				self.__processes[ module_name ].request( msg )
				CORE.info( 'Ask module %s to shutdown gracefully' % module_name )
				# added timer to kill away module after 3000ms
				cb = notifier.Callback( self._purge_child, module_name )
				self.__killtimer[ module_name ] = notifier.timer_add( 3000, cb )
			else:
				CORE.info( 'Got EXIT request for a non-existing module %s' % module_name )
예제 #9
0
	def __init__(self, options):
		super(ImageViewer, self).__init__()

		self.printer = QtGui.QPrinter()
		self.scaleFactor = 0.0

		self.imageLabel = QtGui.QLabel()
		self.imageLabel.setBackgroundRole(QtGui.QPalette.Base)
		self.imageLabel.setSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Ignored)
		self.imageLabel.setScaledContents(True)

		self.scrollArea = QtGui.QScrollArea()
		self.scrollArea.setBackgroundRole(QtGui.QPalette.Dark)
		self.scrollArea.setWidget(self.imageLabel)
		self.setCentralWidget(self.scrollArea)
		self.scrollArea.setWidgetResizable(True)

		self.setWindowTitle("Image Viewer")
		self.resize(500, 400)

		self.italcManager = italc2.ITALC_Manager()
		self.italcManager.school = options.school
		self.italcManager.room = options.room
		self.computer = self.italcManager[options.computer]
		self._timer = notifier.timer_add(500, self.updateScreenshot)
예제 #10
0
파일: session.py 프로젝트: B-Rich/smart
	def handle_request_command( self, msg ):
		"""Handles a COMMAND request. The request must contain a valid
		and known command that can be accessed by the current user. If
		access to the command is prohibited the request is answered as a
		forbidden command.

		If there is no running module process for the given command a
		new one is started and the request is added to a queue of
		requests that will be passed on when the process is ready.

		If a module process is already running the request is passed on
		and the inactivity timer is reset.

		:param Request msg: UMCP request
		"""
		module_name = self.__is_command_known( msg )
		if module_name and msg.arguments:
			if msg.mimetype == MIMETYPE_JSON:
				is_allowed = self.acls.is_command_allowed( msg.arguments[ 0 ], options = msg.options, flavor = msg.flavor )
			else:
				is_allowed = self.acls.is_command_allowed( msg.arguments[ 0 ] )
			if not is_allowed:
				response = Response( msg )
				response.status = BAD_REQUEST_FORBIDDEN
				response.message = status_description( response.status )
				self.signal_emit( 'response', response )
				return
			if not module_name in self.__processes:
				CORE.info( 'Starting new module process and passing new request to module %s: %s' % (module_name, str(msg._id)) )
				mod_proc = ModuleProcess( module_name, debug = MODULE_DEBUG_LEVEL, locale = self.i18n.locale )
				mod_proc.signal_connect( 'result', self._mod_result )
				cb = notifier.Callback( self._socket_died, module_name )
				mod_proc.signal_connect( 'closed', cb )
				cb = notifier.Callback( self._mod_died, module_name )
				mod_proc.signal_connect( 'finished', cb )
				self.__processes[ module_name ] = mod_proc
				cb = notifier.Callback( self._mod_connect, mod_proc, msg )
				notifier.timer_add( 50, cb )
			else:
				proc = self.__processes[ module_name ]
				if proc.running:
					CORE.info( 'Passing new request to running module %s' % module_name )
					proc.request( msg )
					self.reset_inactivity_timer( proc )
				else:
					CORE.info( 'Queuing incoming request for module %s that is not yet ready to receive' % module_name )
					proc._queued_requests.append( msg )
예제 #11
0
	def connect( self ):
		if not self._realsocket or not self._socket:
			self._init_socket()
		try:
			self._socket.connect( ( self._server, self._port ) )
			self._socket.setblocking( 0 )
			notifier.socket_add( self._socket, self._receive_data )
			debug( LOGERROR, 'SSL connection established' )

			self._send_setup()
		except:
			debug( LOGERROR, 'SSL connection failed' )
			self._socket = None
			notifier.timer_add( 5000, notifier.Callback( self.reconnect ) )
			return False

		return True
예제 #12
0
    def connect(self):
        if not self._realsocket or not self._socket:
            self._init_socket()
        try:
            self._socket.connect((self._server, self._port))
            self._socket.setblocking(0)
            notifier.socket_add(self._socket, self._receive_data)
            debug(LOGERROR, 'SSL connection established')

            self._send_setup()
        except:
            debug(LOGERROR, 'SSL connection failed')
            self._socket = None
            notifier.timer_add(5000, notifier.Callback(self.reconnect))
            return False

        return True
예제 #13
0
	def shutdown(self):
		"""Instructs the module process to shutdown"""
		if self.__processes:
			CORE.info('The session is shutting down. Sending EXIT request to %d modules.' % len(self.__processes))

		for module_name in list(self.__processes.keys()):
			CORE.info('Ask module %s to shutdown gracefully' % (module_name,))
			req = Request('EXIT', arguments=[module_name, 'internal'])
			process = self.__processes.pop(module_name)
			process.request(req)
			notifier.timer_remove(process._connect_timer)
			notifier.timer_add(4000, process.stop)

		if self._user_connections:
			reset_ldap_connection_cache(*self._user_connections)

		if isinstance(self.acls, LDAP_ACLs):
			reset_ldap_connection_cache(self.acls.lo)
			self.acls = None
예제 #14
0
	def __init__( self ):
		qt.QApplication.__init__( self, sys.argv )
		self.dialog = qt.QDialog()
		self.setActiveWindow( self.dialog )

		self.button = qt.QPushButton( 'Hello World', self.dialog )
		self.dialog.show()
		qt.QObject.connect( self.button, qt.SIGNAL( 'clicked()' ), self.clickedButton )
		self.timer_id = notifier.timer_add( 1000, self.timerTest )
		self.dispatch_it = 10
예제 #15
0
    def _read_config(self):
        # iterate over config dir
        configdir = '/etc/logcollector.d/'
        if os.path.exists(configdir):
            fnlist = os.listdir(configdir)
            for f in fnlist:
                fn = os.path.join(configdir, f)
                mode = os.stat(fn)[stat.ST_MODE]
                # fetch all files
                if not stat.S_ISDIR(mode):
                    # read file
                    fd = open(fn, 'r')
                    content = fd.read()
                    fd.close()
                    # iterate over lines
                    for line in content.splitlines():
                        items = line.split('\t')
                        if len(items) < 2:
                            items.append('')

                        # if file exists open file
                        if items[0] and os.path.exists(items[0]):
                            try:
                                fd = open(items[0], 'rb')
                                self._config[fd] = {
                                    'filename': items[0],
                                    'serverdir': items[1],
                                    'pos': -1
                                }
                            except:
                                debug(
                                    LOGERROR,
                                    'ERROR: cannot open %s - ignoring file' %
                                    items[0])
        if len(self._config) == 0:
            debug(LOGERROR,
                  'ERROR: there is no file to read - please update config')
            sys.exit(1)
        else:
            notifier.timer_add(50, notifier.Callback(self._check_new_data))
예제 #16
0
    def stop(self):
        """
		Stop the child. Tries to kill the process with signal 15 and after that
		kill -9 will be used to kill the app.
		"""
        if self.stopping:
            return

        self.stopping = True

        if self.is_alive() and not self.__kill_timer:
            cb = notifier.Callback(self.__kill, 15)
            self.__kill_timer = notifier.timer_add(0, cb)
예제 #17
0
파일: session.py 프로젝트: B-Rich/smart
	def reset_inactivity_timer( self, module ):
		"""Resets the inactivity timer. This timer watches the
		inactivity of the module process. If the module did not receive
		a request for MODULE_INACTIVITY_TIMER seconds the module process
		is shut down to save resources. The timer ticks each seconds to
		handle glitches of the system clock.

		:param Module module: a module 
		"""
		if module._inactivity_timer is None:
			module._inactivity_timer = notifier.timer_add( 1000, notifier.Callback( self._inactivitiy_tick, module ) )

		module._inactivity_counter = MODULE_INACTIVITY_TIMER
예제 #18
0
	def reset_inactivity_timer(self, module):
		"""Resets the inactivity timer. This timer watches the
		inactivity of the module process. If the module did not receive
		a request for MODULE_INACTIVITY_TIMER seconds the module process
		is shut down to save resources. The timer ticks each seconds to
		handle glitches of the system clock.

		:param Module module: a module
		"""
		if module._inactivity_timer is None:
			module._inactivity_timer = notifier.timer_add(1000, notifier.Callback(self._inactivitiy_tick, module))

		module._inactivity_counter = MODULE_INACTIVITY_TIMER
예제 #19
0
	def stop( self ):
		"""
		Stop the child. Tries to kill the process with signal 15 and after that
		kill -9 will be used to kill the app.
		"""
		if self.stopping:
			return

		self.stopping = True

		if self.is_alive() and not self.__kill_timer:
			cb = Callback( self.__kill, 15 )
			self.__kill_timer = notifier.timer_add( 0, cb )
예제 #20
0
    def __killall(self, signal):
        """
		Internal killall helper function
		"""
        if not self.is_alive():
            self.__dead = True
            self.stopping = False
            return False
        # child needs some assistance with dying ...
        try:
            # kill all applications with the string <appname> in their
            # commandline. This implementation uses the /proc filesystem,
            # it is Linux-dependent.
            unify_name = re.compile('[^A-Za-z0-9]').sub
            appname = unify_name('', self.binary)

            cmdline_filenames = glob.glob('/proc/[0-9]*/cmdline')

            for cmdline_filename in cmdline_filenames:
                try:
                    fd = open(cmdline_filename)
                    cmdline = fd.read()
                    fd.close()
                except IOError:
                    continue
                if unify_name('', cmdline).find(appname) != -1:
                    # Found one, kill it
                    pid = int(cmdline_filename.split('/')[2])
                    try:
                        os.kill(pid, signal)
                    except:
                        pass
        except OSError:
            pass

        log.info('kill -%d %s' % (signal, self.binary))
        if signal == 15:
            cb = notifier.Callback(self.__killall, 9)
            self.__kill_timer = notifier.timer_add(2000, cb)
        else:
            log.critical('PANIC %s' % self.binary)

        return False
예제 #21
0
	def __killall( self, signal ):
		"""
		Internal killall helper function
		"""
		if not self.is_alive():
			self.__dead = True
			self.stopping = False
			return False
		# child needs some assistance with dying ...
		try:
			# kill all applications with the string <appname> in their
			# commandline. This implementation uses the /proc filesystem,
			# it is Linux-dependent.
			unify_name = re.compile( '[^A-Za-z0-9]' ).sub
			appname = unify_name( '', self.binary )

			cmdline_filenames = glob.glob( '/proc/[0-9]*/cmdline' )

			for cmdline_filename in cmdline_filenames:
				try:
					fd = open( cmdline_filename )
					cmdline = fd.read()
					fd.close()
				except IOError:
					continue
				if unify_name( '', cmdline ).find( appname ) != -1:
					# Found one, kill it
					pid = int( cmdline_filename.split( '/' )[ 2 ] )
					try:
						os.kill( pid, signal )
					except:
						pass
		except OSError:
			pass

		log.info( 'kill -%d %s' % ( signal, self.binary ) )
		if signal == 15:
			cb = Callback( self.__killall, 9 )
			self.__kill_timer = notifier.timer_add( 2000, cb )
		else:
			log.critical( 'PANIC %s' % self.binary )

		return False
예제 #22
0
    def __kill(self, signal):
        """
		Internal kill helper function
		"""
        if not self.is_alive():
            self.__dead = True
            self.stopping = False
            return False
        # child needs some assistance with dying ...
        try:
            os.kill(self.pid, signal)
        except OSError:
            pass

        if signal == 15:
            cb = notifier.Callback(self.__kill, 9)
        else:
            cb = notifier.Callback(self.__killall, 15)

        self.__kill_timer = notifier.timer_add(3000, cb)
        return False
예제 #23
0
	def __kill( self, signal ):
		"""
		Internal kill helper function
		"""
		if not self.is_alive():
			self.__dead = True
			self.stopping = False
			return False
		# child needs some assistance with dying ...
		try:
			os.kill( self.pid, signal )
		except OSError:
			pass

		if signal == 15:
			cb = Callback( self.__kill, 9 )
		else:
			cb = Callback( self.__killall, 15 )

		self.__kill_timer = notifier.timer_add( 3000, cb )
		return False
예제 #24
0
    def handle(self, msg):
        # type: (Request) -> None
        """Handles incoming UMCP requests. This function is called only
		when it is a valid UMCP request.

		:param Request msg: the received UMCP request

		The following commands are handled directly and are not passed
		to the custom module code:

		* SET (acls|username|credentials)
		* EXIT
		"""
        from ..error import UMC_Error, NotAcceptable
        self.__time_remaining = self.__timeout
        PROTOCOL.info('Received UMCP %s REQUEST %s' % (msg.command, msg.id))

        resp = Response(msg)
        resp.status = SUCCESS

        if msg.command == 'EXIT':
            shutdown_timeout = 100
            MODULE.info("EXIT: module shutdown in %dms" % shutdown_timeout)
            # shutdown module after one second
            resp.message = 'module %s will shutdown in %dms' % (
                msg.arguments[0], shutdown_timeout)
            self.response(resp)
            notifier.timer_add(shutdown_timeout, self._timed_out)
            return

        if self.__init_etype:
            notifier.timer_add(10000, self._timed_out)
            six.reraise(self.__init_etype, self.__init_exc,
                        self.__init_etraceback)

        if msg.command == 'SET':
            for key, value in msg.options.items():
                if key == 'acls':
                    self.__acls = ACLs(acls=value)
                    self.__handler.acls = self.__acls
                elif key == 'commands':
                    self.__commands.fromJSON(value['commands'])
                elif key == 'username':
                    self.__username = value
                    self.__handler.username = self.__username
                elif key == 'password':
                    self.__password = value
                    self.__handler.password = self.__password
                elif key == 'auth_type':
                    self.__auth_type = value
                    self.__handler.auth_type = self.__auth_type
                elif key == 'credentials':
                    self.__username = value['username']
                    self.__user_dn = value['user_dn']
                    self.__password = value['password']
                    self.__auth_type = value.get('auth_type')
                    self.__handler.username = self.__username
                    self.__handler.user_dn = self.__user_dn
                    self.__handler.password = self.__password
                    self.__handler.auth_type = self.__auth_type
                elif key == 'locale' and value is not None:
                    try:
                        self.__handler.update_language([value])
                    except NotAcceptable:
                        pass  # ignore if the locale doesn't exists, it continues with locale C
                else:
                    raise UMC_Error(status=422)

            # if SET command contains 'acls', commands' and
            # 'credentials' it is the initialization of the module
            # process
            if 'acls' in msg.options and 'commands' in msg.options and 'credentials' in msg.options:
                MODULE.process('Initializing module.')
                try:
                    self.__handler.init()
                except Exception:
                    try:
                        exc_info = sys.exc_info()
                        self.__init_etype, self.__init_exc, self.__init_etraceback = exc_info  # FIXME: do not keep a reference to traceback
                        self.error_handling(msg, 'init', *exc_info)
                    finally:
                        exc_info = None
                    return

            self.response(resp)
            return

        if msg.arguments:
            cmd = msg.arguments[0]
            cmd_obj = self.command_get(cmd)
            if cmd_obj and (not self.__check_acls
                            or self.__acls.is_command_allowed(
                                cmd, options=msg.options, flavor=msg.flavor)):
                self.__active_requests += 1
                self.__handler.execute(cmd_obj.method, msg)
                return
            raise UMC_Error('Not initialized.', status=403)
예제 #25
0
    def __init__(self):
        qt.QCoreApplication.__init__(self, sys.argv)

        self.timer_id = notifier.timer_add(1000, self.timerTest)
        self.dispatch_it = 10
예제 #26
0
    print "tick"
    return True


def give_birth():
    ls = notifier.popen.run("/bin/ls -ltr /etc", stderr=False, shell=False)
    # process dead?
    if ls.pid == None:
        print ls.stdout.read()
        ls.stdout.close()

    sleep = notifier.popen.run("sleep 5", timeout=3, stderr=False, stdout=False, shell=False)
    if sleep.pid:
        print "process still running", sleep.pid
        ret = notifier.popen.kill(sleep)
        print "killed", ret

    return False


if __name__ == "__main__":
    notifier.init(notifier.GENERIC)

    # run processes
    notifier.timer_add(1500, give_birth)

    # show we can still do things
    notifier.timer_add(500, tick)

    notifier.loop()
예제 #27
0
# 02110-1301 USA

import notifier

import time

def timeout( data ):
    print 'timeout', time.time()
    print '  data    :', data

    return True

def zero( data ):
    print 'timeout', time.time()
    print '  data    :', data

    return True

def dispatch( data ):
    #print 'dispatch', data
    return True

# when no argument is given to init default is GENERIC
notifier.init( notifier.GENERIC, recursive_depth = 5 )
notifier.timer_add( 1000, notifier.Callback( timeout, 'hello' ) )
#notifier.timer_add( 0, notifier.Callback( zero, 'hello' ) )
notifier.dispatcher_add( notifier.Callback( dispatch, 'hello' ) )
#notifier.dispatcher_add( notifier.Callback( dispatch, 'hello' ), False )

notifier.loop()
예제 #28
0
    def run(self):
        self._timer = notifier.timer_add(2000, self.tick)

        notifier.loop()
예제 #29
0
            notifier.step()
        else:
            break


def run_ls():
    global output

    output = []
    proc = notifier.popen.Process("/bin/ls -latr --color=never /usr/lib")
    proc.signal_connect("stdout", stdout)
    proc.signal_connect("stderr", stderr)
    proc.signal_connect("killed", died)
    proc.start()

    return False


if __name__ == "__main__":
    notifier.init(notifier.GENERIC)

    # run a process and wait for its death
    # 	notifier.timer_add( 500, runit )

    # show we can still do things
    notifier.timer_add(100, tick)

    notifier.timer_add(500, run_ls)

    notifier.loop()
예제 #30
0

@nfthreads.threaded(done_with_it)
def my_thread():
    number = random.randint(50, 100)
    for i in range(number):
        time.sleep(0.1)
    if random.randint(0, 10) < 6:
        raise Exception('mysterious problem')
    return number


def doing_something_else():
    print '>>> Pick me!'
    return True


if __name__ == '__main__':
    notifier.init(notifier.GENERIC)

    _stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
    _stdout.write('Starting threads ')
    for i in range(100):
        _stdout.write('.')
        my_thread()
        time.sleep(0.02)
        _stdout.write('\033[1D*')
    _stdout.write('\n')
    notifier.timer_add(1000, doing_something_else)
    notifier.loop()
예제 #31
0
	def __init__( self ):
		qt.QCoreApplication.__init__( self, sys.argv )

		self.timer_id = notifier.timer_add( 1000, self.timerTest )
		self.dispatch_it = 10
예제 #32
0
import notifier
import notifier.signals as signals

def _wait_for_click():
	print "clicked"

def _wait_for_movement( optional = None ):
	print "optional:", optional

def _emitting():
	signals.emit( "clicked" )
	# return True

if __name__ == '__main__':
	notifier.init( notifier.GENERIC )

	signals.new( "clicked" )
	try:
		signals.connect( "clicked2", _wait_for_click )
	except signals.UnknownSignalError, e:
		print 'Exception:', e
	if not signals.exists( 'clicked3' ):
		print "signal 'clicked3' does not exist"
	signals.connect( 'clicked', _wait_for_click )
	signals.connect( 'clicked', notifier.Callback( _wait_for_movement,
												 'optional something' ) )
	notifier.timer_add( 3000, _emitting )

	notifier.loop()
예제 #33
0
	def run( self ):
		self._timer = notifier.timer_add( 2000, self.tick )

		notifier.loop()
 def reset_connection_timeout(self, state):
     state.reset_connection_timeout()
     notifier.timer_remove(state._timer)
     state._timer = notifier.timer_add(
         state.timeout * 1000, notifier.Callback(self._timed_out, state))
예제 #35
0
			recv = None
		except SSL.Error:
			error = sock.getsockopt( socket.SOL_SOCKET, socket.SO_ERROR )
			if error == errno.EPIPE:
				# lost connection: server died probably
				debug( LOGDEBUG, 'EPIPE' )
				recv = None
			else:
				return True

		if not recv:
			sock.close()
			notifier.socket_remove( sock )
			notifier.socket_remove( sock, condition = notifier.IO_WRITE )
			self._socket = None
			notifier.timer_add( 1000, notifier.Callback( self.reconnect ) )
			return False

		self._inbuffer += recv

		debug( LOGDEBUG, 'BUFFER: len=%d    got %d bytes' % (len(self._inbuffer), len(recv)))

		# repeat while enough data is present
		while len(self._inbuffer) > 4:
			# get length of pickle object
			plen = struct.unpack('!I', self._inbuffer[0:4])[0]
			if plen+4 <= len(self._inbuffer):
				# unpickle data
				packet = cPickle.loads( self._inbuffer[4:4+plen] )
				# remove data from buffer
				self._inbuffer = self._inbuffer[4+plen:]
예제 #36
0
def done_with_it( thread, result, another ):
	print "-> Thread '%s' is finished" % thread.name
	print "  Argument:", another
	if isinstance( thread.result, BaseException ):
		print "  Error occurred during thread processing:", type( thread.result ), thread.result
		print "  Details:\n%s" % ''.join( thread.trace )
	else:
		print "  Counted from 0 to %d" % result

def doing_something_else():
	print 'tick'
	return True

if __name__ == '__main__':
	notifier.init( notifier.GENERIC )

	_stdout = os.fdopen( sys.stdout.fileno(), 'w', 0 )
	_stdout.write( 'Starting threads ' )
	for i in range( 100 ):
		_stdout.write( '.' )
		task = threads.Simple( 'test%d' % i,
							   notifier.Callback( my_thread, [ 'hello', 'world' ] ),
							   notifier.Callback( done_with_it, 'another argument' ) )
		task.run()
		time.sleep( 0.05 )
		_stdout.write( '\033[1D*' )
	_stdout.write( '\n' )
	notifier.timer_add( 1000, doing_something_else )
	notifier.loop()
예제 #37
0
import os, sys

import notifier
import notifier.popen


def tick():
    print 'tick'
    cmd = [
        'ps', 'h', '-eo', 'pcpu,vsize,rssize,pmem,user,pid,command',
        '--sort=-pcpu'
    ]
    proc = notifier.popen.Process(cmd, stdout=True)
    proc.signal_connect('stdout', find_result)
    proc.start()

    return True


def find_result(pid, result):
    for line in result:
        print line


if __name__ == '__main__':
    notifier.init(notifier.GENERIC)

    notifier.timer_add(5000, tick)

    notifier.loop()
예제 #38
0
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA

import os

import notifier

def tail_minus_f( logfile ):
	new_size = os.stat( logfile.name )[ 6 ]
	if new_size > logfile.tell():
		buffer = logfile.read( 65536 )
		if buffer: print buffer,

	return True

if __name__ == '__main__':
	notifier.init()
	filename = '/var/log/messages'
	if not os.path.isfile( filename ):
		filename = '/var/log/syslog'
	log = open( filename, 'rb' )
	log.seek( os.stat( filename )[ 6 ] )
	notifier.timer_add( 100, notifier.Callback( tail_minus_f, log ) )
	notifier.loop()
예제 #39
0
                      dest='username',
                      default='Administrator')
    parser.add_option('-p',
                      '--password',
                      dest='password',
                      default='univention')
    options, args = parser.parse_args()

    if options.logmode:
        log_init('/dev/stderr')
        log_set_level(int(options.debug))
    else:
        log_init('italc2-monitor')
        log_set_level(int(options.debug))

    usl.set_credentials(
        'uid=%s,cn=users,%s' % (options.username, config.get('ldap/base')),
        options.password)

    m = italc2.ITALC_Manager()
    m.school = options.school
    m.room = options.room

    if not options.logmode and not options.logonly:
        show_state(options)
        print 'starting timer'
        timer = notifier.timer_add(2000,
                                   notifier.Callback(show_state, options))

    notifier.loop()
예제 #40
0
 def start(self):
     self.stop()
     self._resetUserInfoTimeout()
     self.update()
     self._timer = notifier.timer_add(ITALC_CORE_UPDATE * 1000, self.update)
예제 #41
0
button = gtk.Button('Hello World')
button.connect('clicked', hello)
window.add(button)
button.show()

window.show()


# notifier-timer testfunction
def timer_test():
    print "timer_test"
    #	 notifier.dispatcher_add( notifier.Callback( dispatcher_test, 1, 2, 3 ) )
    return True


def dispatcher_test(a, b, c):
    #	 print 'dispatcher', a, b, c
    return True


def _stdin(fd):
    notifier.socket_remove(0)
    return False


notifier.socket_add(0, _stdin)
notifier.timer_add(4000, notifier.Callback(timer_test))
notifier.dispatcher_add(notifier.Callback(dispatcher_test, 1, 2, 3))
notifier.loop()
예제 #42
0
import time


def timeout(data):
    print 'timeout', time.time()
    print '  data    :', data

    return True


def zero(data):
    print 'timeout', time.time()
    print '  data    :', data

    return True


def dispatch(data):
    #print 'dispatch', data
    return True


# when no argument is given to init default is GENERIC
notifier.init(notifier.GENERIC, recursive_depth=5)
notifier.timer_add(1000, notifier.Callback(timeout, 'hello'))
#notifier.timer_add( 0, notifier.Callback( zero, 'hello' ) )
notifier.dispatcher_add(notifier.Callback(dispatch, 'hello'))
#notifier.dispatcher_add( notifier.Callback( dispatch, 'hello' ), False )

notifier.loop()
예제 #43
0
            recv = None
        except SSL.Error:
            error = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
            if error == errno.EPIPE:
                # lost connection: server died probably
                debug(LOGDEBUG, 'EPIPE')
                recv = None
            else:
                return True

        if not recv:
            sock.close()
            notifier.socket_remove(sock)
            notifier.socket_remove(sock, condition=notifier.IO_WRITE)
            self._socket = None
            notifier.timer_add(1000, notifier.Callback(self.reconnect))
            return False

        self._inbuffer += recv

        debug(
            LOGDEBUG, 'BUFFER: len=%d    got %d bytes' %
            (len(self._inbuffer), len(recv)))

        # repeat while enough data is present
        while len(self._inbuffer) > 4:
            # get length of pickle object
            plen = struct.unpack('!I', self._inbuffer[0:4])[0]
            if plen + 4 <= len(self._inbuffer):
                # unpickle data
                packet = cPickle.loads(self._inbuffer[4:4 + plen])
예제 #44
0
	def handle_request_command(self, msg):
		"""Handles a COMMAND request. The request must contain a valid
		and known command that can be accessed by the current user. If
		access to the command is prohibited the request is answered as a
		forbidden command.

		If there is no running module process for the given command a
		new one is started and the request is added to a queue of
		requests that will be passed on when the process is ready.

		If a module process is already running the request is passed on
		and the inactivity timer is reset.

		:param Request msg: UMCP request
		"""

		# only one command?
		command = None
		if msg.arguments:
			command = msg.arguments[0]

		module_name = moduleManager.module_providing(self.__command_list, command)

		try:
			# check if the module exists in the module manager
			moduleManager[module_name]
		except KeyError:
			# the module has been removed from moduleManager (probably through a reload)
			CORE.warn('Module %r (command=%r, id=%r) does not exists anymore' % (module_name, command, msg.id))
			moduleManager.load()
			self._reload_acls_and_permitted_commands()
			module_name = None

		if not module_name:
			raise Forbidden()

		if msg.arguments:
			if msg.mimetype == MIMETYPE_JSON:
				is_allowed = moduleManager.is_command_allowed(self.acls, msg.arguments[0], options=msg.options, flavor=msg.flavor)
			else:
				is_allowed = moduleManager.is_command_allowed(self.acls, msg.arguments[0])
			if not is_allowed:
				raise Forbidden()
			if module_name not in self.__processes:
				CORE.info('Starting new module process and passing new request to module %s: %s' % (module_name, str(msg._id)))
				try:
					mod_proc = ModuleProcess(module_name, debug=MODULE_DEBUG_LEVEL, locale=self.i18n.locale)
				except EnvironmentError as exc:
					message = self._('Could not open the module. %s Please try again later.') % {
						errno.ENOMEM: self._('There is not enough memory available on the server.'),
						errno.EMFILE: self._('There are too many opened files on the server.'),
						errno.ENFILE: self._('There are too many opened files on the server.'),
						errno.ENOSPC: self._('There is not enough free space on the server.')
					}.get(exc.errno, self._('An unknown operating system error occurred (%s).' % (exc,)))
					raise ServiceUnavailable(message)
				mod_proc.signal_connect('result', self.result)

				cb = notifier.Callback(self._mod_error, module_name)
				mod_proc.signal_connect('error', cb)

				cb = notifier.Callback(self._socket_died, module_name)
				mod_proc.signal_connect('closed', cb)

				cb = notifier.Callback(self._mod_died, module_name)
				mod_proc.signal_connect('finished', cb)

				self.__processes[module_name] = mod_proc

				cb = notifier.Callback(self._mod_connect, mod_proc, msg)
				notifier.timer_add(50, cb)
			else:
				proc = self.__processes[module_name]
				if proc.running:
					CORE.info('Passing new request to running module %s' % module_name)
					proc.request(msg)
					self.reset_inactivity_timer(proc)
				else:
					CORE.info('Queuing incoming request for module %s that is not yet ready to receive' % module_name)
					proc._queued_requests.append(msg)
예제 #45
0
class TestSignal(signals.Provider):
    def __init__(self):
        signals.Provider.__init__(self)
        self.signal_new("test-signal")


test = TestSignal()


def timer_cb(a):
    print "timer argument", a
    signals.emit("test-signal")
    test.signal_emit("test-signal")
    print "-------------------------"
    return True


def signal_cb(signal, a, b):
    print "signal arguments", signal, a, b
    signals.disconnect("test-signal", signal_cb)


notifier.init(notifier.GENERIC)

signals.new("test-signal")
signals.connect("test-signal", notifier.Callback(signal_cb, 1, 2, "global signal"))
test.signal_connect("test-signal", notifier.Callback(signal_cb, 1, 2, "TestSignal signal"))
notifier.timer_add(2000, notifier.Callback(timer_cb, 7))

notifier.loop()
예제 #46
0
        self.signal_new('test-signal')


test = TestSignal()


def timer_cb(a):
    print 'timer argument', a
    signals.emit('test-signal')
    test.signal_emit('test-signal')
    print '-------------------------'
    return True


def signal_cb(signal, a, b):
    print 'signal arguments', signal, a, b
    # disconnect global signal
    signals.disconnect('test-signal', signal_cb)


notifier.init(notifier.GENERIC)

signals.new('test-signal')
signals.connect('test-signal',
                notifier.Callback(signal_cb, 1, 2, 'global signal'))
test.signal_connect('test-signal',
                    notifier.Callback(signal_cb, 1, 2, 'TestSignal signal'))
notifier.timer_add(2000, notifier.Callback(timer_cb, 7))

notifier.loop()
예제 #47
0
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA

import os, sys

import notifier
import notifier.popen

def tick():
	print 'tick'
	cmd = ['ps', 'h', '-eo', 'pcpu,vsize,rssize,pmem,user,pid,command', '--sort=-pcpu']
	proc = notifier.popen.Process( cmd, stdout = True )
	proc.signal_connect( 'stdout', find_result )
	proc.start()

	return True

def find_result( pid, result ):
	for line in result:
		print line

if __name__ == '__main__':
	notifier.init( notifier.GENERIC )

	notifier.timer_add( 5000, tick )

	notifier.loop()
예제 #48
0
import os, sys

#import twisted

import notifier

notifier.init( notifier.TWISTED )

def hello( *args ):
	print 'Hello World'

# notifier-timer testfunction
def timer_test():
	print "timer_test"
#	 notifier.dispatcher_add( notifier.Callback( dispatcher_test, 1, 2, 3 ) )
	return True

def dispatcher_test( a, b, c ):
	print 'dispatcher', a, b, c
	return True

def _stdin( fd ):
	print 'read: ' + os.read( fd, 512 )
	notifier.socket_remove( 0 )
	return False

notifier.socket_add( 0, _stdin )
notifier.timer_add( 4000, notifier.Callback( timer_test ) )
notifier.dispatcher_add( notifier.Callback( dispatcher_test, 1, 2, 3 ) )
notifier.loop()
예제 #49
0
def give_birth():
    ls = notifier.popen.run('/bin/ls -ltr /etc', stderr=False, shell=False)
    # process dead?
    if ls.pid == None:
        print ls.stdout.read()
        ls.stdout.close()

    sleep = notifier.popen.run('sleep 5',
                               timeout=3,
                               stderr=False,
                               stdout=False,
                               shell=False)
    if sleep.pid:
        print 'process still running', sleep.pid
        ret = notifier.popen.kill(sleep)
        print 'killed', ret

    return False


if __name__ == '__main__':
    notifier.init(notifier.GENERIC)

    # run processes
    notifier.timer_add(1500, give_birth)

    # show we can still do things
    notifier.timer_add(500, tick)

    notifier.loop()