Example #1
0
    def execute(self, server, options_dict, non_option_args):
        packages_to_remove = []
        
        for a in non_option_args:
            plist = rcpackageutils.find_package_on_system(server, a)

            if not plist:
                rctalk.error("Unable to find package '" + a + "'")
                sys.exit(1)

            for p in plist:
                dups = filter(lambda x, pn=p:x["name"] == pn["name"],
                              packages_to_remove)

                if dups:
                    rctalk.warning("Duplicate entry found: " + dups[0]["name"])
                else:
                    packages_to_remove.append(p)

        if not packages_to_remove:
            rctalk.message("--- No packages to remove ---")
            sys.exit(0)

        install_deps, remove_deps, dep_info = \
                      resolve_dependencies(server,
                                           [],
                                           packages_to_remove,
                                           [])

        self.transact(server, options_dict,
                      [], [],
                      packages_to_remove, remove_deps)
Example #2
0
def find_remote_package(server, package):
    try:
        import urllib
    except ImportError:
        return None

    # Figure out if the protocol is valid.  Copied mostly from urllib.
    proto, rest = urllib.splittype(package)

    if not proto:
        return None

    name = "open_" + proto
    if "-" in name:
        # replace - with _
        name = string.join(string.split(name, "-"), "_")

    if not hasattr(urllib.URLopener, name):
        return None

    rctalk.message("Fetching %s..." % package)
    u = urllib.URLopener().open(package)
    pdata = ximian_xmlrpclib.Binary(u.read())

    try:
        p = server.rcd.packsys.query_file(pdata)
    except ximian_xmlrpclib.Fault,f :
        if f.faultCode == rcfault.package_not_found:
            return None
        elif f.faultCode == rcfault.invalid_package_file:
            rctalk.warning ("'" + package + "' is not a valid package file")
            return None
        else:
            raise
Example #3
0
def import_commands(rug_dir):
    import glob, imp
    sysdir = rug_dir + "/commands"
    sys.path.append(sysdir)

    loaded_modules = []

    # First load modules in our current directory, for developers, and then
    # out of the system dir.
    files = glob.glob("*cmds.py")
    files = files + glob.glob("%s/*cmds.py" % sysdir)

    for file in files:
        (path, name) = os.path.split(file)
        (name, ext) = os.path.splitext(name)

        if name in loaded_modules:
            continue

        (file, filename, data) = imp.find_module(name, [path])

        try:
            module = imp.load_module(name, file, filename, data)
        except ImportError:
            rctalk.warning("Can't import module " + filename)
        else:
            loaded_modules.append(name)

        if file:
            file.close()
Example #4
0
    def execute(self, server, options_dict, non_option_args):
        packages_to_remove = []

        for a in non_option_args:
            plist = rcpackageutils.find_package_on_system(server, a)

            if not plist:
                rctalk.error("Unable to find package '" + a + "'")
                sys.exit(1)

            for p in plist:
                dups = filter(lambda x, pn=p: x["name"] == pn["name"],
                              packages_to_remove)

                if dups:
                    rctalk.warning("Duplicate entry found: " + dups[0]["name"])
                else:
                    packages_to_remove.append(p)

        if not packages_to_remove:
            rctalk.message("--- No packages to remove ---")
            sys.exit(0)

        install_deps, remove_deps, dep_info = \
                      resolve_dependencies(server,
                                           [],
                                           packages_to_remove,
                                           [])

        self.transact(server, options_dict, [], [], packages_to_remove,
                      remove_deps)
Example #5
0
    def execute(self, server, options_dict, non_option_args):
        if options_dict.has_key("dry-run"):
            dry_run = 1
        else:
            dry_run = 0

        dlist = []

        for d in non_option_args:
            dep = rcpackageutils.parse_dep_str(server, d)

            dups = filter(lambda x, d=dep: x["name"] == d["name"], dlist)

            if dups:
                rctalk.warning("Duplicate entry found: " + dups[0]["name"])

            dlist.append(dep)

        install_deps, remove_deps, dep_info = \
                      resolve_dependencies(server, [], [], dlist)

        if not install_deps and not remove_deps:
            rctalk.message("Requirements are already met on the system.  No "
                           "packages need to be")
            rctalk.message("installed or removed.")
            sys.exit(0)

        self.transact(server, options_dict, [], install_deps, [], remove_deps)
Example #6
0
def import_commands(rug_dir):
    import glob, imp
    sysdir = rug_dir + "/commands"
    sys.path.append(sysdir)

    loaded_modules = []

    # First load modules in our current directory, for developers, and then
    # out of the system dir.
    files = glob.glob("*cmds.py")
    files = files + glob.glob("%s/*cmds.py" % sysdir)
    
    for file in files:
        (path, name) = os.path.split(file)
        (name, ext) = os.path.splitext(name)
        
        if name in loaded_modules:
            continue
        
        (file, filename, data) = imp.find_module(name, [path])

        try:
            module = imp.load_module(name, file, filename, data)
        except ImportError:
            rctalk.warning("Can't import module " + filename)
        else:
            loaded_modules.append(name)

        if file:
            file.close()
Example #7
0
    def execute(self, server, options_dict, non_option_args):
        if options_dict.has_key("dry-run"):
            dry_run = 1
        else:
            dry_run = 0

        dlist = []

        for d in non_option_args:
            dep = rcpackageutils.parse_dep_str(server, d)

            dups = filter(lambda x, d=dep:x["name"] == d["name"], dlist)

            if dups:
                rctalk.warning("Duplicate entry found: " + dups[0]["name"])

            dlist.append(dep)

        install_deps, remove_deps, dep_info = \
                      resolve_dependencies(server, [], [], dlist)

        if not install_deps and not remove_deps:
            rctalk.message("Requirements are already met on the system.  No "
                           "packages need to be")
            rctalk.message("installed or removed.")
            sys.exit(0)

        self.transact(server, options_dict,
                      [], install_deps,
                      [], remove_deps)
