Skip to content

Commit

Permalink
refactor: SnapshotMessages
Browse files Browse the repository at this point in the history
  • Loading branch information
buhtz committed Feb 26, 2024
1 parent 4da45e1 commit ed282ad
Show file tree
Hide file tree
Showing 4 changed files with 80 additions and 48 deletions.
13 changes: 9 additions & 4 deletions common/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -1373,21 +1373,26 @@ def setGlobalFlock(self, value):
def appInstanceFile(self):
return os.path.join(self._LOCAL_DATA_FOLDER, 'app.lock')

def fileId(self, profile_id = None):
def fileId(self, profile_id=None):
if profile_id is None:
profile_id = self.currentProfile()

if profile_id == '1':
return ''

return profile_id

def takeSnapshotLogFile(self, profile_id = None):
return os.path.join(self._LOCAL_DATA_FOLDER, "takesnapshot_%s.log" % self.fileId(profile_id))
return os.path.join(self._LOCAL_DATA_FOLDER,
"takesnapshot_%s.log" % self.fileId(profile_id))

def takeSnapshotMessageFile(self, profile_id = None):
return os.path.join(self._LOCAL_DATA_FOLDER, "worker%s.message" % self.fileId(profile_id))
return os.path.join(self._LOCAL_DATA_FOLDER,
"worker%s.message" % self.fileId(profile_id))

def takeSnapshotProgressFile(self, profile_id = None):
return os.path.join(self._LOCAL_DATA_FOLDER, "worker%s.progress" % self.fileId(profile_id))
return os.path.join(self._LOCAL_DATA_FOLDER,
"worker%s.progress" % self.fileId(profile_id))

