Example #1
0
File: api.py Project: akurz/cobbler
    def signature_update(self, logger):
        try:
            tmpfile = tempfile.NamedTemporaryFile()
            proxies = {}
            proxies['http'] = self.settings().proxy_url_ext
            response = urlgrabber.grabber.urlopen(self.settings().signature_url, proxies=proxies)
            sigjson = response.read()
            tmpfile.write(sigjson)
            tmpfile.flush()

            logger.debug("Successfully got file from %s" % self.settings().signature_url)
            # test the import without caching it
            try:
                utils.load_signatures(tmpfile.name, cache=False)
            except:
                logger.error("Downloaded signatures failed test load (tempfile = %s)" % tmpfile.name)

            # rewrite the real signature file and import it for real
            f = open(self.settings().signature_path, "w")
            f.write(sigjson)
            f.close()

            utils.load_signatures(self.settings().signature_path)
        except:
            utils.log_exc(logger)
Example #2
0
    def signature_update(self, logger):
        try:
            tmpfile = tempfile.NamedTemporaryFile()
            proxies = {}
            proxies['http'] = self.settings().proxy_url_ext
            response = urlgrabber.grabber.urlopen(self.settings().signature_url, proxies=proxies)
            sigjson = response.read()
            tmpfile.write(sigjson)
            tmpfile.flush()

            logger.debug("Successfully got file from %s" % self.settings().signature_url)
            # test the import without caching it
            try:
                utils.load_signatures(tmpfile.name, cache=False)
            except:
                logger.error("Downloaded signatures failed test load (tempfile = %s)" % tmpfile.name)

            # rewrite the real signature file and import it for real
            f = open(self.settings().signature_path, "w")
            f.write(sigjson)
            f.close()

            utils.load_signatures(self.settings().signature_path)
        except:
            utils.log_exc(logger)
Example #3
0
    def signature_update(self, logger):
        try:
            url = self.settings().signature_url
            dlmgr = download_manager.DownloadManager(self._collection_mgr,
                                                     self.logger)
            # write temp json file
            tmpfile = tempfile.NamedTemporaryFile()
            sigjson = dlmgr.urlread(url)
            tmpfile.write(sigjson.text.encode())
            tmpfile.flush()
            logger.debug("Successfully got file from %s" %
                         self.settings().signature_url)
            # test the import without caching it
            try:
                utils.load_signatures(tmpfile.name, cache=False)
            except:
                logger.error(
                    "Downloaded signatures failed test load (tempfile = %s)" %
                    tmpfile.name)

            # rewrite the real signature file and import it for real
            f = open(self.settings().signature_path, "w")
            f.write(sigjson.text)
            f.close()

            utils.load_signatures(self.settings().signature_path)
        except:
            utils.log_exc(logger)
Example #4
0
def test_validate_breed():
    # Arrange
    utils.load_signatures("/var/lib/cobbler/distro_signatures.json")

    # Act
    result = validate.validate_breed("redhat")

    # Assert
    assert result == "redhat"
Example #5
0
def test_validate_os_version():
    # Arrange
    utils.load_signatures("/var/lib/cobbler/distro_signatures.json")

    # Act
    result = validate.validate_os_version("rhel4", "redhat")

    # Assert
    assert result == "rhel4"
Example #6
0
def test_load_signatures():
    # Arrange
    utils.SIGNATURE_CACHE = {}
    old_cache = utils.SIGNATURE_CACHE

    # Act
    utils.load_signatures("/var/lib/cobbler/distro_signatures.json")

    # Assert
    assert old_cache != utils.SIGNATURE_CACHE
Example #7
0
def test_breed():
    # Arrange
    test_api = CobblerAPI()
    utils.load_signatures("/var/lib/cobbler/distro_signatures.json")
    image = Image(test_api)

    # Act
    image.breed = "suse"

    # Assert
    assert image.breed == "suse"
Example #8
0
def test_breed(value, expected_exception):
    # Arrange
    test_api = CobblerAPI()
    utils.load_signatures("/var/lib/cobbler/distro_signatures.json")
    distro = Distro(test_api)

    # Act
    with expected_exception:
        distro.breed = value

        # Assert
        assert distro.breed == value
