Exemple #1
0
    def update_to_latest_patch(self, job, jail):
        """Updates specified jail to latest patch level."""

        uuid, path, _ = self.check_jail_existence(jail)
        status, jid = IOCList.list_get_jid(uuid)
        conf = IOCJson(path).json_load()

        # Sometimes if they don't have an existing patch level, this
        # becomes 11.1 instead of 11.1-RELEASE
        _release = conf["release"].rsplit("-", 1)[0]
        release = _release if "-RELEASE" in _release else conf["release"]

        started = False

        if conf["type"] == "jail":
            if not status:
                self.start(jail)
                started = True
        else:
            return False

        if conf["basejail"] != "yes":
            IOCFetch(release).fetch_update(True, uuid)
        else:
            # Basejails only need their base RELEASE updated
            IOCFetch(release).fetch_update()

        if started:
            self.stop(jail)

        return True
Exemple #2
0
def list_cmd(dataset_type, header, _long, remote, http, plugins):
    """This passes the arg and calls the jail_datasets function."""
    lgr = logging.getLogger('ioc_cli_list')
    freebsd_version = checkoutput(["freebsd-version"])

    if dataset_type is None:
        dataset_type = "all"

    if remote:
        if "HBSD" in freebsd_version:
            hardened = True
        else:
            hardened = False

        IOCFetch("", http=http, hardened=hardened).fetch_release(_list=True)
    elif plugins:
        IOCFetch("").fetch_plugin_index("", _list=True)
    else:
        _list = IOCList(dataset_type, header, _long).list_datasets()

        if not header:
            if dataset_type == "base":
                for item in _list:
                    lgr.info(item)
            else:
                for item in _list:
                    lgr.info("\t".join(item))
        else:
            lgr.info(_list)
Exemple #3
0
    def update(self, job, jail):
        # FIXME: No-op until I change iocage behavior with freebsd-update
        # not existing.
        # TODO: upgrade needs to be broken out of cli.
        """Updates specified jail to latest patch level."""
        from iocage.lib.ioc_fetch import IOCFetch

        tag, uuid, path = self.check_jail_existence(jail)
        status, jid = IOCList.list_get_jid(uuid)
        conf = IOCJson(path).json_load()
        started = False

        if conf["type"] == "jail":
            if not status:
                self.start(jail)
                started = True
        else:
            return False

        IOCFetch(conf["cloned_release"]).fetch_update(True, uuid, tag)

        if started:
            self.stop(jail)

        return True
Exemple #4
0
def list_cmd(dataset_type, header, _long, remote, http, plugins):
    """This passes the arg and calls the jail_datasets function."""
    freebsd_version = checkoutput(["freebsd-version"])

    if dataset_type is None:
        dataset_type = "all"

    if remote:
        if "HBSD" in freebsd_version:
            hardened = True
        else:
            hardened = False

        IOCFetch("", http=http, hardened=hardened).fetch_release(
            _list=True)
    elif plugins:
        IOCFetch("").fetch_plugin_index("", _list=True)
    else:
        IOCList(dataset_type, header, _long).list_datasets()
Exemple #5
0
def update_cmd(jail):
    """Runs update with the command given inside the specified jail."""
    lgr = ioc_logger.Logger('ioc_cli_update').getLogger()

    jails, paths = IOCList("uuid").list_datasets()
    _jail = {
        tag: uuid
        for (tag, uuid) in jails.items()
        if uuid.startswith(jail) or tag == jail
    }

    if len(_jail) == 1:
        tag, uuid = next(iter(_jail.items()))
        path = paths[tag]
    elif len(_jail) > 1:
        lgr.error("Multiple jails found for" " {}:".format(jail))
        for t, u in sorted(_jail.items()):
            lgr.critical("  {} ({})".format(u, t))
        exit(1)
    else:
        lgr.critical("{} not found!".format(jail))
        exit(1)

    freebsd_version = checkoutput(["freebsd-version"])
    status, jid = IOCList.list_get_jid(uuid)
    conf = IOCJson(path).json_load()
    started = False

    if conf["type"] == "jail":
        if not status:
            IOCStart(uuid, tag, path, conf, silent=True)
            status, jid = IOCList.list_get_jid(uuid)
            started = True
    elif conf["type"] == "basejail":
        lgr.critical("Please run \"iocage migrate\" before trying"
                     " to update {} ({})".format(uuid, tag))
        exit(1)
    elif conf["type"] == "template":
        lgr.critical("Please convert back to a jail before trying"
                     " to update {} ({})".format(uuid, tag))
        exit(1)
    else:
        lgr.critical("{} is not a supported jail type.".format(conf["type"]))
        exit(1)

    if "HBSD" in freebsd_version:
        Popen(["hbsd-update", "-j", jid]).communicate()

        if started:
            IOCStop(uuid, tag, path, conf, silent=True)
    else:
        IOCFetch(conf["cloned_release"]).fetch_update(True, uuid, tag)

        if started:
            IOCStop(uuid, tag, path, conf, silent=True)
