Beispiel #1
0
 def _get_scan_list(self):
     beu = BackendUtils()
     if self.args.images:
         scan_list = beu.get_images()
     elif self.args.containers:
         scan_list = beu.get_containers()
     elif self.args.all:
         scan_list = beu.get_images() + beu.get_containers()
     else:
         scan_list = []
         for scan_target in self.args.scan_targets:
             try:
                 # get_backend_and_container throws a ValueError when it cannot find anything
                 _, scan_obj = beu.get_backend_and_container_obj(
                     scan_target)
             except ValueError:
                 try:
                     # get_backend_and_image throws a ValueError when it cannot find anything
                     _, scan_obj = beu.get_backend_and_image_obj(
                         scan_target)
                 except ValueError:
                     raise ValueError(
                         "Unable to locate the container or image '{}'".
                         format(scan_target))
             scan_list.append(scan_obj)
     return scan_list
Beispiel #2
0
    def update(self):
        if self.args.debug:
            write_out(str(self.args))

        if self.args.all and self.args.image is not None:
            raise ValueError("Cannot specify both --all and an image name")

        if self.args.all and self.args.force:
            raise ValueError("Cannot specify both --all and --force")

        if self.args.all and self.args.storage is None:
            raise ValueError("Please specify --storage")

        beu = BackendUtils()

        if self.args.all:
            be = beu.get_backend_from_string(self.args.storage)
            return self.update_all_images(be, self.args.debug)

        try:
            be, img_obj = beu.get_backend_and_image_obj(
                self.image,
                str_preferred_backend=self.args.storage or storage,
                required=True if self.args.storage else False)
            input_name = img_obj.input_name
        except ValueError:
            raise ValueError("{} not found locally.  Unable to update".format(
                self.image))

        be.update(input_name,
                  debug=self.args.debug,
                  force=self.args.force,
                  image_object=img_obj)
        return 0
Beispiel #3
0
 def __init__(self, policy_filename=None):
     """
     :param policy_filename: override policy filename
     """
     super(Pull, self).__init__()
     self.policy_filename=policy_filename
     self.be_utils = BackendUtils()
Beispiel #4
0
    def tag_image(self):
        """
        Tag an image with a different name
        :return: 0 if the tag was created
        """
        if self.args.debug:
            util.write_out(str(self.args))

        beu = BackendUtils()

        backend = None
        if self.args.storage:
            backend = beu.get_backend_from_string(self.args.storage)
            image = backend.has_image(self.args.src)

        else:
            backend, image = beu.get_backend_and_image_obj(self.args.src,
                                                           required=False)

        if not backend or not image:
            raise ValueError("Cannot find image {}.".format(self.args.src))

        backend.tag_image(self.args.src, self.args.target)

        # We need to return something here for dbus
        return 0
Beispiel #5
0
 def run(self):
     storage_set = False if self.args.storage is None else True
     storage = _storage if not storage_set else self.args.storage
     be_utils = BackendUtils()
     if self.name:
         try:
             be, con_obj = be_utils.get_backend_and_container_obj(self.name)
             return be.run(con_obj, atomic=self, args=self.args)
         except ValueError:
             pass
     be = be_utils.get_backend_from_string(storage)
     db = DockerBackend()
     img_object = be.has_image(self.image)
     if img_object is None and storage == 'docker':
         self.display("Need to pull %s" % self.image)
         remote_image_obj = db.make_remote_image(self.args.image)
         # If the image has a atomic.type of system, then we need to land
         # this in the ostree backend.  Install it and then start it
         # because this is run
         if remote_image_obj.is_system_type and not storage_set:
             be = be_utils.get_backend_from_string('ostree')
             be_utils.message_backend_change('docker', 'ostree')
             be.install(self.image, self.name)
             con_obj = be.has_container(self.name)
             return be.run(con_obj)
         if self.args.display:
             return 0
         try:
             db.pull_image(self.image, remote_image_obj)
             img_object = db.has_image(self.image)
         except RegistryInspectError:
             raise ValueError("Unable to find image {}".format(self.image))
     return be.run(img_object, atomic=self, args=self.args)
