Exemple #1
0
    def handle(self, *args, **options):
        if DeviceMetadata.objects.filter(is_own_device=True).count() > 0:
            raise CommandError("Error: This device has already been initialized; aborting.\n")

        name        = args[0] if (len(args) >= 1 and args[0]) else get_host_name()
        description = args[1] if (len(args) >= 2 and args[1]) else ""
        data_file   = args[2] if (len(args) >= 3 and args[2]) else self.data_json_file

        own_device = Device.initialize_own_device(name=name, description=description)
        self.stdout.write("Device '%s'%s has been successfully initialized.\n"
            % (name, description and (" ('%s')" % description) or ""))

        # Nothing to do with a central server
        if settings.CENTRAL_SERVER:
            return

        # Now we're definitely not central server, so ... go for it!
        # Import a zone (for machines sharing zones), and join if it works!
        invitation = None
        if not os.path.exists(data_file):
            sys.stderr.write("Could not find resource file %s.  This may cause warnings to appear when updating your KA Lite version.\n" % data_file)
        else:
            try:
                invitation = load_data_for_offline_install(in_file=data_file)
                self.stdout.write("Successfully imported offline data from %s\n" % data_file)

                # Doesn't hurt to keep data around.
                #if not settings.DEBUG:
                #    os.remove(data_file)
            except Exception as e:
                raise CommandError("Error importing offline data from %s: %s\n" % (data_file, str(e))) 

        confirm_or_generate_zone(invitation)

        initialize_facility(options["facility_name"])
Exemple #2
0
def get_hostname_and_description(hostname=None, description=None):
    default_hostname = get_host_name()
    while not hostname:
        prompt = "Please enter a name for this server%s: " % (
            "" if not default_hostname else
            (" (or, press Enter to use '%s')" % get_host_name()))
        hostname = raw_input(prompt) or default_hostname
        if not hostname:
            sys.stderr.write("\tError: hostname must not be empty.\n")
        else:
            break

    description = description or raw_input(
        "Please enter a one-line description for this server (or, press Enter to leave blank): "
    )

    return (hostname, description)
Exemple #3
0
def get_hostname_and_description(hostname=None, description=None):
    default_hostname = get_host_name()
    while not hostname:
        prompt = "Please enter a name for this server%s: " % ("" if not default_hostname else (" (or, press Enter to use '%s')" % get_host_name()))
        hostname = raw_input(prompt) or default_hostname
        if not hostname:
            sys.stderr.write("\tError: hostname must not be empty.\n")
        else:
            break

    description = description or raw_input("Please enter a one-line description for this server (or, press Enter to leave blank): ")

    return (hostname, description)
Exemple #4
0
    def handle(self, *args, **options):
        if DeviceMetadata.objects.filter(is_own_device=True).count() > 0:
            raise CommandError("Error: This device has already been initialized; aborting.\n")

        if len(args) >= 1 and args[0]:
            name = args[0]
        else:
            name = get_host_name()

        if len(args) >= 2 and args[1]:
            description = args[1]
        else:
            description = ""

        Device.initialize_own_device(name=name, description=description)
        self.stdout.write("Device '%s'%s has been successfully initialized.\n"
            % (name, description and (" ('%s')" % description) or ""))