Example #8
0
    def execute(self, server, options_dict, non_option_args):

        ## First we assemble our query.

        key = "name"
        if options_dict.has_key("search-action"):
            key = "action"
        elif options_dict.has_key("search-host"):
            key = "host"
        elif options_dict.has_key("search-user"):
            key = "user"

        if options_dict.has_key("match-words"):
            op = "contains_word"
        else:
            op = "contains"

        query = []
        for s in non_option_args:
            query.append([key, op, s])

        if query and options_dict.has_key("match-any"):
            query.insert(0, ["", "begin-or", ""])
            query.append(["", "end-or", ""])

        days_back = 30
        if options_dict.has_key("days-back"):
            db = options_dict["days-back"]
            try:
                db = float(db)
            except:
                db = -1

            if db <= 0:
                rctalk.warning(
                    "Ignoring invalid argument to --days-back option.")
            else:
                days_back = db

        secs_back = int(days_back * 86400)  # 1 day = 86400 sec

        query.append(["cutoff_time", "<=", str(secs_back)])

        ## Pass our query to the server, and get a pile of log entries back.
        ## We need to sort them, since they aren't guaranteed to be in any
        ## particular order.

        entries = server.rcd.log.query_log(query)
        entries.sort(lambda x, y: cmp(x["timestamp"], y["timestamp"]))

        ## The way we display the data depends on how
        ## talkative we have been told to be.

        if rctalk.be_terse:
            log_entries_to_table(entries)
        elif rctalk.show_verbose:
            log_entries_list(entries)
        else:
            log_entries_to_quick_table(entries)
Example #9
0
    def execute(self, server, options_dict, non_option_args):

        ## First we assemble our query.

        key = "name"
        if options_dict.has_key("search-action"):
            key = "action"
        elif options_dict.has_key("search-host"):
            key = "host"
        elif options_dict.has_key("search-user"):
            key = "user"

        if options_dict.has_key("match-words"):
            op = "contains_word"
        else:
            op = "contains"

        query = []
        for s in non_option_args:
            query.append([key, op, s])

        if query and options_dict.has_key("match-any"):
            query.insert(0, ["", "begin-or", ""])
            query.append(["", "end-or", ""])

        days_back = 30
        if options_dict.has_key("days-back"):
            db = options_dict["days-back"]
            try:
                db = float(db)
            except:
                db = -1

            if db <= 0:
                rctalk.warning("Ignoring invalid argument to --days-back option.")
            else:
                days_back = db

        secs_back = int(days_back * 86400)  # 1 day = 86400 sec

        query.append(["cutoff_time", "<=", str(secs_back)])

        ## Pass our query to the server, and get a pile of log entries back.
        ## We need to sort them, since they aren't guaranteed to be in any
        ## particular order.

        entries = server.rcd.log.query_log(query)
        entries.sort(lambda x,y:cmp(x["timestamp"], y["timestamp"]))

        ## The way we display the data depends on how
        ## talkative we have been told to be.

        if rctalk.be_terse:
            log_entries_to_table(entries)
        elif rctalk.show_verbose:
            log_entries_list(entries)
        else:
            log_entries_to_quick_table(entries)
Example #10
0
    def execute(self, server, options_dict, non_option_args):

        users = map(lambda x:x[0], server.rcd.users.get_all())
        valid_privs = map(string.lower, server.rcd.users.get_valid_privileges())
        
        privs = []
        if non_option_args:
            for p in non_option_args[1:]:
                if p and string.lower(p) in valid_privs:
                    privs.append(string.lower(p))
                else:
                    rctalk.warning("Ignoring unrecognized privilege '"+p+"'")

        if non_option_args:
            username = non_option_args[0]
        else:
            print "New Username: "******""
                
            if not username:
                rctalk.message("Exiting")
                sys.exit(0)
                
            if not re.compile("^\w+$").match(username):
                rctalk.error("Invalid user name")
                sys.exit(1)

        if username in users:
            rctalk.error("User '" + username + "' already exists.")
            sys.exit(1)

        passwd = get_password()
        if not passwd:
            rctalk.message("Exiting.")
            sys.exit(0)

        if not privs and "view" in valid_privs:
            privs = ["view"]

        privs = get_privileges(privs, valid_privs)
        privs_str = string.join(privs, ", ")

        rc = server.rcd.users.update(username, passwd, privs_str)

        rctalk.message("")

        if rc:
            rctalk.message("User '" + username + "' added.")
        else:
            rctalk.error("User '" + username + "' could not be added.")
Example #11
0
    def execute(self, server, options_dict, non_option_args):

        no_abbrev = options_dict.has_key("no-abbrev") or \
                    options_dict.has_key("terse")

        min_importance = None
        if options_dict.has_key("importance"):
            if not rcpackageutils.update_importances.has_key(
                    options_dict["importance"]):
                rctalk.warning("Invalid importance: " +
                               options_dict["importance"])
            else:
                min_importance = rcpackageutils.update_importances[
                    options_dict["importance"]]

        update_list = rcpackageutils.get_updates(server,
                                                 non_option_args,
                                                 allow_dups=1)

        if min_importance != None:
            up = []
            for u in update_list:
                # higher priorities have lower numbers... i know, i know...
                if u[1]["importance_num"] <= min_importance:
                    up.append(u)
        else:
            up = update_list

        if not up:
            if non_option_args:
                rctalk.message(
                    "No updates are available in the specified channels.")
            else:
                rctalk.message("No updates are available.")

                if not filter(lambda x: x["subscribed"],
                              rcchannelutils.get_channels(server)):
                    rctalk.message("")
                    rctalk.warning(
                        "Updates are only visible when you are subscribed to a channel."
                    )
            sys.exit(0)

        if rctalk.show_verbose:
            verbose_updates_list(server, up)
        elif rctalk.be_terse:
            terse_updates_table(server, up)
        else:
            exploded_updates_table(server, up, no_abbrev)