Example #9
0
def test_os_version():
    # Arrange
    test_api = CobblerAPI()
    utils.load_signatures("/var/lib/cobbler/distro_signatures.json")
    image = Image(test_api)
    image.breed = "suse"

    # Act
    image.os_version = "sles15generic"

    # Assert
    assert image.os_version == "sles15generic"
Example #10
0
def test_make_clone(create_kernel_initrd, fk_kernel, fk_initrd):
    # Arrange
    test_api = CobblerAPI()
    folder = create_kernel_initrd(fk_kernel, fk_initrd)
    utils.load_signatures("/var/lib/cobbler/distro_signatures.json")
    distro = Distro(test_api)
    distro.breed = "suse"
    distro.os_version = "sles15generic"
    distro.kernel = os.path.join(folder, "vmlinuz1")
    distro.initrd = os.path.join(folder, "initrd1.img")

    # Act
    result = distro.make_clone()

    # Assert
    # TODO: When in distro.py the FIXME of this method is done then adjust this here
    assert result != distro
Example #11
0
    def signature_update(self, logger):
        try:
            tmpfile = tempfile.NamedTemporaryFile()
            response = urllib2.urlopen(self.settings().signature_url)
            sigjson = response.read()
            tmpfile.write(sigjson)
            tmpfile.flush()

            logger.debug("Successfully got file from %s" % self.settings().signature_url)
            # test the import without caching it
            if not utils.load_signatures(tmpfile.name, cache=False):
                logger.error("Downloaded signatures failed test load (tempfile = %s)" % tmpfile.name)
                return False

            # rewrite the real signature file and import it for real
            f = open(self.settings().signature_path, "w")
            f.write(sigjson)
            f.close()

            return utils.load_signatures(self.settings().signature_path)
        except:
            utils.log_exc(logger)
            return False
Example #12
0
File: api.py Project: jmaas/cobbler
    def signature_update(self, logger):
        try:
            url = self.settings().signature_url
            dlmgr = download_manager.DownloadManager(self._collection_mgr, self.logger)
            # write temp json file
            tmpfile = tempfile.NamedTemporaryFile()
            sigjson = dlmgr.urlread(url)
            tmpfile.write(sigjson)
            tmpfile.flush()
            logger.debug("Successfully got file from %s" % self.settings().signature_url)
            # test the import without caching it
            try:
                utils.load_signatures(tmpfile.name, cache=False)
            except:
                logger.error("Downloaded signatures failed test load (tempfile = %s)" % tmpfile.name)

            # rewrite the real signature file and import it for real
            f = open(self.settings().signature_path, "w")
            f.write(sigjson)
            f.close()

            utils.load_signatures(self.settings().signature_path)
        except:
            utils.log_exc(logger)