Exemple #5
0
    def handle(self, *args, **options):
        if DeviceMetadata.objects.filter(is_own_device=True).count() > 0:
            raise CommandError(
                "Error: This device has already been initialized; aborting.\n")

        name = args[0] if (len(args) >= 1 and args[0]) else get_host_name()
        description = args[1] if (len(args) >= 2 and args[1]) else ""
        data_file = args[2] if (len(args) >= 3
                                and args[2]) else self.data_json_file

        own_device = Device.initialize_own_device(name=name,
                                                  description=description)
        self.stdout.write(
            "Device '%s'%s has been successfully initialized.\n" %
            (name, description and (" ('%s')" % description) or ""))

        # Nothing to do with a central server
        if settings.CENTRAL_SERVER:
            return
        elif True:  # for 0.10.3, short-cut to avoid invitation logic.
            return

        # Now we're definitely not central server, so ... go for it!
        # Import a zone (for machines sharing zones), and join if it works!
        invitation = None
        if not os.path.exists(data_file):
            sys.stderr.write(
                "Could not find resource file %s.  This may cause warnings to appear when updating your KA Lite version.\n"
                % data_file)
        else:
            try:
                invitation = load_data_for_offline_install(in_file=data_file)
                self.stdout.write(
                    "Successfully imported offline data from %s\n" % data_file)

                # Doesn't hurt to keep data around.
                #if not settings.DEBUG:
                #    os.remove(data_file)
            except Exception as e:
                raise CommandError(
                    "Error importing offline data from %s: %s\n" %
                    (data_file, e))

        confirm_or_generate_zone(invitation)

        initialize_facility(options["facility_name"])
Exemple #6
0
    def handle(self, *args, **options):
        if DeviceMetadata.objects.filter(is_own_device=True).count() > 0:
            raise CommandError(
                "Error: This device has already been initialized; aborting.\n")

        if len(args) >= 1 and args[0]:
            name = args[0]
        else:
            name = get_host_name()

        if len(args) >= 2 and args[1]:
            description = args[1]
        else:
            description = ""

        Device.initialize_own_device(name=name, description=description)
        self.stdout.write(
            "Device '%s'%s has been successfully initialized.\n" %
            (name, description and (" ('%s')" % description) or ""))
Exemple #7
0
    def initialize_own_device(cls, **kwargs):
        """
        Create a device object for the installed device.  Part of installation.
        """
        kwargs["version"] = kwargs.get("version", kalite.VERSION)
        kwargs["name"] = kwargs.get("name", get_host_name())
        own_device = cls(**kwargs)
        own_device.set_key(crypto.get_own_key())

        # imported=True is for when the local device should not sign the object,
        #   and when counters should not be incremented.  That's our situation here!
        own_device.sign(device=own_device)  # must sign, in order to use imported codepath
        super(Device, own_device).save(imported=True, increment_counters=False)

        metadata = own_device.get_metadata()
        metadata.is_own_device = True
        metadata.is_trusted = settings.CENTRAL_SERVER  # this is OK to set, as DeviceMetata is NEVER synced.
        metadata.save()

        return own_device
Exemple #8
0
    def initialize_own_device(cls, **kwargs):
        """
        Create a device object for the installed device.  Part of installation.
        """
        kwargs["version"] = kwargs.get("version", kalite.VERSION)
        kwargs["name"] = kwargs.get("name", get_host_name())
        own_device = cls(**kwargs)
        own_device.set_key(crypto.get_own_key())

        # imported=True is for when the local device should not sign the object,
        #   and when counters should not be incremented.  That's our situation here!
        own_device.sign(
            device=own_device)  # must sign, in order to use imported codepath
        super(Device, own_device).save(imported=True, increment_counters=False)

        metadata = own_device.get_metadata()
        metadata.is_own_device = True
        metadata.is_trusted = settings.CENTRAL_SERVER  # this is OK to set, as DeviceMetata is NEVER synced.
        metadata.save()

        return own_device