Beispiel #6
0
    def pull_image(self):
        storage_set = False if self.args.storage is None else True
        storage = _storage if not storage_set else self.args.storage
        check_storage_is_available(storage)
        if self.args.debug:
            write_out(str(self.args))

        be_utils = BackendUtils()
        be = be_utils.get_backend_from_string(storage)
        self.args.policy_filename = self.policy_filename
        try:
            if be.backend == 'docker':
                remote_image_obj = be.make_remote_image(self.args.image)
                if remote_image_obj.is_system_type and not storage_set:
                    be = be_utils.get_backend_from_string('ostree')
                    be_utils.message_backend_change('docker', 'ostree')
            else:
                remote_image_obj = None
            be.pull_image(self.args.image,
                          remote_image_obj,
                          debug=self.args.debug,
                          assumeyes=self.args.assumeyes)
        except ValueError as e:
            raise ValueError("Failed: {}".format(e))
        return 0
Beispiel #7
0
    def install(self):
        if self.args.debug:
            util.write_out(str(self.args))
        storage_set = False if self.args.storage is None else True
        storage = _storage if not storage_set else self.args.storage
        args_system = getattr(self.args, 'system', None)
        args_user= getattr(self.args, 'user', None)
        if (args_system or args_user) and storage != 'ostree' and storage_set:
            raise ValueError("The --system and --user options are only available for the 'ostree' storage.")
        be_utils = BackendUtils()
        try:
            # Check to see if the container already exists
            _, _ = be_utils.get_backend_and_container_obj(self.name)
            raise ValueError("A container '%s' is already present" % self.name)
        except ValueError:
            pass

        if self.user:
            if not util.is_user_mode():
                raise ValueError("--user does not work for privileged user")
            return self.syscontainers.install_user_container(self.image, self.name)
        elif self.system or storage == 'ostree':
            return self.syscontainers.install(self.image, self.name)
        elif OSTREE_PRESENT and self.args.setvalues:
            raise ValueError("--set is valid only when used with --system or --user")

        # Assumed backend now is docker
        be = be_utils.get_backend_from_string('docker')

        # If the image is already present,
        img_obj = be.has_image(self.image)
        if img_obj is None:
            remote_image_obj = be.make_remote_image(self.args.image)
            # We found an atomic.type of system, therefore install it onto the ostree
            # backend
            if remote_image_obj.is_system_type and not storage_set:
                be_utils.message_backend_change('docker', 'ostree')
                return self.syscontainers.install(self.image, self.name)
            be.pull_image(self.args.image, remote_image_obj, debug=self.args.debug)
            img_obj = be.has_image(self.image)
        install_args = img_obj.get_label('INSTALL')
        if not install_args:
            return 0
        install_args = install_args.split()
        cmd = self.sub_env_strings(self.gen_cmd(install_args + self.quote(self.args.args)))
        self.display(cmd)

        if not self.args.display:
            try:
                name = img_obj.fq_name
            except RegistryInspectError:
                name = img_obj.input_name
            install_data = {}
            install_data[name] = {'id': img_obj.id,
                                  'install_date': strftime("%Y-%m-%d %H:%M:%S", gmtime())
                                  }
            util.InstallData.write_install_data(install_data)
            return util.check_call(cmd)
Beispiel #8
0
    def stop(self):

        if self.args.debug:
            util.write_out(str(self.args))

        beu = BackendUtils()
        be, con_obj = beu.get_backend_and_container_obj(self.args.container, storage)
        be.stop_container(con_obj, atomic=self, args=self.args)
        return 0
Beispiel #9
0
class TestBackendUtils(unittest.TestCase):

    bu = BackendUtils()

    def test_get_backend_for_image_preferred(self):
        pass

    def test_get_backend_for_image(self):
        pass
Beispiel #10
0
 def update(self):
     if self.args.debug:
         write_out(str(self.args))
     beu = BackendUtils()
     try:
         be, img_obj = beu.get_backend_and_image_obj(self.image, str_preferred_backend=self.args.storage or storage, required=True if self.args.storage else False)
         input_name = img_obj.input_name
     except ValueError:
         raise ValueError("{} not found locally.  Unable to update".format(self.image))
     be.update(input_name, self.args)