Example #13
0
File: api.py Project: akurz/cobbler
    def __init__(self, is_cobblerd=False):
        """
        Constructor
        """

        # FIXME: this should be switchable through some simple system

        self.__dict__ = CobblerAPI.__shared_state
        self.perms_ok = False
        if not CobblerAPI.__has_loaded:

            if os.path.exists("/etc/cobbler/use.couch"):
                self.use_couch = True
            else:
                self.use_couch = False

            # 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

            try:
                self.logger = clogger.Logger("/var/log/cobbler/cobbler.log")
            except CX:
                # return to CLI/other but perms are not valid
                # perms_ok is False
                return

            # FIXME: conslidate into 1 server instance

            self.selinux_enabled = utils.is_selinux_enabled()
            self.dist = utils.check_dist()
            self.os_version = utils.os_release()

            CobblerAPI.__has_loaded = True

            # load the modules first, or nothing else works...
            module_loader.load_modules()

            self._collection_mgr = collection_manager.CollectionManager(self)
            self.deserialize()

            # import signatures
            try:
                utils.load_signatures(self.settings().signature_path)
            except Exception as e:
                self.log("Failed to load signatures from %s: %s" % (self.settings().signature_path, e))
                return

            self.log("%d breeds and %d OS versions read from the signature file" % (
                len(utils.get_valid_breeds()), len(utils.get_valid_os_versions()))
            )

            self.authn = self.get_module_from_file(
                "authentication",
                "module",
                "authn_configfile"
            )
            self.authz = self.get_module_from_file(
                "authorization",
                "module",
                "authz_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.yumgen = yumgen.YumGen(self._collection_mgr)
            self.tftpgen = tftpgen.TFTPGen(self._collection_mgr, logger=self.logger)
            self.power_mgr = power_manager.PowerManager(self, self._collection_mgr)
            self.logger.debug("API handle initialized")
            self.perms_ok = True
Example #14
0
                # FIXME: pretty-printing and sorting here
                keys = data.keys()
                keys.sort()
                for x in keys:
                    print "%s: %s" % (x, data[x])
            elif object_action in ["poweron", "poweroff", "powerstatus", "reboot"]:
                power = {}
                power["power"] = object_action.replace("power", "")
                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:
                    utils.load_signatures(filename, cache=True)
                except:
                    print "There was an error loading the signature data in %s." % filename
                    print "Please check the JSON file or run 'cobbler signature update'."
                    return
                else:
                    print "Signatures were successfully loaded"
            else:
                raise exceptions.NotImplementedError()
        else:
            raise exceptions.NotImplementedError()

        # FIXME: add tail/polling code here
        if task_id != -1:
            self.print_task(task_id)
            self.follow_task(task_id)
Example #15
0
    def __init__(self, is_cobblerd=False):
        """
        Constructor
        """

        # FIXME: this should be switchable through some simple system

        self.__dict__ = CobblerAPI.__shared_state
        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

            try:
                self.logger = clogger.Logger("/var/log/cobbler/cobbler.log")
            except CX:
                # return to CLI/other but perms are not valid
                # perms_ok is False
                return

            # FIXME: conslidate into 1 server instance

            self.selinux_enabled = utils.is_selinux_enabled()
            self.dist = utils.check_dist()
            self.os_version = utils.os_release()

            CobblerAPI.__has_loaded = True

            # load the modules first, or nothing else works...
            module_loader.load_modules()

            self._collection_mgr = collection_manager.CollectionManager(self)
            self.deserialize()

            # import signatures
            try:
                utils.load_signatures(self.settings().signature_path)
            except Exception as e:
                self.log("Failed to load signatures from %s: %s" % (self.settings().signature_path, e))
                return

            self.log("%d breeds and %d OS versions read from the signature file" % (
                len(utils.get_valid_breeds()), len(utils.get_valid_os_versions()))
            )

            self.authn = self.get_module_from_file(
                "authentication",
                "module",
                "authn_configfile"
            )
            self.authz = self.get_module_from_file(
                "authorization",
                "module",
                "authz_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.yumgen = yumgen.YumGen(self._collection_mgr)
            self.tftpgen = tftpgen.TFTPGen(self._collection_mgr, logger=self.logger)
            self.power_mgr = power_manager.PowerManager(self, self._collection_mgr)
            self.logger.debug("API handle initialized")
            self.perms_ok = True
Example #16
0
                    "poweron", "poweroff", "powerstatus", "reboot"
            ]:
                power = {}
                power["power"] = object_action.replace("power", "")
                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:
                    utils.load_signatures(filename, cache=True)
                except:
                    print "There was an error loading the signature data in %s." % filename
                    print "Please check the JSON file or run 'cobbler signature update'."
                    return
                else:
                    print "Signatures were successfully loaded"
            else:
                raise exceptions.NotImplementedError()
        else:
            raise exceptions.NotImplementedError()

        # FIXME: add tail/polling code here
        if task_id != -1:
            self.print_task(task_id)
            self.follow_task(task_id)
Example #17
0
File: cli.py Project: jmaas/cobbler
    def object_command(self, object_type, object_action):
        """
        Process object-based commands such as "distro add" or "profile rename"
        """
        task_id = -1        # if assigned, we must tail the logfile
        settings = self.remote.get_settings()

        fields = self.get_fields(object_type)
        network_interface_fields = None
        if object_type == "system":
            network_interface_fields = item_system.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"]:
            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, args) = self.parser.parse_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 in OBJECT_ACTIONS:
            if opt(options, "name") == "" and object_action not in ("reload", "update"):
                print("--name is required")
                sys.exit(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")
                        elif not settings.get('allow_dynamic_settings', False):
                            raise RuntimeError("Dynamic settings changes are not enabled. Change the allow_dynamic_settings to 1 and restart cobblerd to enable dynamic settings changes")
                        elif options.name == 'allow_dynamic_settings':
                            raise RuntimeError("Cannot modify that setting live")
                        elif 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 xxx_todo_changeme:
                    (err) = xxx_todo_changeme
                    (etype, emsg) = err.faultString.split(":", 1)
                    print("exception on server: %s" % emsg)
                    sys.exit(1)
                except RuntimeError as xxx_todo_changeme1:
                    (err) = xxx_todo_changeme1
                    print(err.args[0])
                    sys.exit(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)
                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)
                # FIXME: pretty-printing and sorting here
                keys = list(data.keys())
                keys.sort()
                for x in keys:
                    print("%s: %s" % (x, data[x]))
            elif object_action in ["poweron", "poweroff", "powerstatus", "reboot"]:
                power = {}
                power["power"] = object_action.replace("power", "")
                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:
                    utils.load_signatures(filename, cache=True)
                except:
                    print("There was an error loading the signature data in %s." % filename)
                    print("Please check the JSON file or run 'cobbler signature update'.")
                    return
                else:
                    print("Signatures were successfully loaded")
            else:
                raise NotImplementedException()
        else:
            raise NotImplementedException()

        # FIXME: add tail/polling code here
        if task_id != -1:
            self.print_task(task_id)
            self.follow_task(task_id)
