Skip to content

Commit

Permalink
Updated check/install function for urbackup
Browse files Browse the repository at this point in the history
  • Loading branch information
judahpaul16 committed Apr 28, 2024
1 parent 3b8a213 commit 1403940
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 18 deletions.
27 changes: 15 additions & 12 deletions dirconfig/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,8 @@ def signal_handler(signum, frame):
os.remove(PID_FILE)
sys.exit(0)

def get_urbackup_command():
if os.name == 'nt': # Windows
def get_urbackup_command(os_name=None):
if os.name == 'nt' and os_name != 'Linux': # Windows
return 'urbackupclient_cmd'
else: # Linux or macOS
return 'urbackupclientctl'
Expand All @@ -93,7 +93,7 @@ def add_to_path(new_path_entry):
[Environment]::SetEnvironmentVariable("PATH", $newPath, "User");
Write-Output 'Added to PATH'
}}
"""
""".replace('\n', ' ').replace(' ', '')
try:
# Execute the PowerShell command
result = subprocess.run(["powershell", "-Command", powershell_command], capture_output=True, text=True)
Expand All @@ -107,25 +107,28 @@ def add_to_path(new_path_entry):
print(f"An error occurred: {e}")
logging.error(f"An error occurred: {str(e)}")

def get_installer_filename(os_type):
return "urbackup_client_installer" + (".exe" if os_type.lower() is installer_os.Windows else ".sh")

def check_and_install_urbackup_client(backup_config):
stdout, stderr, returncode = subprocess.run([get_urbackup_command(), "status"], capture_output=True, text=True)
if returncode != 0:
result = subprocess.run([get_urbackup_command(), "status"], capture_output=True, text=True)
if result.returncode != 0:
print("UrBackup client not running. Attempting installation...")
logging.info("UrBackup client not running. Attempting installation...")
# Determine OS type for choosing the correct installer
os_type = installer_os.Linux if os.name != 'nt' else installer_os.Windows
installer_filename = "urbackup_client_installer" + (".exe" if os_type == installer_os.Windows else ".sh")
os_type = "Linux" if os.name != 'nt' else "Windows"
installer_filename = get_installer_filename(os_type)
backup_server = urbackup_server(
server_url=backup_config['connection']['server'],
server_username=backup_config['connection']['username'],
server_password=backup_config['connection']['password']
url=backup_config['connection']['server'],
username=backup_config['connection']['username'],
password=backup_config['connection']['password']
)
if backup_server.login():
client_name = f"{backup_config['name']}-dirconfig"
if backup_server.download_installer(installer_filename, client_name, os_type):
if os_type != 'Windows':
if os_type != "Windows":
subprocess.run(["chmod", "+x", installer_filename]) # Make executable on Unix/Linux
subprocess.run([os.path.join(MODULE_DIR, '{installer_filename}')]) # Execute installer
subprocess.run([os.path.join(MODULE_DIR, installer_filename)]) # Execute installer
# Add urbackupclientctl to PATH if Windows
if os_type == 'Windows':
add_to_path('C:\\Program Files\\UrBackup\\')
Expand Down
73 changes: 67 additions & 6 deletions tests/test_urbackup.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@
from unittest.mock import patch, MagicMock, create_autospec, call
import subprocess
import unittest
from unittest.mock import patch, MagicMock
from dirconfig import backup_task, initiate_backup, check_and_install_urbackup_client, setup_backup_dirs, get_urbackup_command
import os

from dirconfig import \
backup_task, \
initiate_backup, \
check_and_install_urbackup_client, \
setup_backup_dirs, \
get_urbackup_command, \
get_installer_filename, \
MODULE_DIR


class TestBackupFunctions(unittest.TestCase):
def setUp(self):
Expand All @@ -15,11 +26,61 @@ def setUp(self):
'type': 'incremental-file'
}

@patch('dirconfig.subprocess.run')
def test_check_and_install_urbackup_client(self, mock_run):
mock_run.return_value = {'stdout': "Client installed.", 'stderr': "", 'returncode': 0}
@patch('os.name', 'nt')
@patch('subprocess.run')
@patch('dirconfig.get_installer_filename', return_value='urbackup_client_installer.exe')
@patch('dirconfig.get_urbackup_command', return_value='urbackupclient_cmd')
@patch('urbackup.urbackup_server.login', return_value=True)
@patch('urbackup.urbackup_server.download_installer', return_value=True)
def test_check_and_install_urbackup_client_windows(self, mock_download_installer, mock_login, mock_get_urbackup_command, mock_get_installer_filename, mock_run):
mock_completed_process = create_autospec(subprocess.CompletedProcess, instance=True)
mock_completed_process.stdout = "Client not installed"
mock_completed_process.stderr = ""
mock_completed_process.returncode = 1
mock_run.return_value = mock_completed_process

check_and_install_urbackup_client(self.backup_config)

powershell_command = """
$newPathEntry = 'C:\\Program Files\\UrBackup\\';
$envPath = [Environment]::GetEnvironmentVariable("PATH", "User");
if ($envPath -split ';' -contains $newPathEntry) {
Write-Output 'Already in PATH'
} else {
$newPath = $envPath + ';' + $newPathEntry;
[Environment]::SetEnvironmentVariable("PATH", $newPath, "User");
Write-Output 'Added to PATH'
}
""".replace('\n', ' ').replace(' ', '')

expected_calls = [
call([mock_get_urbackup_command(), "status"], capture_output=True, text=True),
call([os.path.join(MODULE_DIR, mock_get_installer_filename())]),
call(['powershell', '-Command', powershell_command], capture_output=True, text=True),
]
mock_run.assert_has_calls(expected_calls, any_order=True)

@patch('os.name', 'posix')
@patch('subprocess.run')
@patch('dirconfig.get_installer_filename', return_value='urbackup_client_installer.sh')
@patch('dirconfig.get_urbackup_command', return_value='urbackupclientctl')
@patch('urbackup.urbackup_server.login', return_value=True)
@patch('urbackup.urbackup_server.download_installer', return_value=True)
def test_check_and_install_urbackup_client_posix(self, mock_download_installer, mock_login, mock_get_urbackup_command, mock_get_installer_filename, mock_run):
mock_completed_process = create_autospec(subprocess.CompletedProcess, instance=True)
mock_completed_process.stdout = "Client not installed"
mock_completed_process.stderr = ""
mock_completed_process.returncode = 1
mock_run.return_value = mock_completed_process

check_and_install_urbackup_client(self.backup_config)
mock_run.assert_called_with([get_urbackup_command(), "status"], capture_output=True, text=True)

expected_calls = [
call([mock_get_urbackup_command(), "status"], capture_output=True, text=True),
call(['chmod', '+x', mock_get_installer_filename()]),
call([os.path.join(MODULE_DIR, mock_get_installer_filename())]),
]
mock_run.assert_has_calls(expected_calls, any_order=True)

@patch('dirconfig.subprocess.run')
def test_setup_backup_dirs(self, mock_run):
Expand Down

0 comments on commit 1403940

Please sign in to comment.