Beispiel #11
0
    def prune_images(self):
        """
        Remove dangling images from registry
        :return: 0 if all images deleted or no dangling images found
        """

        if self.args.debug:
            util.write_out(str(self.args))

        beu = BackendUtils()
        for backend in beu.available_backends:
            be = backend()
            be.prune()

        return 0
Beispiel #12
0
    def delete_image(self):
        """
        Mark given image(s) for deletion from registry
        :return: 0 if all images marked for deletion, otherwise 2 on any failure
        """
        if self.args.debug:
            util.write_out(str(self.args))

        beu = BackendUtils()
        # Ensure the input values match up first
        delete_objects = []

        # We need to decide on new returns for dbus because we now check image
        # validity prior to executing the delete.  If there is going to be a
        # failure, it will be here.
        #
        # The failure here is basically that it couldnt verify/find the image.

        for image in self.args.delete_targets:
            be, img_obj = beu.get_backend_and_image(image, str_preferred_backend=self.args.storage)
            delete_objects.append((be, img_obj))

        if self.args.remote:
            return self._delete_remote(self.args.delete_targets)

        max_img_name = max([len(x.input_name) for _, x in delete_objects]) + 2

        if not self.args.assumeyes:
            util.write_out("Do you wish to delete the following images?\n")
            two_col = "   {0:" + str(max_img_name) + "} {1}"
            util.write_out(two_col.format("IMAGE", "STORAGE"))
            for del_obj in delete_objects:
                be, img_obj = del_obj
                util.write_out(two_col.format(img_obj.input_name, be.backend))
            confirm = util.input("\nConfirm (y/N) ")
            confirm = confirm.strip().lower()
            if not confirm in ['y', 'yes']:
                util.write_err("User aborted delete operation for {}".format(self.args.delete_targets))
                sys.exit(2)

        # Perform the delete
        for del_obj in delete_objects:
            be, img_obj = del_obj
            be.delete_image(img_obj.input_name, force=self.args.force)

        # We need to return something here for dbus
        return
Beispiel #13
0
    def uninstall(self):
        if self.args.debug:
            util.write_out(str(self.args))

        beu = BackendUtils()
        try:
            be, img_obj = beu.get_backend_and_image_obj(
                self.args.image, str_preferred_backend=self.args.storage)
        except ValueError as e:
            if 'ostree' in [x().backend for x in beu.available_backends]:
                ost = OSTreeBackend()
                img_obj = ost.has_container(self.args.image)
                if not img_obj:
                    raise ValueError(e)
                be = ost
        be.uninstall(img_obj, name=self.args.name, atomic=self)
        return 0
Beispiel #14
0
    def stop(self):

        if self.args.debug:
            util.write_out(str(self.args))

        beu = BackendUtils()
        be, con_obj = beu.get_backend_and_container_obj(
            self.args.container, storage)
        con_obj.stop_args = con_obj.get_label('stop')
        if con_obj.stop_args and be.backend == 'docker':
            cmd = self.gen_cmd(con_obj.stop_args + self.quote(self.args.args))
            cmd = self.sub_env_strings(cmd)
            self.display(cmd)
            # There should be some error handling around this
            # in case it fails.  And what should then be done?
            util.check_call(cmd, env=self.cmd_env())

        be.stop_container(con_obj)
Beispiel #15
0
    def run(self):
        if self.name:
            be_utils = BackendUtils()
            try:
                be, con_obj = be_utils.get_backend_and_container_obj(self.name)
                return be.run(con_obj, atomic=self, args=self.args)
            except ValueError:
                pass

        db = DockerBackend()
        img_object = db.has_image(self.image)
        if img_object is None:
            self.display("Need to pull %s" % self.image)
            if self.args.display:
                return 0
            try:
                db.pull_image(self.image)
                img_object = db.has_image(self.image)
            except RegistryInspectError:
                raise ValueError("Unable to find image {}".format(self.image))

        db.run(img_object, atomic=self, args=self.args)