Exemple #6
0
    def fetch(self, job, options):
        """Fetches a release or plugin."""
        from iocage.lib.ioc_fetch import IOCFetch
        self.check_dataset_existence()

        release = options["release"]
        server = options["server"]
        user = options["user"]
        password = options["password"]
        plugin_file = options["plugin_file"]
        props = options["props"]

        if plugin_file:
            IOCFetch("", server, user, password).fetch_plugin(plugin_file,
                                                              props, 0)
            return True

        IOCFetch(release, server, user, password).fetch_release()

        return True
Exemple #7
0
    def fetch(self, job, options):
        """Fetches a release or plugin."""
        from iocage.lib.ioc_fetch import IOCFetch
        self.check_dataset_existence()

        release = options.get("release", None)
        server = options.get("server", "ftp.freebsd.org")
        user = options.get("user", "anonymous")
        password = options.get("password", "anonymous@")
        plugin_file = options.get("plugin_file", None)
        props = options.get("props", None)

        if plugin_file:
            IOCFetch("", server, user, password).fetch_plugin(plugin_file,
                                                              props, 0)
            return True

        IOCFetch(release, server, user, password).fetch_release()

        return True
Exemple #8
0
def test_fetch(release, server, user, password, auth, root_dir, http, _file,
               hardened):
    IOCFetch(release,
             server,
             user,
             password,
             auth,
             root_dir,
             http=http,
             _file=_file,
             hardened=hardened).fetch_release()

    assert True == True
Exemple #9
0
    def update(self, job, jail):
        """Updates specified jail to latest patch level."""
        from iocage.lib.ioc_fetch import IOCFetch

        tag, uuid, path = self.check_jail_existence(jail)
        status, jid = IOCList.list_get_jid(uuid)
        conf = IOCJson(path).json_load()
        started = False

        if conf["type"] == "jail":
            if not status:
                self.start(jail)
                started = True
        else:
            return False

        IOCFetch(conf["cloned_release"]).fetch_update(True, uuid, tag)

        if started:
            self.stop(jail)

        return True
Exemple #10
0
    def list(self, lst_type, options=None):
        """Lists either 'all', 'base', 'template'"""
        self.check_dataset_existence()

        lst_type = lst_type.lower()

        if options is None:
            options = {}

        if lst_type == "release":
            lst_type = "base"

        full = options.get("full", True)
        hdr = options.get("header", False)

        if lst_type == "plugins":
            from iocage.lib.ioc_fetch import IOCFetch

            _list = IOCFetch("").fetch_plugin_index("", _list=True)
        else:
            _list = IOCList(lst_type, hdr, full).list_datasets()

        return _list