Example #12
0
    def confirm(self, options_dict, removals):
        if not options_dict.has_key("no-confirmation"):
            confirm = rctalk.prompt("Do you want to continue? [y/N]")
            if not confirm or not (confirm[0] == "y" or confirm[0] == "Y"):
                rctalk.message("Cancelled.")
                sys.exit(0)

        allow_remove = self.unattended_removals() \
                       or options_dict.has_key("allow-removals")

        if removals \
           and options_dict.has_key("no-confirmation") \
           and not allow_remove:
            rctalk.warning("Removals are required.  Use the -r option or "
                           "confirm interactively.")
            sys.exit(1)            
Example #13
0
    def confirm(self, options_dict, removals):
        if not options_dict.has_key("no-confirmation"):
            confirm = rctalk.prompt("Do you want to continue? [y/N]")
            if not confirm or not (confirm[0] == "y" or confirm[0] == "Y"):
                rctalk.message("Cancelled.")
                sys.exit(0)

        allow_remove = self.unattended_removals() \
                       or options_dict.has_key("allow-removals")

        if removals \
           and options_dict.has_key("no-confirmation") \
           and not allow_remove:
            rctalk.warning("Removals are required.  Use the -r option or "
                           "confirm interactively.")
            sys.exit(1)
Example #14
0
    def execute(self, server, options_dict, non_option_args):

        if options_dict.has_key("strict"):
            all_users = map(lambda x:x[0], server.rcd.users.get_all())
            failed = 0
            for username in non_option_args:
                if not username in all_users:
                    rctalk.warning("User '" + username + "' does not exist")
                    failed = 1
            if failed:
                rctalk.error("User deletion cancelled")
        
        for username in non_option_args:
            if not server.rcd.users.remove(username):
                rctalk.warning("Attempt to delete user '" + username + "' failed")
            else:
                rctalk.message("User '" + username + "' deleted.")
Example #15
0
    def execute(self, server, options_dict, non_option_args):

        service = None
        if options_dict.has_key("service"):
            services = rcserviceutils.get_services(server)
            service = rcserviceutils.find_service(services,
                                                  options_dict["service"])

            if not service:
                rctalk.error("Unknown service '%s'" % options_dict["service"])
                sys.exit(1)

        failed = 0
        to_do = []
        if options_dict.has_key("all"):
            to_do = filter(lambda c:not c["hidden"],
                           rcchannelutils.get_channels(server))
            if service:
                to_do = filter(lambda c,s=service:c.get("service") == s["id"],
                               to_do)
        else:
            for a in non_option_args:
                clist = rcchannelutils.get_channels_by_name(server, a, service)
                if not rcchannelutils.validate_channel_list(a, clist):
                    failed = 1
                else:
                    c = clist[0]
                    to_do.append(c)
                    if options_dict.has_key("strict") and not c["subscribed"]:
                        rctalk.error("Not subscribed to channel " + \
                                     rcchannelutils.channel_to_str(c))
                        failed = 1

        if failed:
            sys.exit(1)

        for c in to_do:
            if c:
                if server.rcd.packsys.unsubscribe(c["id"]):
                    rctalk.message("Unsubscribed from channel " + \
                                   rcchannelutils.channel_to_str(c))
                else:
                    rctalk.warning("Attempt to unsubscribe to channel " + \
                                   rcchannelutils.channel_to_str(c) + " failed")
Example #16
0
def get_updates(server, non_option_args, allow_dups=0):
    up = server.rcd.packsys.get_updates()

    # If channels are specified by the command line, filter out all except
    # for updates from those channels.
    if non_option_args:
        channel_id_list = []
        failed = 0
        for a in non_option_args:
            clist = rcchannelutils.get_channels_by_name(server, a)
            if not rcchannelutils.validate_channel_list(a, clist):
                failed = 1
            else:
                c = clist[0]
                if c["subscribed"]:
                    channel_id_list.append(c["id"])
                else:
                    rctalk.warning("You are not subscribed to "
                                   + rcchannelutils.channel_to_str(c)
                                   + ", so no updates are available.")
                    
        if failed:
            sys.exit(1)

        up = filter(lambda x, cidl=channel_id_list:x[1]["channel"] in cidl, up)

    # Filter out exact duplicates
    if not allow_dups:
        def pkg_to_key(p):
            return "%s:%d:%s:%s" % \
                   (p["name"], p["epoch"], p["version"], p["release"])

        dup_dict = {}
        for u in up:
            key = pkg_to_key(u[1]) # u[1] is the new version of the package
            if not dup_dict.has_key(key):
                dup_dict[key] = u

        up = dup_dict.values()

        del dup_dict

    return up
Example #17
0
    def execute(self, server, options_dict, non_option_args):

        if not non_option_args:
            self.usage()
            sys.exit(1)

        path = os.path.abspath(non_option_args[0])
        path_base = os.path.basename(path)

        aliases = map(rcchannelutils.get_channel_alias,
                      rcchannelutils.get_channels(server))

        complain_about_collision = 0
        alias = string.lower(path_base)
        if options_dict.has_key("alias"):
            alias = options_dict["alias"]
            complain_about_collision = 1

        # Ensure we don't have an alias collision
        old_alias = alias
        count = 1
        while alias in aliases:
            alias = "%s-%d" % (old_alias, count)
            count = count + 1

        if old_alias != alias and complain_about_collision:
            rctalk.warning("Alias '%s' already in use.  Using '%s' instead." %
                           (old_alias, alias))

        name = options_dict.get("name", path)
        if options_dict.has_key("recurse"):
            recursive = 1
        else:
            recursive = 0

        try:
            server.rcd.packsys.mount_directory(path, name, alias, recursive)
        except ximian_xmlrpclib.Fault, f:
            if f.faultCode == rcfault.invalid_service:
                rctalk.error(f.faultString)
                sys.exit(1)
            else:
                raise
