Skip to content

Commit

Permalink
🔀 Merge pull request #1 from bioinformatics-ptp/python3
Browse files Browse the repository at this point in the history
✨ support kvmBackup with python3
  • Loading branch information
bunop authored Feb 8, 2022
2 parents 5aa8677 + 64ec1b8 commit 008d91f
Show file tree
Hide file tree
Showing 8 changed files with 534 additions and 276 deletions.
99 changes: 96 additions & 3 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ __pycache__/

# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
Expand All @@ -20,9 +19,12 @@ lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
Expand All @@ -37,26 +39,117 @@ pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*,cover
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock

# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm
# JetBrains specific template is maintainted in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/

# backup files
*~

10 changes: 5 additions & 5 deletions Lib/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"""
kvmBackup - a software for snapshotting KVM images and backing them up
Copyright (C) 2015-2016 PTP
Copyright (C) 2015-2022 Paolo Cozzi
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
Expand All @@ -19,12 +19,12 @@
Created on Wed Oct 21 13:56:55 2015
@author: Paolo Cozzi <paolo.cozzi@ptp.it>
@author: Paolo Cozzi <bunop@libero.it>
"""

import helper
import flock
from . import helper
from . import flock

__author__ = "Paolo Cozzi"
__version__ = "1.0"
__version__ = "1.1"
__all__ = ["helper", "flock"]
68 changes: 40 additions & 28 deletions Lib/flock.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"""
kvmBackup - a software for snapshotting KVM images and backing them up
Copyright (C) 2015-2016 PTP
Copyright (C) 2015-2022 Paolo Cozzi
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
Expand All @@ -19,37 +19,45 @@
Created on Wed Oct 21 13:08:56 2015
@author: Paolo Cozzi <paolo.cozzi@ptp.it>
@author: Paolo Cozzi <bunop@libero.it>
Simple lockfile to detect previous instances of app (Python recipe http://code.activestate.com/recipes/498171/)
Simple lockfile to detect previous instances of app (Python recipe
http://code.activestate.com/recipes/498171/)
"""

from __future__ import print_function

import logging
import os
import socket
import logging

# Logging istance
logger = logging.getLogger(__name__)


class flock(object):
'''Class to handle creating and removing (pid) lockfiles'''

# custom exceptions
class FileLockAcquisitionError(Exception): pass
class FileLockReleaseError(Exception): pass
class FileLockAcquisitionError(Exception):
pass

class FileLockReleaseError(Exception):
pass

# convenience callables for formatting
addr = lambda self: '%d@%s' % (self.pid, self.host)
fddr = lambda self: '<%s %s>' % (self.path, self.addr())
pddr = lambda self, lock: '<%s %s@%s>' %\
(self.path, lock['pid'], lock['host'])
def addr(self): return '%d@%s' % (self.pid, self.host)
def fddr(self): return '<%s %s>' % (self.path, self.addr())

def pddr(self, lock): return '<%s %s@%s>' %\
(self.path, lock['pid'], lock['host'])

def __init__(self, path, debug=None):
self.pid = os.getpid()
self.host = socket.gethostname()
self.path = path
self.debug = debug # set this to get status messages
self.pid = os.getpid()
self.host = socket.gethostname()
self.path = path
self.debug = debug # set this to get status messages

def acquire(self):
'''Acquire a lock, returning self if successful, False otherwise'''
Expand All @@ -64,11 +72,13 @@ def acquire(self):
fh.close()
if self.debug:
logger.debug('Acquired lock: %s' % self.fddr())
except:

# TODO: catch the proper exception
except Exception:
if os.path.isfile(self.path):
try:
os.unlink(self.path)
except:
except Exception:
pass
raise (self.FileLockAcquisitionError,
'Error acquiring lock: %s' % self.fddr())
Expand All @@ -81,7 +91,7 @@ def release(self):
os.unlink(self.path)
if self.debug:
logger.debug('Released lock: %s' % self.fddr())
except:
except Exception:
raise (self.FileLockReleaseError,
'Error releasing lock: %s' % self.fddr())
return self
Expand All @@ -90,12 +100,12 @@ def _readlock(self):
'''Internal method to read lock info'''
try:
lock = {}
fh = open(self.path)
fh = open(self.path)
data = fh.read().rstrip().split('@')
fh.close()
lock['pid'], lock['host'] = data
return lock
except:
except Exception:
return {'pid': 8**10, 'host': ''}

def islocked(self):
Expand All @@ -104,7 +114,7 @@ def islocked(self):
lock = self._readlock()
os.kill(int(lock['pid']), 0)
return (lock['host'] == self.host)
except:
except Exception:
return False

def ownlock(self):
Expand All @@ -116,26 +126,28 @@ def __del__(self):
'''Magic method to clean up lock when program exits'''
self.release()

## ========
# ========

# Test programs: run test1.py then test2.py (in the same dir)
# from another teminal -- test2.py should print
# a message that there is a lock in place and exit.

## Test programs: run test1.py then test2.py (in the same dir)
## from another teminal -- test2.py should print
## a message that there is a lock in place and exit.

if __name__ == "__main__":
# test1.py
from time import sleep
#from flock import flock

# from flock import flock
lock = flock('tmp.lock', True).acquire()
if lock:
sleep(30)
else:
print 'locked!'
print('locked!')

# test2.py
from flock import flock
lock = flock('tmp.lock', True).acquire()
if lock:
print 'doing stuff'
print('doing stuff')
else:
print 'locked!'
print('locked!')
Loading

0 comments on commit 008d91f

Please sign in to comment.