Exemple #11
0
def fetch_cmd(http, _file, server, user, password, auth, verify, release,
              plugins, plugin_file, root_dir, props, count, update, eol,
              files):
    """CLI command that calls fetch_release()"""
    freebsd_version = checkoutput(["freebsd-version"])
    arch = os.uname()[4]

    lgr = ioc_logger.Logger("ioc_cli_fetch").getLogger()

    if not files:
        if arch == "arm64":
            files = ("MANIFEST", "base.txz", "doc.txz")
        else:
            files = ("MANIFEST", "base.txz", "lib32.txz", "doc.txz")

    if "HBSD" in freebsd_version:
        if server == "ftp.freebsd.org":
            hardened = True
        else:
            hardened = False
    else:
        hardened = False

    if plugins or plugin_file:
        if plugin_file:
            try:
                with open(plugin_file) as f:
                    return json.load(f)
            except FileNotFoundError:
                lgr.critical("Please supply a file before any properties.")
                exit(1)
            except json.decoder.JSONDecodeError:
                lgr.critical("Invalid JSON file supplied, please supply a "
                             "correctly formatted JSON file.")
                exit(1)

        ip = [
            x for x in props
            if x.startswith("ip4_addr") or x.startswith("ip6_addr")
        ]
        if not ip:
            lgr.critical("An IP address is needed to fetch a "
                         "plugin!\nPlease specify "
                         "ip(4|6)_addr=\"INTERFACE|IPADDRESS\"!")
            exit(1)
        if plugins:
            IOCFetch(release=None).fetch_plugin_index(props)
            exit()

        if count == 1:
            IOCFetch("",
                     server,
                     user,
                     password,
                     auth,
                     root_dir,
                     http=http,
                     _file=_file,
                     verify=verify,
                     hardened=hardened,
                     update=update,
                     eol=eol,
                     files=files).fetch_plugin(plugin_file, props, 0)
        else:
            for j in range(1, count + 1):
                IOCFetch("",
                         server,
                         user,
                         password,
                         auth,
                         root_dir,
                         http=http,
                         _file=_file,
                         verify=verify,
                         hardened=hardened,
                         update=update,
                         eol=eol,
                         files=files).fetch_plugin(plugin_file, props, j)
    else:
        IOCFetch(release,
                 server,
                 user,
                 password,
                 auth,
                 root_dir,
                 http=http,
                 _file=_file,
                 verify=verify,
                 hardened=hardened,
                 update=update,
                 eol=eol,
                 files=files).fetch_release()
Exemple #12
0
def create_cmd(release, template, count, props, pkglist, basejail, empty,
               short, uuid):
    lgr = ioc_logger.Logger('ioc_cli_create').getLogger()

    if short and uuid:
        lgr.critical(
            "Can't use --short (-s) and --uuid (-u) at the same time!")
        exit(1)

    if not template and not release and not empty:
        lgr.critical("Must supply either --template (-t) or --release (-r)!")
        exit(1)

    if release and "=" in release:
        lgr.critical("Please supply a valid RELEASE!")
        exit(1)

    if template:
        # We don't really care it's not a RELEASE at this point.
        release = template

    if pkglist:
        _pkgformat = """
{
    "pkgs": [
    "foo",
    "bar"
    ]
}"""

        if not os.path.isfile(pkglist):
            lgr.critical("{} does not exist!\nPlease supply a JSON file "
                         "with the format:{}".format(pkglist, _pkgformat))
            exit(1)
        else:
            try:
                # Just try to open the JSON with the right key.
                with open(pkglist, "r") as p:
                    json.load(p)["pkgs"]  # noqa
            except JSONDecodeError:
                lgr.critical("Please supply a valid JSON file with the"
                             f" format:\n{_pkgformat}")
                exit(1)

    pool = IOCJson().json_get_value("pool")
    iocroot = IOCJson(pool).json_get_value("iocroot")

    if not os.path.isdir(
            f"{iocroot}/releases/{release}") and not template and not empty:
        freebsd_version = checkoutput(["freebsd-version"])

        if "HBSD" in freebsd_version:
            hardened = True
        else:
            hardened = False

        IOCFetch(release, hardened=hardened).fetch_release()

    if empty:
        release = "EMPTY"

    if count == 1:
        try:
            IOCCreate(release,
                      props,
                      0,
                      pkglist,
                      template=template,
                      short=short,
                      uuid=uuid,
                      basejail=basejail,
                      empty=empty).create_jail()
        except RuntimeError as err:
            lgr.error(err)
            if template:
                lgr.info("Created Templates:")
                templates = IOCList("template", hdr=False).list_datasets()
                for temp in templates:
                    lgr.info("  {}".format(temp[3]))
    else:
        for j in range(1, count + 1):
            try:
                IOCCreate(release,
                          props,
                          j,
                          pkglist,
                          template=template,
                          short=short,
                          basejail=basejail,
                          empty=empty).create_jail()
            except RuntimeError as err:
                lgr.error(err)
                if template:
                    lgr.info("Created Templates:")
                    templates = IOCList("template", hdr=False).list_datasets()
                    for temp in templates:
                        lgr.info("  {}".format(temp[3]))
                exit(1)