Example #18
0
    def execute(self, server, options_dict, non_option_args):

        if not non_option_args:
            self.usage()
            sys.exit(1)

        path = os.path.abspath(non_option_args[0])
        path_base = os.path.basename(path)

        aliases = map(rcchannelutils.get_channel_alias,
                      rcchannelutils.get_channels(server))

        complain_about_collision = 0
        alias = string.lower(path_base)
        if options_dict.has_key("alias"):
            alias = options_dict["alias"]
            complain_about_collision = 1

        # Ensure we don't have an alias collision
        old_alias = alias
        count = 1
        while alias in aliases:
            alias = "%s-%d" % (old_alias, count)
            count = count + 1

        if old_alias != alias and complain_about_collision:
            rctalk.warning("Alias '%s' already in use.  Using '%s' instead." %
                           (old_alias, alias))

        name = options_dict.get("name", path)
        if options_dict.has_key("recurse"):
            recursive = 1
        else:
            recursive = 0

        try:
            server.rcd.packsys.mount_directory(path, name, alias, recursive)
        except ximian_xmlrpclib.Fault, f:
            if f.faultCode == rcfault.invalid_service:
                rctalk.error(f.faultString)
                sys.exit(1)
            else:
                raise
Example #19
0
    def execute(self, server, options_dict, non_option_args):

        no_abbrev = options_dict.has_key("no-abbrev") or \
                    options_dict.has_key("terse")

        min_importance = None
        if options_dict.has_key("importance"):
            if not rcpackageutils.update_importances.has_key(options_dict["importance"]):
                rctalk.warning("Invalid importance: " +
                               options_dict["importance"])
            else:
                min_importance = rcpackageutils.update_importances[options_dict["importance"]]

        update_list = rcpackageutils.get_updates(server, non_option_args,
                                                 allow_dups=1)

        if min_importance != None:
            up = []
            for u in update_list:
                # higher priorities have lower numbers... i know, i know...
                if u[1]["importance_num"] <= min_importance:
                    up.append(u)
        else:
            up = update_list
        
        if not up:
            if non_option_args:
                rctalk.message("No updates are available in the specified channels.")
            else:
                rctalk.message("No updates are available.")

                if not filter(lambda x:x["subscribed"], rcchannelutils.get_channels(server)):
                    rctalk.message("")
                    rctalk.warning("Updates are only visible when you are subscribed to a channel.")
            sys.exit(0)

        if rctalk.show_verbose:
            verbose_updates_list(server, up)
        elif rctalk.be_terse:
            terse_updates_table(server, up)
        else:
            exploded_updates_table(server, up, no_abbrev)
Example #20
0
    def execute(self, server, options_dict, non_option_args):

        results = server.rcd.system.ping ()

        if results:
            rctalk.message("Daemon identified itself as:")

            if results.has_key("name"):
                rctalk.message("  " + results["name"])
            else:
                rctalk.warning("Server did not return a name.")

            if results.has_key("copyright"):
                rctalk.message("  " + results["copyright"])
            else:
                rctalk.warning("Daemon did not return copyright information.")

            # Exit normally if we could ping the server
            return

        # And exit abnormally if we couldn't.
        sys.exit(1)
Example #21
0
    def execute(self, server, options_dict, non_option_args):

        results = server.rcd.system.ping()

        if results:
            rctalk.message("Daemon identified itself as:")

            if results.has_key("name"):
                rctalk.message("  " + results["name"])
            else:
                rctalk.warning("Server did not return a name.")

            if results.has_key("copyright"):
                rctalk.message("  " + results["copyright"])
            else:
                rctalk.warning("Daemon did not return copyright information.")

            # Exit normally if we could ping the server
            return

        # And exit abnormally if we couldn't.
        sys.exit(1)
Example #22
0
    def execute(self, server, options_dict, non_option_args):
        headers = ["Name", "Value"]
        pref_table = []
        
        if not non_option_args:
            if options_dict.has_key("no-descriptions"):
                f = lambda p:[p["name"], str(p["value"])]
            else:
                headers.append("Description")
                f = lambda p:[p["name"], str(p["value"]), p["description"]]

            pref_table = map(f, server.rcd.prefs.list_prefs())
        else:
            for a in non_option_args:
                try:
                    p = server.rcd.prefs.get_pref(a)
                except ximian_xmlrpclib.Fault, f:
                    if f.faultCode == rcfault.invalid_preference:
                        rctalk.warning("There is no preference named '" + a + "'")
                    else:
                        raise
                else:
                    pref_table.append([a, str(p)])
Example #23
0
def extract_command_from_argv(argv):
    command = None
    i = 0
    unknown_commands = []
    while i < len(argv) and not command:
        if argv[i][0] != "-":
            command = construct(argv[i])
            if command:
                argv.pop(i)
            else:
                unknown_commands.append(argv[i])
        else:
            takes_arg = 0
            for o in default_opt_table:
                if not (argv[i][1:] == o[0] or argv[i][2:] == o[1]):
                    continue

                if o[2] != "":
                    takes_arg = 1
                    break

            if takes_arg and string.find(argv[i], "=") == -1:
                i = i + 1

        i = i + 1

    if not command:
        map(lambda x: rctalk.warning("Unknown command '%s'" % x),
            unknown_commands)
        rctalk.warning("No command found on command line.")
        if "--help" in argv or "-?" in argv:
            usage_full()
        else:
            usage_basic()
        sys.exit(1)

    return command