def takeSnapshotInstanceFile(self, profile_id=None):
return os.path.join(
Expand Down
6 changes: 3 additions & 3 deletions common/diagnostics.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,8 +199,8 @@ def collect_diagnostics():
def _get_qt_information():
"""Collect Version and Theme information from Qt.
If environment variable DISPLAY is set a temporary QApplication instances
is created.
If environment variable ``DISPLAY`` is set a temporary QApplication
instances is created.
"""
try:
import PyQt6.QtCore
Expand Down Expand Up @@ -302,7 +302,7 @@ def _get_os_release():
First it extract infos from the file ``/etc/os-release``. Because not all
GNU Linux distributions follow the standards it will also look for
alternative release files (pattern: /etc/*release).
alternative release files (pattern: ``/etc/*release``).
See http://linuxmafia.com/faq/Admin/release-files.html for examples.
Returns:
Expand Down
100 changes: 60 additions & 40 deletions common/snapshots.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

import json
import os
import pathlib
from pathlib import Path
import stat
import datetime
import gettext
Expand Down Expand Up @@ -79,56 +79,73 @@ def __init__(self, cfg = None):
r'([\d\?]+:[\d\?]{2}:[\d\?]{2})' #estimated time of arrival
r'(.*$)') #trash at the end

self.lastBusyCheck = datetime.datetime(1,1,1)
self.lastBusyCheck = datetime.datetime(1, 1, 1)
self.flock = None
self.restorePermissionFailed = False

#TODO: make own class for takeSnapshotMessage
# TODO: make own class for takeSnapshotMessage
def clearTakeSnapshotMessage(self):
files = (self.config.takeSnapshotMessageFile(), \
self.config.takeSnapshotProgressFile())
for f in files:
if os.path.exists(f):
os.remove(f)
"""Delete message and progress file"""
Path(self.config.takeSnapshotMessageFile()).unlink(missing_ok=True)
Path(self.config.takeSnapshotProgressFile()).unlink(missing_ok=True)

#TODO: make own class for takeSnapshotMessage
# TODO: make own class for takeSnapshotMessage
def takeSnapshotMessage(self):
wait = datetime.datetime.now() - datetime.timedelta(seconds = 5)
"""Get the current message from the message file.
Returns:
(tuple(int, str)): The message type and its string or `None`. See
`setTakeSnapshotMessage()` for further details.
Dev note (buhtz):
Too many try..excepts in here.
"""
# Dev note (buhtz): Not sure what happens here or why this is usefull.
wait = datetime.datetime.now() - datetime.timedelta(seconds=5)

if self.lastBusyCheck < wait:
self.lastBusyCheck = datetime.datetime.now()

if not self.busy():
self.clearTakeSnapshotMessage()

return None

if not os.path.exists(self.config.takeSnapshotMessageFile()):
# Filename of the message file
message_fn = self.config.takeSnapshotMessageFile()

if not os.path.exists(message_fn):
return None

try:
with open(self.config.takeSnapshotMessageFile(), 'rt') as f:
items = f.read().split('\n')
except Exception as e:
logger.debug('Failed to get takeSnapshot message from %s: %s'
%(self.config.takeSnapshotMessageFile(), str(e)),
self)
with open(message_fn, 'rt') as handle:
items = handle.read().split('\n')

# TODO (buhtz): Too broad exception
except Exception as exc:
logger.debug('Failed to get takeSnapshot message from '
f'{message_fn}: {str(exc)}', self)

return None

if len(items) < 2:
return None

# "Message id": Type of the message.
mid = 0

try:
mid = int(items[0])
except Exception as e:
logger.debug('Failed to extract message ID from %s: %s'
%(items[0], str(e)),
self)

del items[0]
message = '\n'.join(items)
# TODO (buhtz): Too broad exception
except Exception as exc:
logger.debug('Failed to extract message ID from '
f'{items}: {str(exc)}', self)

return(mid, message)
return (mid, '\n'.join(items[1:]))

# TODO: make own class for takeSnapshotMessage
def setTakeSnapshotMessage(self, type_id, message, timeout = -1):
def setTakeSnapshotMessage(self, type_id, message, timeout=-1):
"""Update the status message of the active snapshot creation job
Write the status message into a message file to allow async
Expand All @@ -148,29 +165,32 @@ def setTakeSnapshotMessage(self, type_id, message, timeout = -1):
In fact currently all known plug-ins do
ignore the timeout value!
"""
data = str(type_id) + '\n' + message

message_fn = self.config.takeSnapshotMessageFile()

try:
with open(self.config.takeSnapshotMessageFile(), 'wt') as f:
f.write(data)
except Exception as e:
logger.debug('Failed to set takeSnapshot message to %s: %s'
%(self.config.takeSnapshotMessageFile(), str(e)),
self)
# Write message to file (and overwrites the previos one)
with open(message_fn, 'wt') as f:
f.write(str(type_id) + '\n' + message)

except Exception as exc:
logger.debug('Failed to set takeSnapshot message '
f'to {message_fn}: {str(exc)}', self)

if 1 == type_id:
# Error message?
if type_id == 1:
self.snapshotLog.append('[E] ' + message, 1)
else:
self.snapshotLog.append('[I] ' + message, 3)
self.snapshotLog.append('[I] ' + message, 3)

try:
profile_id =self.config.currentProfile()
profile_id = self.config.currentProfile()
profile_name = self.config.profileName(profile_id)
self.config.PLUGIN_MANAGER.message(profile_id, profile_name, type_id, message, timeout)
except Exception as e:
logger.debug('Failed to send message to plugins: %s'
%str(e),
self)
self.config.PLUGIN_MANAGER.message(
profile_id, profile_name, type_id, message, timeout)

except Exception as exc:
logger.debug(f'Failed to send message to plugins: {str(exc)}', self)

def busy(self):
instance = ApplicationInstance(self.config.takeSnapshotInstanceFile(), False)
Expand Down
9 changes: 8 additions & 1 deletion qt/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -921,7 +921,14 @@ def raiseApplication(self):
logger.debug("Raise cmd: %s" %raiseCmd, self)
self.qapp.alert(self)

def updateTakeSnapshot(self, force_wait_lock = False):
def updateTakeSnapshot(self, force_wait_lock=False):
"""Update the statusbar and progress indicator with latest message
from the snapshot message file.
This method is called via a timeout event. See
`self.timerUpdateTakeSnapshot`. Also see
`Snapshots.takeSnapshotMessage()` for further details.
"""
if force_wait_lock:
self.forceWaitLockCounter = 10

Expand Down

0 comments on commit ed282ad

Please sign in to comment.