Completed
Push — master ( 422e90...9c87d7 )
by Juan José
17s queued 13s
created

ospd_openvas.lock.LockFile.__exit__()   A

Complexity

Conditions 1

Size

Total Lines 2
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nop 4
dl 0
loc 2
rs 10
c 0
b 0
f 0
1
# -*- coding: utf-8 -*-
2
# Copyright (C) 2020 Greenbone Networks GmbH
3
#
4
# SPDX-License-Identifier: GPL-2.0-or-later
5
#
6
# This program is free software; you can redistribute it and/or
7
# modify it under the terms of the GNU General Public License
8
# as published by the Free Software Foundation; either version 2
9
# of the License, or (at your option) any later version.
10
#
11
# This program is distributed in the hope that it will be useful,
12
# but WITHOUT ANY WARRANTY; without even the implied warranty of
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
# GNU General Public License for more details.
15
#
16
# You should have received a copy of the GNU General Public License
17
# along with this program; if not, write to the Free Software
18
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19
20
import logging
21
import time
22
23
from pathlib import Path
24
25
logger = logging.getLogger(__name__)
26
27
28
class LockFile:
29
    def __init__(self, path: Path):
30
        self._lock_file_path = path
31
        self._has_lock = False
32
33
    def is_locked(self) -> bool:
34
        return self._lock_file_path.exists()
35
36
    def has_lock(self) -> bool:
37
        return self._has_lock
38
39
    def acquire_lock(self) -> "LockFile":
40
        """ Acquite a lock by creating a lock file.
41
        """
42
        if self.has_lock() or self.is_locked():
43
            return self
44
45
        try:
46
            # create parent directories recursively
47
            parent_dir = self._lock_file_path.parent
48
            parent_dir.mkdir(parents=True, exist_ok=True)
49
50
            self._lock_file_path.touch(exist_ok=False)
51
            self._has_lock = True
52
53
            logger.debug("Created lock file %s.", str(self._lock_file_path))
54
55
        except FileExistsError as e:
56
            logger.error(
57
                "Failed to create lock file %s. %s",
58
                str(self._lock_file_path),
59
                e,
60
            )
61
62
        return self
63
64
    def wait_for_lock(self):
65
        while not self.has_lock():
66
            self.acquire_lock()
67
            time.sleep(10)
68
69
        return self
70
71
    def release_lock(self) -> None:
72
        """ Release the lock by deleting the lock file
73
        """
74
        if self.has_lock() and self.is_locked():
75
            self._lock_file_path.unlink()
76
            self._has_lock = False
77
            logger.debug("Removed lock file %s.", str(self._lock_file_path))
78
79
    def __enter__(self):
80
        self.acquire_lock()
81
        return self
82
83
    def __exit__(self, exc_type, exc_value, exc_tb):
84
        self.release_lock()
85