Example #24
0
    def execute(self, server, options_dict, non_option_args):

        locks = server.rcd.packsys.get_locks()
        
        to_delete = []
        indices = []
        for x in non_option_args:
            success = 1
            try:
                i = int(x)
            except:
                success = 0

            if success:
                if 0 <= i-1 < len(locks):
                    indices.append(i)
                    to_delete.append(locks[i-1])
                else:
                    success = 0

            if not success:
                rctalk.warning("Ignoring invalid lock number '%s'" % x)

        if not to_delete:
            rctalk.warning("No valid lock numbers specified.")
            sys.exit(1)

        table = locks_to_table(server, to_delete, 1)
        for row, i in map(lambda x, y:(x, y), table, indices):
            row.insert(0, str(i))

        rcformat.tabular(["#", "Pattern", "Channel", "Importance"], table)

        if not options_dict.has_key("no-confirmation"):
            rctalk.message("")
            if len(to_delete) == 1:
                msg = "this lock"
            else:
                msg = "these locks"
            confirm = rctalk.prompt("Delete %s? [y/N]" % msg)
            if not confirm or not string.lower(confirm[0]) == "y":
                rctalk.message("Cancelled.")
                sys.exit(0)

        failures = []
        for l, i in map(lambda x, y: (x, y), to_delete, indices):
            retval = server.rcd.packsys.remove_lock(l)
            if not retval:
                failures.append(i)

        if failures:
            rctalk.warning("Unable to remove lock%s %s",
                           (len(failures) > 1 and "s") or "",
                           string.join(map(str, failures), ", "))
            sys.exit(1)
Example #25
0
    def execute(self, server, options_dict, non_option_args):

        locks = server.rcd.packsys.get_locks()

        to_delete = []
        indices = []
        for x in non_option_args:
            success = 1
            try:
                i = int(x)
            except:
                success = 0

            if success:
                if 0 <= i - 1 < len(locks):
                    indices.append(i)
                    to_delete.append(locks[i - 1])
                else:
                    success = 0

            if not success:
                rctalk.warning("Ignoring invalid lock number '%s'" % x)

        if not to_delete:
            rctalk.warning("No valid lock numbers specified.")
            sys.exit(1)

        table = locks_to_table(server, to_delete, 1)
        for row, i in map(lambda x, y: (x, y), table, indices):
            row.insert(0, str(i))

        rcformat.tabular(["#", "Pattern", "Channel", "Importance"], table)

        if not options_dict.has_key("no-confirmation"):
            rctalk.message("")
            if len(to_delete) == 1:
                msg = "this lock"
            else:
                msg = "these locks"
            confirm = rctalk.prompt("Delete %s? [y/N]" % msg)
            if not confirm or not string.lower(confirm[0]) == "y":
                rctalk.message("Cancelled.")
                sys.exit(0)

        failures = []
        for l, i in map(lambda x, y: (x, y), to_delete, indices):
            retval = server.rcd.packsys.remove_lock(l)
            if not retval:
                failures.append(i)

        if failures:
            rctalk.warning("Unable to remove lock%s %s",
                           (len(failures) > 1 and "s") or "",
                           string.join(map(str, failures), ", "))
            sys.exit(1)
Example #26
0
def validate_channel_list(name, chan_list):

    if len(chan_list) == 0:
        rctalk.warning("Invalid channel: '" + name + "'")
        return 0
    elif len(chan_list) > 1:
        rctalk.warning("Ambiguous channel: '" + name + "' matches")
        for c in chan_list:
            rctalk.warning("  " + c["name"])
        return 0

    cname = chan_list[0]["name"]
    if string.lower(name) != string.lower(cname) \
       and name != chan_list[0]["id"]:
        if not rctalk.be_terse:
            rctalk.message("'" + name + "' matches '" + cname + "'")

    return 1
Example #27
0
def get_privileges(initial, in_legal):

    legal = in_legal
    legal.sort()
    legal.append("superuser")

    current = {}
    for priv in initial:
        if string.lower(priv) in legal:
            current[string.lower(priv)] = 1

    rctalk.message("")
    rctalk.message("At the prompt, type +/- followed by a privilege name to add/remove")
    rctalk.message("that privilege.  To accept the current set of privileges, press return.")

    while 1:
        table = []
        for l in legal:
            if current.has_key("superuser") or current.has_key(l):
                flag = "yes"
            else:
                flag = "no"

            table.append([l, flag])

        rctalk.message("")
        rctalk.message("Current Privileges:")
        rcformat.aligned(table)

        print "Changes: ",
        changes = string.split(sys.stdin.readline())

        if not changes:
            return current.keys()

        # Yuck.  Handle spaces between "+"/"-" and priv name
        max = len(changes)
        filter = []
        i = 0
        while i < max:
            # If "+" or "-" is by itself and not the last thing on the line
            if changes[i] in ("+", "-") and i+1 < max:
                filter.append(changes[i] + changes[i+1])
                i = i + 1
            else:
                filter.append(changes[i])

            i = i + 1

        changes = filter
        
        for change in changes:
            x = string.lower(change)
            valid = 0
            if len(x) > 1:
                pm = x[0]
                priv = x[1:]

                if pm in ["+", "-"] and priv in legal:
                    if pm == "+":
                        current[priv] = 1
                        valid = 1
                    elif pm == "-":
                        if current.has_key(priv):
                            del current[priv]
                        valid = 1

            if not valid:
                rctalk.warning("Ignoring invalid privilege setting \"" + change + "\"")
Example #28
0
    def poll_transaction(self, server, download_id, transact_id, step_id):

        message_offset = 0
        download_complete = 0

        while 1:
            try:
                if download_id != -1 and not download_complete:
                    pending = server.rcd.system.poll_pending(download_id)

                    rctalk.message_status(rcformat.pending_to_str(pending))

                    if pending["status"] == "finished":
                        rctalk.message_finished("Download complete")
                        download_complete = 1
                    elif pending["status"] == "failed":
                        rctalk.message_finished("Download failed: %s" % pending["error_msg"])
                        sys.exit(1)
                elif transact_id == -1:
                    # We're in "download only" mode.
                    if download_complete:
                        break
                    elif download_id == -1:
                        # We're in "download only" mode, but everything we
                        # wanted to download is already cached on the system.
                        rctalk.message_finished("Nothing to download")
                        break
                else:
                    pending = server.rcd.system.poll_pending(transact_id)
                    step_pending = server.rcd.system.poll_pending(step_id)

                    message_len = len(pending["messages"])
                    if message_len > message_offset:
                        for e in pending["messages"][message_offset:]:
                            rctalk.message_finished(rcformat.transaction_status(e))
                        message_offset = message_len

                    message_or_message_finished = rctalk.message

                    if step_pending["status"] == "running":
                        rctalk.message_status(rcformat.pending_to_str(step_pending, time=0))

                    if pending["status"] == "finished":
                        rctalk.message_finished("Transaction finished")
                        break
                    elif pending["status"] == "failed":
                        rctalk.message_finished("Transaction failed: %s" % pending["error_msg"],
                                                force_output=1)
                        sys.exit(1)

                time.sleep(0.4)
            except KeyboardInterrupt:
                if download_id != -1 and not download_complete:
                    rctalk.message("")
                    rctalk.message("Cancelling download...")
                    v = server.rcd.packsys.abort_download(download_id)
                    if v:
                        sys.exit(1)
                    else:
                        rctalk.warning("Transaction cannot be cancelled")
                else:
                    rctalk.warning("Transaction cannot be cancelled")