Beispiel #16
0
    def install(self):
        debug = self.args.debug
        if self.args.debug:
            util.write_out(str(self.args))
        be_utils = BackendUtils()
        try:
            # Check to see if the container already exists
            _, _ = be_utils.get_backend_and_container_obj(self.name)
            raise ValueError("A container '%s' is already present" % self.name)
        except ValueError:
            pass

        if self.user:
            if not util.is_user_mode():
                raise ValueError("--user does not work for privileged user")
            return self.syscontainers.install_user_container(self.image, self.name)
        elif self.system:
            return self.syscontainers.install(self.image, self.name)
        elif OSTREE_PRESENT and self.args.setvalues:
            raise ValueError("--set is valid only when used with --system or --user")

        # Assumed backend now is docker
        be = be_utils.get_backend_from_string('docker')

        # If the image is already present,
        img_obj = be.has_image(self.image)
        if img_obj is None:
            be.pull_image(self.image, debug=debug)
            img_obj = be.has_image(self.image)
        install_args = img_obj.get_label('INSTALL')
        if not install_args:
            return 0
        install_args = install_args.split()
        cmd = self.sub_env_strings(self.gen_cmd(install_args + self.quote(self.args.args)))
        self.display(cmd)

        if not self.args.display:
            return util.check_call(cmd)
Beispiel #17
0
    def verify(self):
        if self.args.image and self.args.all:
            raise ValueError("Incompatible options specified.  --all doesn't support an image name")
        if not self.args.all and not self.args.image:
            raise ValueError("Please specify the image name")
        if self.args.all and not self.args.storage:
            raise ValueError("Please specify --storage")

        if self.args.all:
            be = BackendUtils().get_backend_from_string(self.args.storage)
            images = be.get_images()
            for i in images:
                if i.repotags is None:
                    continue
                img_name = i.repotags[0]

                d = util.Decompose(img_name)
                if d.registry == "":
                    util.write_err("Image {} not fully qualified: skipping".format(img_name))
                    continue

                self._verify_one_image(img_name)
        else:
            return self._verify_one_image(self.args.image)
Beispiel #18
0
 def __init__(self):
     super(Containers, self).__init__()
     self.beu = BackendUtils()
Beispiel #19
0
    def install(self):
        if self.args.debug:
            util.write_out(str(self.args))
        storage_set = False if self.args.storage is None else True
        storage = _storage if not storage_set else self.args.storage
        args_system = getattr(self.args, 'system', None)
        args_user = getattr(self.args, 'user', None)
        if (args_system or args_user) and storage != 'ostree' and storage_set:
            raise ValueError(
                "The --system and --user options are only available for the 'ostree' storage."
            )
        be_utils = BackendUtils()
        try:
            # Check to see if the container already exists
            _, _ = be_utils.get_backend_and_container_obj(self.name)
            raise ValueError("A container '%s' is already present" % self.name)
        except ValueError:
            pass

        if self.user:
            if not util.is_user_mode():
                raise ValueError("--user does not work for privileged user")
            return self.syscontainers.install_user_container(
                self.image, self.name)
        if self.ostree_uri(self.image):
            return self.syscontainers.install(self.image, self.name)
        # Check if image exists
        str_backend = 'ostree' if self.args.system else self.args.storage or storage
        be = be_utils.get_backend_from_string(str_backend)
        img_obj = be.has_image(self.args.image)
        if img_obj and img_obj.is_system_type:
            be = be_utils.get_backend_from_string('ostree')

        if img_obj is None:
            # Unable to find the image locally, look remotely
            remote_image_obj = be.make_remote_image(self.args.image)
            # We found an atomic.type of system, therefore install it onto the ostree
            # backend
            if remote_image_obj.is_system_type and not storage_set:
                be_utils.message_backend_change('docker', 'ostree')
                be = be_utils.get_backend_from_string('ostree')
            be.pull_image(self.args.image,
                          remote_image_obj,
                          debug=self.args.debug)
            img_obj = be.has_image(self.image)

        if be.backend is not 'docker':
            if OSTREE_PRESENT and self.args.setvalues and not self.user and not self.system:
                raise ValueError(
                    "--set is valid only when used with --system or --user")

            # We need to fix this long term and get ostree
            # using the backend approach vs the atomic args
            be.syscontainers.set_args(self.args)
            return be.install(self.image, self.name)

        installation = None
        if storage == 'docker' and not args_system:
            if self.args.system_package == 'build':
                raise ValueError(
                    "'--system-package=build' is not supported for docker backend"
                )
            installation = be.rpm_install(img_obj, self.name)

        install_args = img_obj.get_label('INSTALL')

        if installation or install_args:
            try:
                name = img_obj.fq_name
            except RegistryInspectError:
                name = img_obj.input_name
            install_data_content = {
                'id': img_obj.id,
                "container_name": self.name,
                'install_date': strftime("%Y-%m-%d %H:%M:%S", gmtime())
            }
            if installation:
                # let's fail the installation if rpm for this image is already installed
                if util.InstallData.image_installed(img_obj):
                    raise ValueError("Image {} is already installed.".format(
                        self.image))
                install_data_content[
                    "rpm_installed_files"] = installation.installed_files
                rpm_nvra = re.sub(r"\.rpm$", "",
                                  installation.original_rpm_name)
                install_data_content["system_package_nvra"] = rpm_nvra
            install_data = {name: install_data_content}
            util.InstallData.write_install_data(install_data)

        if not install_args:
            return 0
        install_args = install_args.split()
        cmd = self.sub_env_strings(
            self.gen_cmd(install_args + self.quote(self.args.args)))
        self.display(cmd)

        if not self.args.display:
            return util.check_call(cmd)
