| 1 |
# SPDX-FileCopyrightText: 2022-2024 Greenbone AG |
| 2 |
# |
| 3 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 4 |
# |
| 5 |
|
| 6 |
import asyncio |
| 7 |
import errno |
| 8 |
import fcntl |
| 9 |
import os |
| 10 |
import shutil |
| 11 |
from contextlib import asynccontextmanager |
| 12 |
from pathlib import Path |
| 13 |
from types import TracebackType |
| 14 |
from typing import AsyncGenerator, Optional, Type, Union |
| 15 |
|
| 16 |
from rich.console import Console |
| 17 |
from rich.live import Live |
| 18 |
from rich.spinner import Spinner as RichSpinner |
| 19 |
|
| 20 |
from greenbone.feed.sync.errors import FileLockingError, GreenboneFeedSyncError |
| 21 |
|
| 22 |
DEFAULT_FLOCK_WAIT_INTERVAL = 5 # in seconds |
| 23 |
|
| 24 |
|
| 25 |
def is_root() -> bool: |
| 26 |
""" |
| 27 |
Checks if the current user is root |
| 28 |
""" |
| 29 |
return os.geteuid() == 0 |
| 30 |
|
| 31 |
|
| 32 |
@asynccontextmanager |
| 33 |
async def flock_wait( |
| 34 |
path: Union[str, Path], |
| 35 |
*, |
| 36 |
console: Optional[Console] = None, |
| 37 |
wait_interval: Optional[Union[int, float]] = DEFAULT_FLOCK_WAIT_INTERVAL, |
| 38 |
) -> AsyncGenerator[None, None]: |
| 39 |
""" |
| 40 |
Try to lock a file and wait if it is already locked |
| 41 |
|
| 42 |
Arguments: |
| 43 |
path: File to lock |
| 44 |
console: A console to print messages to or None to keep the function |
| 45 |
quiet. |
| 46 |
wait_interval: Time to wait in seconds after failed lock attempt before |
| 47 |
re-trying to lock the file. Set to None to raise a FileLockingError |
| 48 |
instead of re-trying to acquire the lock. Default is 5 seconds. |
| 49 |
""" |
| 50 |
# ensure path is a Path |
| 51 |
path = Path(path) |
| 52 |
|
| 53 |
# ensure parent directories exist |
| 54 |
try: |
| 55 |
path.parent.mkdir(parents=True, exist_ok=True, mode=0o770) |
| 56 |
except OSError as e: |
| 57 |
raise FileLockingError( |
| 58 |
f"Could not create parent directories for {path}" |
| 59 |
) from e |
| 60 |
|
| 61 |
try: |
| 62 |
with path.open("w", encoding="utf8") as fd0: |
| 63 |
has_lock = False |
| 64 |
while not has_lock: |
| 65 |
try: |
| 66 |
if console: |
| 67 |
console.print( |
| 68 |
f"Trying to acquire lock on {path.absolute()}" |
| 69 |
) |
| 70 |
|
| 71 |
fcntl.flock(fd0, fcntl.LOCK_EX | fcntl.LOCK_NB) |
| 72 |
|
| 73 |
if console: |
| 74 |
console.print(f"Acquired lock on {path.absolute()}") |
| 75 |
|
| 76 |
has_lock = True |
| 77 |
path.chmod(mode=0o660) |
| 78 |
except OSError as e: |
| 79 |
if e.errno in (errno.EAGAIN, errno.EACCES): |
| 80 |
if wait_interval is None: |
| 81 |
raise FileLockingError( |
| 82 |
f"{path.absolute()} is locked. Another process " |
| 83 |
"related to the feed update may already running." |
| 84 |
) from None |
| 85 |
|
| 86 |
if console: |
| 87 |
console.print( |
| 88 |
f"{path.absolute()} is locked by another process. " |
| 89 |
f"Waiting {wait_interval} seconds before next try." |
| 90 |
) |
| 91 |
await asyncio.sleep(wait_interval) |
| 92 |
else: |
| 93 |
raise |
| 94 |
|
| 95 |
try: |
| 96 |
yield |
| 97 |
finally: |
| 98 |
try: |
| 99 |
# free the lock |
| 100 |
if console: |
| 101 |
console.print(f"Releasing lock on {path.absolute()}") |
| 102 |
|
| 103 |
fcntl.flock(fd0, fcntl.LOCK_UN) |
| 104 |
except OSError: |
| 105 |
pass |
| 106 |
except PermissionError as e: |
| 107 |
raise FileLockingError( |
| 108 |
"Permission error while trying to open the lock file " |
| 109 |
f"{path.absolute()}" |
| 110 |
) from e |
| 111 |
|
| 112 |
|
| 113 |
class Spinner: |
| 114 |
def __init__(self, console: Console, status: str) -> None: |
| 115 |
self._spinner = RichSpinner( |
| 116 |
"dots", text=status, style="status.spinner", speed=1.0 |
| 117 |
) |
| 118 |
self._live = Live( |
| 119 |
self._spinner, |
| 120 |
console=console, |
| 121 |
refresh_per_second=12.5, |
| 122 |
transient=False, |
| 123 |
) |
| 124 |
|
| 125 |
def __enter__(self) -> "Spinner": |
| 126 |
self._live.start() |
| 127 |
return self |
| 128 |
|
| 129 |
def __exit__( |
| 130 |
self, |
| 131 |
exc_type: Optional[Type[BaseException]], |
| 132 |
exc_val: Optional[BaseException], |
| 133 |
exc_tb: Optional[TracebackType], |
| 134 |
) -> None: |
| 135 |
self._live.stop() |
| 136 |
|
| 137 |
|
| 138 |
def change_user_and_group( |
| 139 |
user: Union[str, int], group: Union[str, int] |
| 140 |
) -> None: |
| 141 |
""" |
| 142 |
Change effective user or group of the current running process |
| 143 |
|
| 144 |
Args: |
| 145 |
user: User name or ID |
| 146 |
group: Group name or ID |
| 147 |
""" |
| 148 |
if isinstance(user, str): |
| 149 |
user_id = shutil._get_uid( # type: ignore[attr-defined] # pylint: disable=protected-access # noqa: E501 |
| 150 |
user |
| 151 |
) |
| 152 |
if user_id is None: |
| 153 |
raise GreenboneFeedSyncError( |
| 154 |
f"Can't run as user '{user}'. User '{user}' is unknown." |
| 155 |
) |
| 156 |
user = user_id |
| 157 |
if isinstance(group, str): |
| 158 |
group_id = shutil._get_gid(group) # type: ignore[attr-defined] # pylint: disable=protected-access # noqa: E501 |
| 159 |
if group_id is None: |
| 160 |
raise GreenboneFeedSyncError( |
| 161 |
f"Can't run as group '{group}'. Group '{group}' is unknown." |
| 162 |
) |
| 163 |
group = group_id |
| 164 |
|
| 165 |
os.setegid(group) # type: ignore[arg-type] |
| 166 |
os.seteuid(user) # type: ignore[arg-type] |