Example #29
0
    def execute(self, server, options_dict, non_option_args):

        channels = rcchannelutils.get_channels(server)
        channel_table = []

        if options_dict.has_key("service"):
            services = rcserviceutils.get_services(server)
            service = rcserviceutils.find_service(services,
                                                  options_dict["service"])

            if not service:
                rctalk.error("Unknown service '%s'" % options_dict["service"])
                sys.exit(1)

            channels = filter(lambda c,s=service:c.get("service") == s["id"],
                              channels)

        headers = ["subd?", "Alias", "Name"]
        if options_dict.has_key("show-ids"):
            headers.insert(2, "ID")
        if options_dict.has_key("show-services"):
            headers.append("Service")

        for c in channels:

            show = 1

            if c["hidden"]:
                show = 0

            if c["subscribed"]:
                if rctalk.be_terse:
                    subflag = "Yes"
                else:
                    subflag = " Yes "
                if options_dict.has_key("unsubscribed"):
                    show = 0
            else:
                subflag = ""
                if options_dict.has_key("subscribed"):
                    show = 0

            if options_dict.has_key("mounted") and not c["mounted"]:
                show = 0

            if show:
                row = [subflag, rcchannelutils.get_channel_alias(c), c["name"]]
                if options_dict.has_key("show-ids"):
                    row.insert(2, c["id"])
                if options_dict.has_key("show-services"):
                    services = rcserviceutils.get_services(server)
                    service = rcserviceutils.find_service(services, c["service"])
                    row.append(service["name"])
                channel_table.append(row)

        if channel_table:
            channel_table.sort(lambda x, y:cmp(x[2],y[2]))
            rcformat.tabular(headers, channel_table)
        else:
            if options_dict.has_key("unsubscribed"):
                rctalk.message("--- No unsubscribed channels ---")
            elif options_dict.has_key("subscribed"):
                rctalk.message("--- No subscribed channels ---")
            elif options_dict.has_key("mounted"):
                rctalk.message("--- No mounted channels ---")
            else:
                rctalk.warning("--- No channels available ---")
Example #30
0
            if f.faultCode == rcfault.cant_activate \
                   or f.faultCode == rcfault.invalid_service:

                err_str = f.faultString
                success = 0
            else:
                raise
        else:
            success = 1

        if success:
            rctalk.message("System successfully activated")

            if not options_dict.has_key("no-refresh"):
                rcchannelutils.refresh_channels(server)

        else:
            if not err_str:
                err_str = "Invalid activation code or email address"

            rctalk.warning("System could not be activated: %s" % err_str)
            sys.exit(1)


rccommand.register(ServiceListCmd)
rccommand.register(ServiceAddCmd)
rccommand.register(ServiceDeleteCmd)
rccommand.register(ServiceMirrorsCmd)
rccommand.register(ServiceRefreshCmd)
rccommand.register(ServiceActivateCmd)
Example #31
0
    def execute(self, server, options_dict, non_option_args):

        if len(non_option_args) < 1:
            self.usage()
            sys.exit(1)

        match = {}

        # Split non-option args on whitespace, reassembling the
        # pieces into a new list.
        non_option_args = reduce(lambda x, y: x + y,
                                 map(string.split, non_option_args))

        if len(non_option_args) == 3:
            name, relation, version = non_option_args

            if "?" in name or "*" in name:
                rctalk.warning(
                    "Wildcards are not allowed when specifying versioned locks."
                )
                sys.exit(1)

            valid_relations = ("=", "<", ">", "<=", ">=")
            if relation not in valid_relations:
                valid_str = string.join(
                    map(lambda x: "'%s'" % x, valid_relations), ", ")
                rctalk.warning("'%s' is not a valid relation." % relation)
                rctalk.warning("Valid relations are: %s" % valid_str)
                sys.exit(1)

            match["dep"] = {
                "name": name,
                "relation": relation,
                "version_str": version
            }

        elif len(non_option_args) == 1:
            glob = non_option_args[0]
            # FIXME: It would be nice to verify that the incoming glob
            # is valid.  (It probably shouldn't contain whitespace, shouldn't
            # be the empty string, etc.)
            match["glob"] = glob
        elif len(non_option_args) != 0:
            rctalk.error("Unrecognized input \"%s\"" %
                         string.join(non_option_args, " "))
            sys.exit(1)

        if options_dict.has_key("channel"):
            cname = options_dict["channel"]
            clist = rcchannelutils.get_channels_by_name(server, cname)
            if not rcchannelutils.validate_channel_list(cname, clist):
                sys.exit(1)
            match["channel"] = clist[0]["id"]

        if options_dict.has_key("name"):
            # FIXME: It would be nice to verify that the incoming glob
            # is valid.  (It probably shouldn't contain whitespace, shouldn't
            # be the empty string, etc.)
            match["glob"] = options_dict["name"]

        if options_dict.has_key("importance"):
            num = rcformat.importance_str_to_num(options_dict["importance"])
            if num < 0:
                rctalk.error("'%s' is not a valid importance level" %
                             options_dict["importance"])
                sys.exit(1)

            # We want to match (i.e. lock) all packages below the given
            # importance.  Remember, in a match the opposite of >= is
            # <=, not <.  (Maybe this is broken, but it seems pretty
            # unnecessary to offer the full selection of comparison
            # operators.)
            match["importance_num"] = num
            match["importance_gteq"] = 0

        # FIXME: validate that the match isn't empty, etc.
        server.rcd.packsys.add_lock(match)

        rctalk.message("--- Added Lock ---")
        display_match(server, match)
