def break_lock(self): from lockfile import FileLock lock = FileLock(self.lock_path) if lock.is_locked(): lock.break_lock()
def tearDown(self): self.del_lock() fl = FileLock(smtp2gs_locker.LOCK_NAME) fl.break_lock() smtp2gs_locker.LOCK_NAME = self.oldLockName smtp2gs_locker.BREAK_LOCK_AGE = self.oldBreakLockTimeout smtp2gs_locker.MAX_LOCK_TIMEOUT = self.maxLockTimeout
def MakeGraphTop3(self, Data, FileName): """ Funzione che produce un grafico dei nodi a maggiore latenza sotto forma di istogram. :param Data: Serie di dati da dover graficare. :param FileName: Nome file da assegnare al grafico prodotto. :returns: *nulla* """ global Interval FileName = 'extra/MonitorGraph/'+FileName ordered = sorted(Data.iteritems(), key=operator.itemgetter(1), reverse=True) first3 = [] colors3 = [] for item in ordered: if (len(first3) < 3) and (item[0] in self.ProbeList): colors3.append(self.Colors[sorted(self.ProbeList).index(item[0])]) first3.append(item[1]) #ogni volta cerca di acquisire il lock per creare una nuova immagine, se non riesce, rompe il lock TempLock = FileLock(FileName) try: TempLock.acquire(timeout=Interval) except LockTimeout: TempLock.break_lock() else: cairoplot.vertical_bar_plot(FileName, first3, 170, 130, display_values=True, colors=colors3) TempLock.release()
def MakeGraph(self, Data, FileName): """ Funzione che produce un grafico temporale. :param Data: Serie di dati da dover graficare. :param FileName: Nome file da assegnare al grafico prodotto. :returns: *nulla* """ global Interval,TimeStep Markers=[] FileName = 'extra/MonitorGraph/'+FileName for x in range((TimeStep-1)*Interval,-1,-Interval): Markers.append(str(x)) #ogni volta cerca di acquisire il lock per creare una nuova immagine, se non riesce, rompe il lock TempLock = FileLock(FileName) try: TempLock.acquire(timeout=Interval) except LockTimeout: TempLock.break_lock() else: cairoplot.dot_line_plot(FileName, dict(zip(self.ProbeList,Data[:])), 600, 200, axis=True, grid=True, series_legend=False, x_labels=Markers, series_colors=self.Colors) TempLock.release()
def MakeGraphPercent(self, Data, FileName): """ Funzione che produce un grafico percentuale sotto forma di pieplot. :param Data: Dato da dover graficare. :param FileName: Nome file da assegnare al grafico prodotto. :returns: *nulla* """ global Interval Labels = ["%IN USO","TOT"] FileName = 'extra/MonitorGraph/'+FileName #print "**Data Graph**" #print Data #selezione della combinazione di colori per i grafici percentuali, a soglie [0,33],[34,66],[67,100] if (Data <= 33): PercentColors = ["lime","gray"] elif (Data <= 66): PercentColors = ["yellow","light_gray"] else : PercentColors = ["red","white"] Data = [int(Data),100-int(Data)] #ogni volta cerca di acquisire il lock per creare una nuova immagine, se non riesce, rompe il lock TempLock = FileLock(FileName) try: TempLock.acquire(timeout=Interval) except LockTimeout: TempLock.break_lock() else: cairoplot.pie_plot(FileName, dict(zip(Labels,Data)), 185, 130, colors = PercentColors) TempLock.release()
def daemonize(args, callback): with DaemonContext(): from Pyflix.utils.logger import log_set_up log_set_up(True) log = logging.getLogger('pyflix.daemon') log.info("running daemon") create_process = False lock = Lock(LOCKFILE, os.getpid(), args.name, args.sea_ep[0], args.sea_ep[1], args.port) if lock.is_locked(): log.debug("lock active") lock_pid = lock.get_pid() if not lock.is_same_file(args.name, args.sea_ep[0], args.sea_ep[1]) \ or not is_process_running(lock_pid): try: log.debug("killing process %s" % lock_pid) os.kill(lock_pid, signal.SIGQUIT) except OSError: pass except TypeError: pass lock.break_lock() create_process = True else: create_process = True if create_process: log.debug("creating proccess") lock.acquire() callback() lock.release() else: log.debug("same daemon process")
def main(argv=None): global argparser, lockfilepath global session, server, db if argv is None: args = argparser.parse_args() else: args = argparser.parse_args(argv) try: session, server, db = getCheshire3Env(args) except (EnvironmentError, ObjectDoesNotExistException): return 1 with db.get_path(session, 'defaultLogger') as session.logger: mp = db.get_path(session, 'metadataPath') lock = FileLock(mp) if lock.is_locked() and args.unlock: # Forcibly unlock session.logger.log_warning(session, "Unlocking Database") lock.break_lock() try: lock.acquire(timeout=30) # wait up to 30 seconds except LockTimeout: msg = ("The database is locked. It is possible that another" "user is currently indexing this database. Please wait at " "least 10 minutes and then try again. If you continue to " "get this message and you are sure no one is reindexing " "the database please contact the archives hub team for " "advice." ) session.logger.log_critical(session, msg) return 1 try: return args.func(args) finally: lock.release()
def getFileLock(location, filename): lock = FileLock("%s/%s" % (location, filename)) while not lock.i_am_locking(): try: lock.acquire(timeout=60) except: lock.break_lock() lock.acquire() return lock
def get_lock(): '''Get a file-lock, breaking the lock if it has been held for too long. :return: A lock, which may be locked. Use the :meth:`lockfile.FileLock.i_am_locking` method to find out if the lock is held, or not. :rtype: :class:`lockfile.FileLock` It is more than possible for Postfix to consume every single thread on the sever. By adding a lock, with a short timeout, we slow down the consumption of threads by the asynchronous email UI; this allows the Web UI to be responsive. We break the lock if the lock is very old because it is more than possible for something to crash with the lock taken. (It does assume that no email will take more than :const:`BREAK_LOCK_AGE` to process.) If the file is still locked, after we wait for something to finish and check that the lock is not too old, then we exit. Postfix will try running the script with the same arguments again later. **Example**:: from gs.group.messsages.add.smtp2gs import locker lock = locker.get_lock() if lock.i_am_locking(): # Do stuff. ''' # TODO: Use Redis for the locking # (We have the config for Redis in the config file) create_file(LOCK_NAME) # The following is a modification of the example from the lockfile # documentation <http://packages.python.org/lockfile/lockfile.html> lock = FileLock(LOCK_NAME) lock_file = LOCK_NAME + '.lock' if not lock.i_am_locking(): if (isfile(lock_file) and (age(lock_file) >= BREAK_LOCK_AGE)): lock.break_lock() try: lock.acquire(timeout=MAX_LOCK_TIMEOUT) except LockTimeout: pass return lock
def MakeLegend(self, FileName): """ Funzione che produce un'immagine con la legenda. :param FileName: Nome file da assegnare al risultato. :returns: *nulla* """ global Interval FileName = 'extra/MonitorGraph/'+FileName FakeValues = range(len(self.ProbeList)) #ogni volta cerca di acquisire il lock per creare una nuova immagine, se non riesce, rompe il lock TempLock = FileLock(FileName) try: TempLock.acquire(timeout=Interval) except LockTimeout: TempLock.break_lock() else: cairoplot.dot_line_plot(FileName, dict(zip(self.ProbeList,FakeValues)), 200, 10*len(self.ProbeList)+50, axis=False, grid=False, series_legend=True,series_colors=self.Colors) TempLock.release()
def send_all(): """ Send all eligible messages in the queue. """ lock = FileLock("send_mail") logging.debug("acquiring lock...") try: lock.acquire(LOCK_WAIT_TIMEOUT) except AlreadyLocked: logging.debug("lock already in place. quitting.") return except LockTimeout: if LOCK_WAIT_TIMEOUT == -1: logging.debug("waiting for the lock timed out. quitting.") return else: logging.debug("killing existing lock because of timeout.") lock.break_lock() logging.debug("acquired.") start_time = time.time() dont_send = 0 deferred = 0 sent = 0 try: connection = None for message in prioritize(): try: if connection is None: connection = get_connection(backend=EMAIL_BACKEND) logging.info( "sending message '%s' to %s" % (message.subject.encode("utf-8"), ", ".join(message.to_addresses)) ) email = message.email email.connection = connection email.send() MessageLog.objects.log(message, 1) # @@@ avoid using literal result code message.delete() sent += 1 except ( socket_error, smtplib.SMTPSenderRefused, smtplib.SMTPRecipientsRefused, smtplib.SMTPAuthenticationError, ), err: message.defer() logging.info("message deferred due to failure: %s" % err) MessageLog.objects.log(message, 3, log_message=str(err)) # @@@ avoid using literal result code deferred += 1 # Get new connection, it case the connection itself has an error. connection = None finally: logging.debug("releasing lock...") lock.release() logging.debug("released.") logging.info("") logging.info("%s sent; %s deferred;" % (sent, deferred)) logging.info("done in %.2f seconds" % (time.time() - start_time))
class MainWindow(): def __init__(self, CallMonitor, CallSetup, CallManager): #callbacks per Client e Server self.start_monitor = CallMonitor self.setup_monitor = CallSetup self.manager = CallManager #settaggio grafici self.RunFlag = False self.SetLocks() #costruzione GUI self.builder = Gtk.Builder() self.builder.add_from_file("src/MonitorGui.glade") #customu Colors per cairoplot self.color_counter = 0 dic = { "on_quit_button_press_event" : self.menu_quit, "on_MainWindow_delete_event" : self.request_quit, "on_MainWindow_destroy" : self.quit, "on_cpu_chart_draw" : self.show_cpu, "on_mem_chart_draw" : self.show_mem, "on_lat_chart_draw" : self.show_lat, "on_cpu_tot_stat_draw" : self.show_cpu_stat, "on_mem_tot_stat_draw" : self.show_mem_stat, "on_swp_tot_stat_draw" : self.show_swp_stat, "on_lat_tot_stat_draw" : self.show_lat_stat, "on_legend_chart_draw" : self.show_legend, "on_start_button_press" : self.start_monitoring, "on_about_dialog" : self.about_dialog, "show_something" : self.show_dialog, "hide_something" : self.hide_dialog, "set_something" : self.set_widget, "on_SendStress_pressed" : self.run_stress, "on_ProbeBox_config" : self.config_combo_probe, "on_ConfirmConfButton_press" : self.config_probe, "on_documentation_button_press" : self.open_doc, "on_SaveGraph_button_press" : self.save_graph, "on_refresh_button_press" : self.refresh_probe } self.builder.connect_signals(dic) self.window = self.builder.get_object("MainWindow") self.window.show() Gtk.main() #------------------------------------------------------------------------------- def SetLocks(self): """ Funzione di appoggio per settare i FileLock su tutti i grafici utilizzati. :returns: *nulla* """ thisRun = self.RunFlag self.CPUTempLock = FileLock(self.BuildFilePath(thisRun, "cpu.png")) self.MEMTempLock = FileLock(self.BuildFilePath(thisRun, "mem.png")) self.SWPTempLock = FileLock(self.BuildFilePath(thisRun, "swp.png")) self.LATTempLock = FileLock(self.BuildFilePath(thisRun, "lat.png")) self.LEGTempLock = FileLock(self.BuildFilePath(thisRun, "legenda.png")) self.CPUStatLock = FileLock(self.BuildFilePath(thisRun, "cpu_stat.png")) self.MEMStatLock = FileLock(self.BuildFilePath(thisRun, "mem_stat.png")) self.SWPStatLock = FileLock(self.BuildFilePath(thisRun, "swp_stat.png")) self.LATStatLock = FileLock(self.BuildFilePath(thisRun, "lat_stat.png")) #------------------------------------------------------------------------------- def BuildFilePath(self, ThisRun, FileName): """ In base al flag self.RunFlag decide come costruire il percorso del file desiderato. :param FileName: Nome del file desiderato. :returns: Il percorso completo del file da visualizzare nella GUI. """ if (ThisRun): FileNamePath = 'extra/MonitorGraph/'+FileName else: FileNamePath = 'extra/MonitorGraph/defaults/def_'+FileName return FileNamePath #------------------------------------------------------------------------------- def open_doc(self, widget, data=None): """ Funzione handler per aprire la documentazione. :returns: *nulla* """ webbrowser.open('file://'+os.path.abspath("./doc/build/html/index.html")) #------------------------------------------------------------------------------- def save_graph(self, widget, data=None): """ Funzione handler per il salvataggio dei grafici. :returns: *nulla* """ #un po' di pulizia prima di fare il salvataggio os.system("find ./extra/MonitorGraph/ -type f -not -name '*.png' | xargs rm -f") snapshotFile ="./extra/UserOutput/Snapshot"+time.strftime("%Y%m%d-%H%M", time.gmtime())+".tar" os.system("tar -cf "+snapshotFile+" --exclude def* --directory ./extra/ MonitorGraph/") print "Snapshot saved to",snapshotFile #------------------------------------------------------------------------------- def get_color(self, widget, data=None): """ Funzione handler per recuperare un colore nel formato utilizzato da cairoplot. :returns: *nulla* """ pygtk_color = widget.get_current_color() pygtk_color = pygtk_color.to_string() pygtk_red = int('0x'+pygtk_color[1:5],16) pygtk_green = int('0x'+pygtk_color[5:9],16) pygtk_blue = int('0x'+pygtk_color[9:12],16) cairo_color = '"custom-'+str(self.color_counter)+'"\t: (' cairo_color += str(round(float(pygtk_red/65535.),1)) cairo_color += (',') cairo_color += str(round(float(pygtk_green/65535.),1)) cairo_color += (',') cairo_color += str(round(float(pygtk_blue/65535.),1)) cairo_color += (',1.0)') print cairo_color self.color_counter += 1 #------------------------------------------------------------------------------- def refresh_probe(self, widget, data=None): """ Funzione handler per recuperare il controllo delle Probe che risultano ZOMBIE. :returns: *nulla* """ self.setup_monitor() #------------------------------------------------------------------------------- def config_probe(self, widget, data=None): """ Funzione handler per costruire il file di configurazione con i valori scelti dall'utente. :returns: *nulla* """ Configure.ExcludeServer = (int(self.builder.get_object("MasterRadio").get_active())) Configure.MaxNodes = (int(self.builder.get_object("NodeScale").get_value())) Configure.LocalhostOnly = (int(self.builder.get_object("LocalHostRadio").get_active())) Configure.TimeStep = (int(self.builder.get_object("TimeStepScale").get_value())) Configure.Interval = (int(self.builder.get_object("IntervalScale").get_value())) nomeFile = (str(self.builder.get_object("NameText").get_text())) if ('/' not in nomeFile) : Configure.SaveConfig(NewFile="./extra/UserOutput/"+nomeFile) else : Configure.SaveConfig(NewFile = nomeFile) print "### Sending setup signal to Monitor..." self.setup_monitor() #------------------------------------------------------------------------------- def config_combo_probe(self, widget, data=None): """ Funzione handler per presentare la lista delle Probe attualmente connesse al server. :returns: *nulla* """ ProbeList = self.manager.GetProbe() cbox = self.builder.get_object("ProbeBox") store = Gtk.ListStore(str) token = self.manager.GetToken() for item in ProbeList: if (not item.startswith(token)): store.append([item]) cbox.set_model(store) cell = Gtk.CellRendererText() cbox.clear() cbox.pack_start(cell, True) cbox.add_attribute(cell, 'text', 0) cbox.set_active(0) #------------------------------------------------------------------------------- def run_stress(self, widget, data=None): """ Funzione handler per il tasto di invio stress su di una Probe. Raccoglie i dati dalla lista delle Probe e dai bottoni di selezione per poi spedirli al server. :param widget: Gli passo la lista delle Probe per raccoglierne il nome selezionato. :returns: *nulla* """ CPUValue = self.builder.get_object("StressCPU") MEMValue = self.builder.get_object("StressMEM") self.manager.SetStress(widget.get_active(), CPUValue.get_active(), MEMValue.get_active()) #------------------------------------------------------------------------------- def set_widget(self, widget, data=None): """ Funzione handler *generico* setta il testo al widget fornito in ingresso. :param widget: Widget al quale devo settare il testo, tramite la funzione set_text() :returns: *nulla* """ if ('/' not in Configure.ConfigFile) : nomeFile = "./"+Configure.ConfigFile else : nomeFile = Configure.ConfigFile widget.set_text(nomeFile) #------------------------------------------------------------------------------- def hide_dialog(self, widget, data=None): """ Funzione handler *generico* setta come nascosto un widget fornito in ingresso. :param widget: Widget da nascondere, tramite la funzione hide() :returns: True """ widget.hide() return True #------------------------------------------------------------------------------- def about_dialog(self, widget, data=None): """ Funzione handler per la finestra di About. Lancia il dialog e controlla la risposta.m :param widget: Widget da lanciare con la funzione run() :returns: *nulla* """ response = widget.run() if (response < 0): widget.hide() #------------------------------------------------------------------------------- def show_dialog(self, widget, data): """ Funzione handler *generico* setta come visibile un widget fornito in ingresso. :param widget: Widget da mostrare, tramite la funzione show() :returns: *nulla* """ widget.show() #------------------------------------------------------------------------------- def start_monitoring(self, widget, data): """ Funzione handler per il tasto Avvia, sblocca la visualizzazione dei grafici. :returns: *nulla* """ #cambio le impostazioni dei locks self.RunFlag = True self.SetLocks() print "### Sending start signal to Monitor..." self.start_monitor() time.sleep(Configure.Interval) #------------------------------------------------------------------------------- def show_legend(self, image, data): """ Funzione handler per il tasto Legenda, mostra l'immagine della legenda. :returns: *nulla* """ try: self.LEGTempLock.acquire(timeout=2) except AlreadyLocked: pass except LockFailed: pass except LockTimeout: pass else: #print 'Got LEGlock for reading',Timeout image.set_from_file(self.LEGTempLock.path) self.LEGTempLock.release() time.sleep(Quiet) #------------------------------------------------------------------------------- def show_cpu(self, image, data): """ Funzione handler per l'evento show del grafico CPU temporale, aggiorna l'immagine. Cerca di acquisire il lock sull'immagine prima di leggerla, questo per evitare di mostrare un'immagine formata a metà mentre viene scritta dal Client. :param image: Il widget immagine dove dev'essere mostrata. :param Quiet: Tempo di attesa per evitare che si aggiornino di continuo. :returns: *nulla* """ try: self.CPUTempLock.acquire(timeout=2) except AlreadyLocked: pass except LockFailed: pass except LockTimeout: pass else: #print 'Got CPUlock for reading' image.set_from_file(self.CPUTempLock.path) self.CPUTempLock.release() time.sleep(Quiet) #------------------------------------------------------------------------------- def show_cpu_stat(self, image, data): """ Funzione handler per l'evento show del grafico CPU statistica, aggiorna l'immagine. Cerca di acquisire il lock sull'immagine prima di leggerla, questo per evitare di mostrare un'immagine formata a metà mentre viene scritta dal Client. :param image: Il widget immagine dove dev'essere mostrata. :param Quiet: Tempo di attesa per evitare che si aggiornino di continuo. :returns: *nulla* """ try: self.CPUStatLock.acquire(timeout=2) except AlreadyLocked: pass except LockFailed: pass except LockTimeout: pass else: #print 'Got CPUStatlock for reading' image.set_from_file(self.CPUStatLock.path) self.CPUStatLock.release() time.sleep(Quiet) #------------------------------------------------------------------------------- def show_mem_stat(self, image, data): """ Funzione handler per l'evento show del grafico Memoria statistica, aggiorna l'immagine. Cerca di acquisire il lock sull'immagine prima di leggerla, questo per evitare di mostrare un'immagine formata a metà mentre viene scritta dal Client. :param image: Il widget immagine dove dev'essere mostrata. :param Quiet: Tempo di attesa per evitare che si aggiornino di continuo. :returns: *nulla* """ try: self.MEMStatLock.acquire(timeout=2) except AlreadyLocked: pass except LockFailed: pass except LockTimeout: pass else: #print 'Got CPUStatlock for reading' image.set_from_file(self.MEMStatLock.path) self.MEMStatLock.release() time.sleep(Quiet) #------------------------------------------------------------------------------- def show_swp_stat(self, image, data): """ Funzione handler per l'evento show del grafico Swap statistica, aggiorna l'immagine. Cerca di acquisire il lock sull'immagine prima di leggerla, questo per evitare di mostrare un'immagine formata a metà mentre viene scritta dal Client. :param image: Il widget immagine dove dev'essere mostrata. :param Quiet: Tempo di attesa per evitare che si aggiornino di continuo. :returns: *nulla* """ try: self.SWPStatLock.acquire(timeout=2) except AlreadyLocked: pass except LockFailed: pass except LockTimeout: pass else: #print 'Got CPUStatlock for reading' image.set_from_file(self.SWPStatLock.path) self.SWPStatLock.release() time.sleep(Quiet) #------------------------------------------------------------------------------- def show_lat_stat(self, image, data): """ Funzione handler per l'evento show del grafico Latenza statistica, aggiorna l'immagine. Cerca di acquisire il lock sull'immagine prima di leggerla, questo per evitare di mostrare un'immagine formata a metà mentre viene scritta dal Client. :param image: Il widget immagine dove dev'essere mostrata. :param Quiet: Tempo di attesa per evitare che si aggiornino di continuo. :returns: *nulla* """ try: self.LATStatLock.acquire(timeout=2) except AlreadyLocked: pass except LockFailed: pass except LockTimeout: pass else: #print 'Got CPUStatlock for reading' image.set_from_file(self.LATStatLock.path) self.LATStatLock.release() time.sleep(Quiet) #------------------------------------------------------------------------------- def show_mem(self, image, data): """ Funzione handler per l'evento show del grafico Memoria temporale, aggiorna l'immagine. Cerca di acquisire il lock sull'immagine prima di leggerla, questo per evitare di mostrare un'immagine formata a metà mentre viene scritta dal Client. :param image: Il widget immagine dove dev'essere mostrata. :param Quiet: Tempo di attesa per evitare che si aggiornino di continuo. :returns: *nulla* """ try: self.MEMTempLock.acquire(timeout=2) except AlreadyLocked: pass except LockFailed: pass except LockTimeout: pass else: #print 'Got MEMlock for reading' image.set_from_file(self.MEMTempLock.path) self.MEMTempLock.release() time.sleep(Quiet) #------------------------------------------------------------------------------- def show_lat(self, image, data): """ Funzione handler per l'evento show del grafico Latenza temporale, aggiorna l'immagine. Cerca di acquisire il lock sull'immagine prima di leggerla, questo per evitare di mostrare un'immagine formata a metà mentre viene scritta dal Client. :param image: Il widget immagine dove dev'essere mostrata. :param Quiet: Tempo di attesa per evitare che si aggiornino di continuo. :returns: *nulla* """ try: self.LATTempLock.acquire(timeout=2) except AlreadyLocked: pass except LockFailed: pass except LockTimeout: pass else: #print 'Got SWPlock for reading' image.set_from_file(self.LATTempLock.path) self.LATTempLock.release() time.sleep(Quiet) #------------------------------------------------------------------------------- def menu_quit (self,widget,data): """ Funzione handler per il tasto Esci, scatena l'evento delete sulla main window. :returns: *nulla* """ self.window.delete_event() #------------------------------------------------------------------------------- def request_quit(self, widget, data): """ Funzione handler per l'evento delete della main window, mostra un messaggio di richiesta di conferma. :returns: ``True`` se si richiede di propagare il segnale al destroy. :returns: ``False`` se non è necessario passare al destroy. """ MainWin = self.builder.get_object("MainWindow") dialog = Gtk.MessageDialog(MainWin, 0, Gtk.MessageType.WARNING, Gtk.ButtonsType.OK_CANCEL, "Sei sicuro di voler uscire?") dialog.format_secondary_text("Il segnale di chiusura verrà automaticamente propagato. ") response = dialog.run() if response == Gtk.ResponseType.OK: print "### Closing up..." self.manager.ShutDown() dialog.destroy() return(False) elif response == Gtk.ResponseType.CANCEL: dialog.destroy() return (True) #------------------------------------------------------------------------------- def quit(self, widget): """ Funzione handler per il segnale destroy della main window, rompe i lock e chiude. :returns: *nulla*. """ print ">> Releasing locked resources..." self.CPUTempLock.break_lock() self.MEMTempLock.break_lock() self.SWPTempLock.break_lock() self.LATTempLock.break_lock() self.LEGTempLock.break_lock() self.CPUStatLock.break_lock() self.MEMStatLock.break_lock() self.SWPStatLock.break_lock() self.LATStatLock.break_lock() #sys.exit(0) Gtk.main_quit()