Exemple #9
0
    def handle(self, *args, **options):
        if not options["interactive"]:
            options["username"] = options["username"] or settings.INSTALL_ADMIN_USERNAME or getpass.getuser()
            options["hostname"] = options["hostname"] or get_host_name()

        sys.stdout.write("  _   __  ___    _     _ _        \n")
        sys.stdout.write(" | | / / / _ \  | |   (_) |       \n")
        sys.stdout.write(" | |/ / / /_\ \ | |    _| |_ ___  \n")
        sys.stdout.write(" |    \ |  _  | | |   | | __/ _ \ \n")
        sys.stdout.write(" | |\  \| | | | | |___| | ||  __/ \n")
        sys.stdout.write(" \_| \_/\_| |_/ \_____/_|\__\___| \n")
        sys.stdout.write("                                  \n")
        sys.stdout.write("http://kalite.learningequality.org\n")
        sys.stdout.write("                                  \n")
        sys.stdout.write("         version %s\n" % version.VERSION)
        sys.stdout.write("                                  \n")

        if sys.version_info >= (2,8) or sys.version_info < (2,6):
            raise CommandError("You must have Python version 2.6.x or 2.7.x installed. Your version is: %s\n" % sys.version_info)

        if options["interactive"]:
            sys.stdout.write("--------------------------------------------------------------------------------\n")
            sys.stdout.write("\n")
            sys.stdout.write("This script will configure the database and prepare it for use.\n")
            sys.stdout.write("\n")
            sys.stdout.write("--------------------------------------------------------------------------------\n")
            sys.stdout.write("\n")
            raw_input("Press [enter] to continue...")
            sys.stdout.write("\n")

        # Tried not to be os-specific, but ... hey. :-/
        if not is_windows() and hasattr(os, "getuid") and os.getuid() == 502:
            sys.stdout.write("-------------------------------------------------------------------\n")
            sys.stdout.write("WARNING: You are installing KA-Lite as root user!\n")
            sys.stdout.write("\tInstalling as root may cause some permission problems while running\n")
            sys.stdout.write("\tas a normal user in the future.\n")
            sys.stdout.write("-------------------------------------------------------------------\n")
            if options["interactive"]:
                if not raw_input_yn("Do you wish to continue and install it as root?"):
                    raise CommandError("Aborting script.\n")
                sys.stdout.write("\n")

        # Check to see if the current user is the owner of the install directory
        current_owner = find_owner(BASE_DIR)
        current_user = getpass.getuser()
        if current_owner != current_user:
            raise CommandError("""You are not the owner of this directory!
    Please copy all files to a directory that you own and then
    re-run this script.""")

        if not os.access(BASE_DIR, os.W_OK):
            raise CommandError("You do not have permission to write to this directory!")

        database_file = settings.DATABASES["default"]["NAME"]
        install_clean = True
        if os.path.exists(database_file):
            # We found an existing database file.  By default,
            #   we will upgrade it; users really need to work hard
            #   to delete the file (but it's possible, which is nice).
            sys.stdout.write("-------------------------------------------------------------------\n")
            sys.stdout.write("WARNING: Database file already exists! \n")
            sys.stdout.write("-------------------------------------------------------------------\n")
            if not options["interactive"] \
               or raw_input_yn("Keep database file and upgrade to KA Lite version %s? " % version.VERSION) \
               or not raw_input_yn("Remove database file '%s' now? " % database_file) \
               or not raw_input_yn("WARNING: all data will be lost!  Are you sure? "):
                install_clean = False
                sys.stdout.write("Upgrading database to KA Lite version %s\n" % version.VERSION)

            if install_clean:
                # After all, don't delete--just move.
                sys.stdout.write("OK.  We will run a clean install; \n")
                sys.stdout.write("the database file will be moved to a deletable location.\n")

        # Do all input at once, at the beginning
        if install_clean and options["interactive"]:
            if not options["username"] or not options["password"]:
                sys.stdout.write("\n")
                sys.stdout.write("Please choose a username and password for the admin account on this device.\n")
                sys.stdout.write("\tYou must remember this login information, as you will need\n")
                sys.stdout.write("\tto enter it to administer this installation of KA Lite.\n")
                sys.stdout.write("\n")
            (username, password) = get_username_password(options["username"], options["password"])
            (hostname, description) = get_hostname_and_description(options["hostname"], options["description"])
        else:
            username = options["username"] or settings.INSTALL_ADMIN_USERNAME
            password = options["password"] or settings.INSTALL_ADMIN_PASSWORD
            hostname = options["hostname"]
            description = options["description"]

        if username and not validate_username(username):
            raise CommandError("Username must contain only letters, digits, and underscores, and start with a letter.\n")


        ########################
        # Now do stuff
        ########################

        # Move database file (if exists)
        if install_clean and os.path.exists(database_file):
            # This is an overwrite install; destroy the old db
            dest_file = tempfile.mkstemp()[1]
            sys.stdout.write("(Re)moving database file to temp location, starting clean install.  Recovery location: %s\n" % dest_file)
            shutil.move(database_file, dest_file)

        # Got this far, it's OK to stop the server.
        import serverstop

        # Should clean_pyc for (clean) reinstall purposes
        call_command("clean_pyc", interactive=False, verbosity=options.get("verbosity"))

        # Migrate the database
        call_command("syncdb", interactive=False, verbosity=options.get("verbosity"))
        call_command("migrate", merge=True, verbosity=options.get("verbosity"))

        # Install data
        if install_clean:
            # Create device, load on any zone data
            call_command("generatekeys", verbosity=options.get("verbosity"))
            call_command("initdevice", hostname, description, verbosity=options.get("verbosity"))

        else:
            # Device exists; load data if required.
            #
            # Hackish, as this duplicates code from initdevice.
            #
            if os.path.exists(InitCommand.data_json_file):
                # This is a pathway to install zone-based data on a software upgrade.
                sys.stdout.write("Loading zone data from '%s'\n" % InitCommand.data_json_file)
                load_data_for_offline_install(in_file=InitCommand.data_json_file)

            confirm_or_generate_zone()
            initialize_facility()

        # Create the admin user
        if password:  # blank password (non-interactive) means don't create a superuser
            admin = get_object_or_None(User, username=username)
            if not admin:
                call_command("createsuperuser", username=username, email="*****@*****.**", interactive=False, verbosity=options.get("verbosity"))
                admin = User.objects.get(username=username)
            admin.set_password(password)
            admin.save()


        # Move scripts
        for script_name in ["start", "stop", "run_command"]:
            script_file = script_name + system_script_extension()
            dest_dir = os.path.join(settings.PROJECT_PATH, "..")
            src_dir = os.path.join(dest_dir, "scripts")
            shutil.copyfile(os.path.join(src_dir, script_file), os.path.join(dest_dir, script_file))
            shutil.copystat(os.path.join(src_dir, script_file), os.path.join(dest_dir, script_file))

        start_script_path = os.path.realpath(os.path.join(settings.PROJECT_PATH, "..", "start%s" % system_script_extension()))


        # Run videoscan, on the distributed server.
        if not settings.CENTRAL_SERVER:
            sys.stdout.write("Scanning for video files in the content directory (%s)\n" % settings.CONTENT_ROOT)
            call_command("videoscan")


        # done; notify the user.
        sys.stdout.write("\n")
        if install_clean:
            sys.stdout.write("CONGRATULATIONS! You've finished setting up the KA Lite server software.\n")
            sys.stdout.write("\tPlease run '%s' to start the server,\n" % start_script_path)
            sys.stdout.write("\tthen load 'http://127.0.0.1:%d/' in your browser to complete the device configuration.\n" % settings.user_facing_port())
        else:
            sys.stdout.write("CONGRATULATIONS! You've finished updating the KA Lite server software.\n")
            sys.stdout.write("\tPlease run '%s' to start the server.\n" % start_script_path)
        sys.stdout.write("\n")