Example #32
0
    def poll_transaction(self, server, download_id, transact_id, step_id):

        message_offset = 0
        download_complete = 0

        while 1:
            try:
                if download_id != -1 and not download_complete:
                    pending = server.rcd.system.poll_pending(download_id)

                    rctalk.message_status(rcformat.pending_to_str(pending))

                    if pending["status"] == "finished":
                        rctalk.message_finished("Download complete")
                        download_complete = 1
                    elif pending["status"] == "failed":
                        rctalk.message_finished("Download failed: %s" % pending["error_msg"])
                        sys.exit(1)
                elif transact_id == -1:
                    # We're in "download only" mode.
                    if download_complete:
                        break
                    elif download_id == -1:
                        # We're in "download only" mode, but everything we
                        # wanted to download is already cached on the system.
                        rctalk.message_finished("Nothing to download")
                        break
                else:
                    pending = server.rcd.system.poll_pending(transact_id)
                    step_pending = server.rcd.system.poll_pending(step_id)

                    message_len = len(pending["messages"])
                    if message_len > message_offset:
                        for e in pending["messages"][message_offset:]:
                            if e[:len("patch")] == "patch":
                                ## Patch messages look something like:
                                ## "patch:Error installing 'foo'\n\n
                                ## Skip this patch or abort the update?"
                                ##
                                ## First, remove the "patch: identifier,
                                ## then the question from the end
                                (id,m) = string.split(e, ":", 1)
                                if m.index("\n\n") > 0:
                                    m = m[:m.index("\n\n")]
                                rctalk.message_status("Warning: %s\n" % m)
                            else:
                                rctalk.message_finished(rcformat.transaction_status(e))
                        message_offset = message_len

                    message_or_message_finished = rctalk.message

                    if step_pending["status"] == "running":
                        rctalk.message_status(rcformat.pending_to_str(step_pending, time=0))

                    if pending["status"] == "finished":
                        rctalk.message_finished("Transaction finished")
                        break
                    elif pending["status"] == "failed":
                        rctalk.message_finished("Transaction failed: %s" % pending["error_msg"],
                                                force_output=1)
                        sys.exit(1)

                time.sleep(0.4)
            except KeyboardInterrupt:
                if download_id != -1 and not download_complete:
                    rctalk.message("")
                    rctalk.message("Cancelling download...")
                    try:
                        v = server.rcd.you.abort_download(download_id)
                        if v:
                            sys.exit(1)
                    except ximian_xmlrpclib.Fault:
                            pass

                rctalk.warning("Transaction cannot be cancelled")
Example #33
0
    def poll_transaction(self, server, download_id, transact_id, step_id):

        message_offset = 0
        download_complete = 0

        while 1:
            try:
                if download_id != -1 and not download_complete:
                    pending = server.rcd.system.poll_pending(download_id)

                    rctalk.message_status(rcformat.pending_to_str(pending))

                    if pending["status"] == "finished":
                        rctalk.message_finished("Download complete")
                        download_complete = 1
                    elif pending["status"] == "failed":
                        rctalk.message_finished("Download failed: %s" %
                                                pending["error_msg"])
                        sys.exit(1)
                elif transact_id == -1:
                    # We're in "download only" mode.
                    if download_complete:
                        break
                    elif download_id == -1:
                        # We're in "download only" mode, but everything we
                        # wanted to download is already cached on the system.
                        rctalk.message_finished("Nothing to download")
                        break
                else:
                    pending = server.rcd.system.poll_pending(transact_id)
                    step_pending = server.rcd.system.poll_pending(step_id)

                    message_len = len(pending["messages"])
                    if message_len > message_offset:
                        for e in pending["messages"][message_offset:]:
                            rctalk.message_finished(
                                rcformat.transaction_status(e))
                        message_offset = message_len

                    message_or_message_finished = rctalk.message

                    if step_pending["status"] == "running":
                        rctalk.message_status(
                            rcformat.pending_to_str(step_pending, time=0))

                    if pending["status"] == "finished":
                        rctalk.message_finished("Transaction finished")
                        break
                    elif pending["status"] == "failed":
                        rctalk.message_finished("Transaction failed: %s" %
                                                pending["error_msg"],
                                                force_output=1)
                        sys.exit(1)

                time.sleep(0.4)
            except KeyboardInterrupt:
                if download_id != -1 and not download_complete:
                    rctalk.message("")
                    rctalk.message("Cancelling download...")
                    v = server.rcd.packsys.abort_download(download_id)
                    if v:
                        sys.exit(1)
                    else:
                        rctalk.warning("Transaction cannot be cancelled")
                else:
                    rctalk.warning("Transaction cannot be cancelled")