Example #18
0
    def object_command(self, object_type, object_action):
        """
        Process object-based commands such as "distro add" or "profile rename"
        """
        task_id = -1        # if assigned, we must tail the logfile
        settings = self.remote.get_settings()

        fields = self.get_fields(object_type)
        network_interface_fields = None
        if object_type == "system":
            network_interface_fields = system.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"]:
            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, args) = self.parser.parse_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 in OBJECT_ACTIONS:
            if opt(options, "name") == "" and object_action not in ("reload", "update"):
                print("--name is required")
                sys.exit(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")
                        elif not settings.get('allow_dynamic_settings', False):
                            raise RuntimeError("Dynamic settings changes are not enabled. Change the allow_dynamic_settings to 1 and restart cobblerd to enable dynamic settings changes")
                        elif options.name == 'allow_dynamic_settings':
                            raise RuntimeError("Cannot modify that setting live")
                        elif 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 xxx_todo_changeme:
                    (err) = xxx_todo_changeme
                    (etype, emsg) = err.faultString.split(":", 1)
                    print("exception on server: %s" % emsg)
                    sys.exit(1)
                except RuntimeError as xxx_todo_changeme1:
                    (err) = xxx_todo_changeme1
                    print(err.args[0])
                    sys.exit(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)
                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)
                # FIXME: pretty-printing and sorting here
                keys = list(data.keys())
                keys.sort()
                for x in keys:
                    print("%s: %s" % (x, data[x]))
            elif object_action in ["poweron", "poweroff", "powerstatus", "reboot"]:
                power = {}
                power["power"] = object_action.replace("power", "")
                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:
                    utils.load_signatures(filename, cache=True)
                except:
                    print("There was an error loading the signature data in %s." % filename)
                    print("Please check the JSON file or run 'cobbler signature update'.")
                    return
                else:
                    print("Signatures were successfully loaded")
            else:
                raise NotImplementedException()
        else:
            raise NotImplementedException()

        # FIXME: add tail/polling code here
        if task_id != -1:
            self.print_task(task_id)
            self.follow_task(task_id)