Exemple #10
0
    def handle(self, *args, **options):
        if not options["interactive"]:
            options["username"] = options[
                "username"] or settings.INSTALL_ADMIN_USERNAME or getpass.getuser(
                )
            options["hostname"] = options["hostname"] or get_host_name()

        sys.stdout.write("  _   __  ___    _     _ _        \n")
        sys.stdout.write(" | | / / / _ \  | |   (_) |       \n")
        sys.stdout.write(" | |/ / / /_\ \ | |    _| |_ ___  \n")
        sys.stdout.write(" |    \ |  _  | | |   | | __/ _ \ \n")
        sys.stdout.write(" | |\  \| | | | | |___| | ||  __/ \n")
        sys.stdout.write(" \_| \_/\_| |_/ \_____/_|\__\___| \n")
        sys.stdout.write("                                  \n")
        sys.stdout.write("http://kalite.learningequality.org\n")
        sys.stdout.write("                                  \n")
        sys.stdout.write("         version %s\n" % version.VERSION)
        sys.stdout.write("                                  \n")

        if sys.version_info >= (2, 8) or sys.version_info < (2, 6):
            raise CommandError(
                "You must have Python version 2.6.x or 2.7.x installed. Your version is: %s\n"
                % sys.version_info)

        if options["interactive"]:
            sys.stdout.write(
                "--------------------------------------------------------------------------------\n"
            )
            sys.stdout.write("\n")
            sys.stdout.write(
                "This script will configure the database and prepare it for use.\n"
            )
            sys.stdout.write("\n")
            sys.stdout.write(
                "--------------------------------------------------------------------------------\n"
            )
            sys.stdout.write("\n")
            raw_input("Press [enter] to continue...")
            sys.stdout.write("\n")

        # Tried not to be os-specific, but ... hey. :-/
        if not is_windows() and hasattr(os, "getuid") and os.getuid() == 502:
            sys.stdout.write(
                "-------------------------------------------------------------------\n"
            )
            sys.stdout.write(
                "WARNING: You are installing KA-Lite as root user!\n")
            sys.stdout.write(
                "\tInstalling as root may cause some permission problems while running\n"
            )
            sys.stdout.write("\tas a normal user in the future.\n")
            sys.stdout.write(
                "-------------------------------------------------------------------\n"
            )
            if options["interactive"]:
                if not raw_input_yn(
                        "Do you wish to continue and install it as root?"):
                    raise CommandError("Aborting script.\n")
                sys.stdout.write("\n")

        # Check to see if the current user is the owner of the install directory
        current_owner = find_owner(BASE_DIR)
        current_user = getpass.getuser()
        if current_owner != current_user:
            raise CommandError("""You are not the owner of this directory!
    Please copy all files to a directory that you own and then
    re-run this script.""")

        if not os.access(BASE_DIR, os.W_OK):
            raise CommandError(
                "You do not have permission to write to this directory!")

        database_file = settings.DATABASES["default"]["NAME"]
        install_clean = True
        if os.path.exists(database_file):
            # We found an existing database file.  By default,
            #   we will upgrade it; users really need to work hard
            #   to delete the file (but it's possible, which is nice).
            sys.stdout.write(
                "-------------------------------------------------------------------\n"
            )
            sys.stdout.write("WARNING: Database file already exists! \n")
            sys.stdout.write(
                "-------------------------------------------------------------------\n"
            )
            if not options["interactive"] \
               or raw_input_yn("Keep database file and upgrade to KA Lite version %s? " % version.VERSION) \
               or not raw_input_yn("Remove database file '%s' now? " % database_file) \
               or not raw_input_yn("WARNING: all data will be lost!  Are you sure? "):
                install_clean = False
                sys.stdout.write("Upgrading database to KA Lite version %s\n" %
                                 version.VERSION)

            if install_clean:
                # After all, don't delete--just move.
                sys.stdout.write("OK.  We will run a clean install; \n")
                sys.stdout.write(
                    "the database file will be moved to a deletable location.\n"
                )

        # Do all input at once, at the beginning
        if install_clean and options["interactive"]:
            if not options["username"] or not options["password"]:
                sys.stdout.write("\n")
                sys.stdout.write(
                    "Please choose a username and password for the admin account on this device.\n"
                )
                sys.stdout.write(
                    "\tYou must remember this login information, as you will need\n"
                )
                sys.stdout.write(
                    "\tto enter it to administer this installation of KA Lite.\n"
                )
                sys.stdout.write("\n")
            (username,
             password) = get_username_password(options["username"],
                                               options["password"])
            (hostname, description) = get_hostname_and_description(
                options["hostname"], options["description"])
        else:
            username = options["username"] or settings.INSTALL_ADMIN_USERNAME
            password = options["password"] or settings.INSTALL_ADMIN_PASSWORD
            hostname = options["hostname"]
            description = options["description"]

        if username and not validate_username(username):
            raise CommandError(
                "Username must contain only letters, digits, and underscores, and start with a letter.\n"
            )

        ########################
        # Now do stuff
        ########################

        # Move database file (if exists)
        if install_clean and os.path.exists(database_file):
            # This is an overwrite install; destroy the old db
            dest_file = tempfile.mkstemp()[1]
            sys.stdout.write(
                "(Re)moving database file to temp location, starting clean install.  Recovery location: %s\n"
                % dest_file)
            shutil.move(database_file, dest_file)

        # Got this far, it's OK to stop the server.
        import serverstop

        # Should clean_pyc for (clean) reinstall purposes
        call_command("clean_pyc",
                     interactive=False,
                     verbosity=options.get("verbosity"))

        # Migrate the database
        call_command("syncdb",
                     interactive=False,
                     verbosity=options.get("verbosity"))
        call_command("migrate", merge=True, verbosity=options.get("verbosity"))

        # Install data
        if install_clean:
            # Create device, load on any zone data
            call_command("generatekeys", verbosity=options.get("verbosity"))
            call_command("initdevice",
                         hostname,
                         description,
                         verbosity=options.get("verbosity"))

        else:
            # Device exists; load data if required.
            #
            # Hackish, as this duplicates code from initdevice.
            #
            if os.path.exists(InitCommand.data_json_file):
                # This is a pathway to install zone-based data on a software upgrade.
                sys.stdout.write("Loading zone data from '%s'\n" %
                                 InitCommand.data_json_file)
                load_data_for_offline_install(
                    in_file=InitCommand.data_json_file)

            confirm_or_generate_zone()
            initialize_facility()

        # Create the admin user
        if password:  # blank password (non-interactive) means don't create a superuser
            admin = get_object_or_None(User, username=username)
            if not admin:
                call_command("createsuperuser",
                             username=username,
                             email="*****@*****.**",
                             interactive=False,
                             verbosity=options.get("verbosity"))
                admin = User.objects.get(username=username)
            admin.set_password(password)
            admin.save()

        # Move scripts
        for script_name in ["start", "stop", "run_command"]:
            script_file = script_name + system_script_extension()
            dest_dir = os.path.join(settings.PROJECT_PATH, "..")
            src_dir = os.path.join(dest_dir, "scripts")
            shutil.copyfile(os.path.join(src_dir, script_file),
                            os.path.join(dest_dir, script_file))
            shutil.copystat(os.path.join(src_dir, script_file),
                            os.path.join(dest_dir, script_file))

        start_script_path = os.path.realpath(
            os.path.join(settings.PROJECT_PATH, "..",
                         "start%s" % system_script_extension()))

        # Run videoscan, on the distributed server.
        if not settings.CENTRAL_SERVER:
            sys.stdout.write(
                "Scanning for video files in the content directory (%s)\n" %
                settings.CONTENT_ROOT)
            call_command("videoscan")

        # done; notify the user.
        sys.stdout.write("\n")
        if install_clean:
            sys.stdout.write(
                "CONGRATULATIONS! You've finished setting up the KA Lite server software.\n"
            )
            sys.stdout.write("\tPlease run '%s' to start the server,\n" %
                             start_script_path)
            sys.stdout.write(
                "\tthen load 'http://127.0.0.1:%d/' in your browser to complete the device configuration.\n"
                % settings.user_facing_port())
        else:
            sys.stdout.write(
                "CONGRATULATIONS! You've finished updating the KA Lite server software.\n"
            )
            sys.stdout.write("\tPlease run '%s' to start the server.\n" %
                             start_script_path)
        sys.stdout.write("\n")