Example #34
0
    def poll_transaction(self, server, download_id, transact_id, step_id):

        message_offset = 0
        download_complete = 0

        while 1:
            try:
                if download_id != -1 and not download_complete:
                    pending = server.rcd.system.poll_pending(download_id)

                    rctalk.message_status(rcformat.pending_to_str(pending))

                    if pending["status"] == "finished":
                        rctalk.message_finished("Download complete")
                        download_complete = 1
                    elif pending["status"] == "failed":
                        rctalk.message_finished("Download failed: %s" %
                                                pending["error_msg"])
                        sys.exit(1)
                elif transact_id == -1:
                    # We're in "download only" mode.
                    if download_complete:
                        break
                    elif download_id == -1:
                        # We're in "download only" mode, but everything we
                        # wanted to download is already cached on the system.
                        rctalk.message_finished("Nothing to download")
                        break
                else:
                    pending = server.rcd.system.poll_pending(transact_id)
                    step_pending = server.rcd.system.poll_pending(step_id)

                    message_len = len(pending["messages"])
                    if message_len > message_offset:
                        for e in pending["messages"][message_offset:]:
                            if e[:len("patch")] == "patch":
                                ## Patch messages look something like:
                                ## "patch:Error installing 'foo'\n\n
                                ## Skip this patch or abort the update?"
                                ##
                                ## First, remove the "patch: identifier,
                                ## then the question from the end
                                (id, m) = string.split(e, ":", 1)
                                if m.index("\n\n") > 0:
                                    m = m[:m.index("\n\n")]
                                rctalk.message_status("Warning: %s\n" % m)
                            else:
                                rctalk.message_finished(
                                    rcformat.transaction_status(e))
                        message_offset = message_len

                    message_or_message_finished = rctalk.message

                    if step_pending["status"] == "running":
                        rctalk.message_status(
                            rcformat.pending_to_str(step_pending, time=0))

                    if pending["status"] == "finished":
                        rctalk.message_finished("Transaction finished")
                        break
                    elif pending["status"] == "failed":
                        rctalk.message_finished("Transaction failed: %s" %
                                                pending["error_msg"],
                                                force_output=1)
                        sys.exit(1)

                time.sleep(0.4)
            except KeyboardInterrupt:
                if download_id != -1 and not download_complete:
                    rctalk.message("")
                    rctalk.message("Cancelling download...")
                    try:
                        v = server.rcd.you.abort_download(download_id)
                        if v:
                            sys.exit(1)
                    except ximian_xmlrpclib.Fault:
                        pass

                rctalk.warning("Transaction cannot be cancelled")
Example #35
0
    def execute(self, server, options_dict, non_option_args):

        if len(non_option_args) < 1:
            self.usage()
            sys.exit(1)

        match = {}

        # Split non-option args on whitespace, reassembling the
        # pieces into a new list.
        non_option_args = reduce(lambda x,y: x+y,
                                 map(string.split, non_option_args))

        if len(non_option_args) == 3:
            name, relation, version = non_option_args

            if "?" in name or "*" in name:
                rctalk.warning("Wildcards are not allowed when specifying versioned locks.")
                sys.exit(1)

            valid_relations = ("=", "<", ">", "<=", ">=")
            if relation not in valid_relations:
                valid_str = string.join(map(lambda x: "'%s'" % x, valid_relations), ", ")
                rctalk.warning("'%s' is not a valid relation." % relation)
                rctalk.warning("Valid relations are: %s" % valid_str)
                sys.exit(1)

            match["dep"] = {"name": name,
                            "relation":relation,
                            "version_str":version }
            
        elif len(non_option_args) == 1:
            glob = non_option_args[0]
            # FIXME: It would be nice to verify that the incoming glob
            # is valid.  (It probably shouldn't contain whitespace, shouldn't
            # be the empty string, etc.)
            match["glob"] = glob
        elif len(non_option_args) != 0:
            rctalk.error("Unrecognized input \"%s\"" %
                         string.join(non_option_args, " "))
            sys.exit(1)
            
        if options_dict.has_key("channel"):
            cname = options_dict["channel"]
            clist = rcchannelutils.get_channels_by_name(server, cname)
            if not rcchannelutils.validate_channel_list(cname, clist):
                sys.exit(1)
            match["channel"] = clist[0]["id"]

        if options_dict.has_key("name"):
            # FIXME: It would be nice to verify that the incoming glob
            # is valid.  (It probably shouldn't contain whitespace, shouldn't
            # be the empty string, etc.)
            match["glob"] = options_dict["name"]

        if options_dict.has_key("importance"):
            num = rcformat.importance_str_to_num(options_dict["importance"])
            if num < 0:
                rctalk.error("'%s' is not a valid importance level" %
                             options_dict["importance"])
                sys.exit(1)

            # We want to match (i.e. lock) all packages below the given
            # importance.  Remember, in a match the opposite of >= is
            # <=, not <.  (Maybe this is broken, but it seems pretty
            # unnecessary to offer the full selection of comparison
            # operators.)
            match["importance_num"] = num
            match["importance_gteq"] = 0

        # FIXME: validate that the match isn't empty, etc.
        server.rcd.packsys.add_lock(match)

        rctalk.message("--- Added Lock ---")
        display_match(server, match)
Example #36
0
        except ximian_xmlrpclib.Fault, f:
            if f.faultCode == rcfault.cant_activate \
                   or f.faultCode == rcfault.invalid_service:
                
                err_str = f.faultString
                success = 0
            else:
                raise
        else:
            success = 1

        if success:
            rctalk.message("System successfully activated")

            if not options_dict.has_key("no-refresh"):
                rcchannelutils.refresh_channels(server)
            
        else:
            if not err_str:
                err_str = "Invalid activation code or email address"
            
            rctalk.warning("System could not be activated: %s" % err_str)
            sys.exit(1)

rccommand.register(ServiceListCmd)
rccommand.register(ServiceAddCmd)
rccommand.register(ServiceDeleteCmd)
rccommand.register(ServiceMirrorsCmd)
rccommand.register(ServiceRefreshCmd)
rccommand.register(ServiceActivateCmd)
Example #37
0
            return None
        else:
            raise

    if rcmain.local:
        pdata = os.path.abspath(package)
    else:
        pdata = ximian_xmlrpclib.Binary(open(package).read())

    try:
        p = server.rcd.packsys.query_file(pdata)
    except ximian_xmlrpclib.Fault, f:
        if f.faultCode == rcfault.package_not_found:
            return None
        elif f.faultCode == rcfault.invalid_package_file:
            rctalk.warning ("'" + package + "' is not a valid package file")
            return None
        else:
            raise

    if rcmain.local:
        p["package_filename"] = pdata
    else:
        p["package_data"] = pdata

    return p


def find_package(server, str, allow_unsub, allow_system=1):

    channel = None