Exemple #13
0
def fetch_cmd(http, _file, server, user, password, auth, verify, release,
              plugins, plugin_file, root_dir, props, count, update):
    """CLI command that calls fetch_release()"""
    freebsd_version = checkoutput(["freebsd-version"])

    if "HBSD" in freebsd_version:
        if server == "ftp.freebsd.org":
            hardened = True
    else:
        hardened = False

    if plugins or plugin_file:
        ip = [
            x for x in props
            if x.startswith("ip4_addr") or x.startswith("ip6_addr")
        ]
        if not ip:
            raise RuntimeError("ERROR: An IP address is needed to fetch a "
                               "plugin!\nPlease specify "
                               "ip(4|6)_addr=\"INTERFACE|IPADDRESS\"!")
        if plugins:
            IOCFetch("").fetch_plugin_index(props)
            exit()

        if count == 1:
            IOCFetch("",
                     server,
                     user,
                     password,
                     auth,
                     root_dir,
                     http=http,
                     _file=_file,
                     verify=verify,
                     hardened=hardened,
                     update=update).fetch_plugin(plugin_file, props, 0)
        else:
            for j in range(1, count + 1):
                IOCFetch("",
                         server,
                         user,
                         password,
                         auth,
                         root_dir,
                         http=http,
                         _file=_file,
                         verify=verify,
                         hardened=hardened,
                         update=update).fetch_plugin(plugin_file, props, j)
    else:
        IOCFetch(release,
                 server,
                 user,
                 password,
                 auth,
                 root_dir,
                 http=http,
                 _file=_file,
                 verify=verify,
                 hardened=hardened,
                 update=update).fetch_release()
Exemple #14
0
def create_cmd(release, template, count, props, pkglist, basejail, short):
    lgr = logging.getLogger('ioc_cli_create')

    if not template and not release:
        raise RuntimeError(
            "Must supply either --template (-t) or --release (-r)!")

    if release and "=" in release:
        raise RuntimeError("Please supply a valid RELEASE!")

    if template:
        # We don't really care it's not a RELEASE at this point.
        release = template

    if pkglist:
        if not os.path.isfile(pkglist):
            _pkgformat = """
{
    "pkgs": [
    "foo",
    "bar",
    ]
}"""
            raise RuntimeError("{} does not exist!\nPlease supply a JSON file "
                               "with the format:{}".format(
                                   pkglist, _pkgformat))

    pool = IOCJson().json_get_value("pool")
    iocroot = IOCJson(pool).json_get_value("iocroot")

    if not os.path.isdir("{}/releases/{}".format(iocroot,
                                                 release)) and not template:
        IOCFetch(release).fetch_release()

    if count == 1:
        try:
            IOCCreate(release,
                      props,
                      0,
                      pkglist,
                      template=template,
                      short=short,
                      basejail=basejail).create_jail()
        except RuntimeError as err:
            lgr.error(err)
            if template:
                lgr.info("Created Templates:")
                templates = IOCList("template", hdr=False,
                                    rtrn_object=True).list_datasets()
                for temp in templates:
                    lgr.info("  {}".format(temp))
    else:
        for j in range(1, count + 1):
            try:
                IOCCreate(release,
                          props,
                          j,
                          pkglist,
                          template=template,
                          short=short,
                          basejail=basejail).create_jail()
            except RuntimeError as err:
                lgr.error(err)
                if template:
                    lgr.info("Created Templates:")
                    templates = IOCList("template",
                                        hdr=False,
                                        rtrn_object=True).list_datasets()
                    for temp in templates:
                        lgr.info("  {}".format(temp))
                exit(1)