Beispiel #20
0
 def __init__(self):
     super(Info, self).__init__()
     self.beu = BackendUtils()
Beispiel #21
0
 def __init__(self):
     super(Verify, self).__init__()
     self.debug = False
     self.backend_utils = BackendUtils()
Beispiel #22
0
    def delete_image(self):
        """
        Mark given image(s) for deletion from registry
        :return: 0 if all images marked for deletion, otherwise 2 on any failure
        """
        if self.args.debug:
            util.write_out(str(self.args))

        if len(self.args.delete_targets) > 0 and self.args.all:
            raise ValueError(
                "You must select --all or provide a list of images to delete.")

        beu = BackendUtils()
        delete_objects = []

        # We need to decide on new returns for dbus because we now check image
        # validity prior to executing the delete.  If there is going to be a
        # failure, it will be here.
        #
        # The failure here is basically that it couldnt verify/find the image.

        if self.args.all:
            delete_objects = beu.get_images(get_all=True)
        else:
            for image in self.args.delete_targets:
                _, img_obj = beu.get_backend_and_image_obj(
                    image,
                    str_preferred_backend=self.args.storage or storage,
                    required=True if self.args.storage else False)
                delete_objects.append(img_obj)

        if self.args.remote:
            return self._delete_remote(self.args.delete_targets)

        _image_names = []
        for del_obj in delete_objects:
            if del_obj.repotags:
                _image_names.append(len(del_obj.repotags[0]))
            else:
                _image_names.append(len(del_obj.id))
        max_img_name = max(_image_names) + 2

        if not self.args.assumeyes:
            util.write_out("Do you wish to delete the following images?\n")
            two_col = "   {0:" + str(max_img_name) + "} {1}"
            util.write_out(two_col.format("IMAGE", "STORAGE"))
            for del_obj in delete_objects:
                image = None if not del_obj.repotags else del_obj.repotags[0]
                if image is None or "<none>" in image:
                    image = del_obj.id[0:12]
                util.write_out(two_col.format(image, del_obj.backend.backend))
            confirm = util.input("\nConfirm (y/N) ")
            confirm = confirm.strip().lower()
            if not confirm in ['y', 'yes']:
                util.write_err("User aborted delete operation for {}".format(
                    self.args.delete_targets))
                sys.exit(2)

        # Perform the delete
        for del_obj in delete_objects:
            del_obj.backend.delete_image(del_obj.input_name,
                                         force=self.args.force)

        # We need to return something here for dbus
        return