示例#1
0
 def execute(self):
     """
     Given the command-line arguments, this figures out which subcommand is
     being run, creates a parser appropriate to that command, and runs it.
     """
     parser = LaxOptionParser(usage="%prog subcommand [options] [args]",
         version=pinax.get_version(),
         option_list=BaseCommand.option_list)
     try:
         options, args = parser.parse_args(self.argv)
         handle_default_options(options)
     except:
         pass
     
     try:
         subcommand = self.argv[1]
     except IndexError:
         sys.stderr.write("Type '%s --help' for usage.\n" % self.prog_name)
         sys.exit(1)
     
     if self.argv[1:] == ['--version']:
         pass
     elif self.argv[1:] == ['--help']:
         parser.print_lax_help()
         sys.stderr.write(self.main_help_text() + '\n')
     else:
         self.fetch_command(subcommand).run_from_argv(self.argv)
示例#2
0
def entry():
  _deprecation_check(sys.argv[0])

  from django.core.exceptions import ImproperlyConfigured
  from django.core.management import execute_from_command_line, find_commands, find_management_module
  from django.core.management import LaxOptionParser
  from django.core.management.base import BaseCommand

  os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'desktop.settings')

  # What's the subcommand being run?
  # This code uses the same logic from django.core.management to handle command args
  argv = sys.argv[:]
  parser = LaxOptionParser(option_list=BaseCommand.option_list)
  parser.parse_args(argv)
  if len(argv) > 1:
    prof_id = subcommand = argv[1]
  else:
    prof_id = str(os.getpid())

  try:
    # Let django handle the normal execution
    if os.getenv("DESKTOP_PROFILE"):
      _profile(prof_id, lambda: execute_from_command_line(sys.argv))
    else:
      execute_from_command_line(sys.argv)
  except ImproperlyConfigured, e:
    if len(sys.argv) > 1 and sys.argv[1] == 'is_db_alive' and 'oracle' in str(e).lower():
      sys.exit(10)
    else:
      raise e
示例#3
0
def entry():
    _deprecation_check(sys.argv[0])

    from django.core.exceptions import ImproperlyConfigured
    from django.core.management import execute_from_command_line, find_commands, find_management_module
    from django.core.management import LaxOptionParser
    from django.core.management.base import BaseCommand

    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'desktop.settings')

    # What's the subcommand being run?
    # This code uses the same logic from django.core.management to handle command args
    argv = sys.argv[:]
    parser = LaxOptionParser(option_list=BaseCommand.option_list)
    parser.parse_args(argv)
    if len(argv) > 1:
        prof_id = subcommand = argv[1]
    else:
        prof_id = str(os.getpid())

    try:
        # Let django handle the normal execution
        if os.getenv("DESKTOP_PROFILE"):
            _profile(prof_id, lambda: execute_from_command_line(sys.argv))
        else:
            execute_from_command_line(sys.argv)
    except ImproperlyConfigured, e:
        if len(sys.argv) > 1 and sys.argv[
                1] == 'is_db_alive' and 'oracle' in str(e).lower():
            sys.exit(10)
        else:
            raise e
示例#4
0
    def check_options(self):
        # django switched to argparse in version 1.8
        if DJANGO_VERSION >= (1, 8):
            parser = base.CommandParser(None,
                                        usage="%(prog)s subcommand [options] [args]",
                                        add_help=False)
            parser.add_argument('--settings')
            parser.add_argument('--pythonpath')
            parser.add_argument(CONFIGURATION_ARGUMENT,
                                help=CONFIGURATION_ARGUMENT_HELP)

            parser.add_argument('args', nargs='*')  # catch-all
            try:
                options, args = parser.parse_known_args(self.argv[2:])
                if options.configuration:
                    os.environ[self.namevar] = options.configuration
                base.handle_default_options(options)
            except base.CommandError:
                pass  # Ignore any option errors at this point.
        # django < 1.7 did use optparse
        else:
            from django.core.management import LaxOptionParser
            parser = LaxOptionParser(option_list=configuration_options,
                                     add_help_option=False)
            try:
                options, args = parser.parse_args(self.argv)
                if options.configuration:
                    os.environ[self.namevar] = options.configuration
            except:
                pass  # Ignore any option errors at this point.
    def check_options(self):
        # django switched to argparse in version 1.8
        if DJANGO_VERSION >= (1, 8):
            parser = base.CommandParser(None,
                                        usage="%(prog)s subcommand [options] [args]",
                                        add_help=False)
            parser.add_argument('--settings')
            parser.add_argument('--pythonpath')
            parser.add_argument(CONFIGURATION_ARGUMENT,
                                help=CONFIGURATION_ARGUMENT_HELP)

            parser.add_argument('args', nargs='*')  # catch-all
            try:
                options, args = parser.parse_known_args(self.argv[2:])
                if options.configuration:
                    os.environ[self.namevar] = options.configuration
                base.handle_default_options(options)
            except base.CommandError:
                pass  # Ignore any option errors at this point.
        # django < 1.7 did use optparse
        else:
            from django.core.management import LaxOptionParser
            parser = LaxOptionParser(option_list=configuration_options,
                                     add_help_option=False)
            try:
                options, args = parser.parse_args(self.argv)
                if options.configuration:
                    os.environ[self.namevar] = options.configuration
            except:
                pass  # Ignore any option errors at this point.
 def check_options(self):
     parser = LaxOptionParser(option_list=configuration_options,
                              add_help_option=False)
     try:
         options, args = parser.parse_args(self.argv)
         if options.configuration:
             os.environ[self.namevar] = options.configuration
     except:
         pass  # Ignore any option errors at this point.
def has_settings_option():
    parser = LaxOptionParser(usage="%prog subcommand [options] [args]",
                             version=get_version(),
                             option_list=BaseCommand.option_list)
    try:
        options = parser.parse_args(sys.argv[:])[0]
    except:
        return False # Ignore any option errors at this point.
    return bool(options.settings)
示例#8
0
def has_settings_option():
    parser = LaxOptionParser(usage="%prog subcommand [options] [args]",
                             version=get_version(),
                             option_list=BaseCommand.option_list)
    try:
        options = parser.parse_args(sys.argv[:])[0]
    except:
        return False  # Ignore any option errors at this point.
    return bool(options.settings)
示例#9
0
def has_settings_option():
    parser = LaxOptionParser(usage="%prog subcommand [options] [args]",
                             version=get_version(),
                             option_list=BaseCommand.option_list)
    try:
        options = parser.parse_args(sys.argv[:])[0]
        if options.settings:
            print "=" * 20
            print "%s has_settings_option '%s%s%s'%s" % (BYELLOW,BRED,options.settings,BYELLOW,NORMAL)
            print "=" * 20
    except:
        return False # Ignore any option errors at this point.
    return bool(options.settings)
示例#10
0
    def execute(self, argv=None, stdout=None, stderr=None):

        if argv is None:
            argv = sys.argv

        parser = LaxOptionParser(usage="%prog subcommand [options] [args]",
            version=wirecloud.platform.__version__,
            option_list=())

        if stdout is None:
            stdout = sys.stdout

        if stderr is None:
            stderr = sys.stderr

        try:
            options, args = parser.parse_args(argv)
        except:
            pass  # Ignore any option errors at this point.

        try:
            subcommand = argv[1]
        except IndexError:
            subcommand = 'help'  # Display help if no arguments were given.

        if subcommand == 'help':
            if len(args) <= 2:
                parser.print_lax_help()
                stdout.write(self.main_help_text() + '\n')
            elif args[2] == '--commands':
                stdout.write(self.main_help_text(commands_only=True) + '\n')
            else:
                command = self.fetch_command(args[2])
                if command is not None:
                    command.print_help(self.prog_name, args[2], file=stdout)
                else:
                    stdout.write(self.unknown_command_text(args[2]) + '\n')

        elif subcommand == 'version':
            stdout.write(parser.get_version() + '\n')
        elif '--version' in argv[1:]:
            # LaxOptionParser already takes care of printing the version.
            pass
        elif '--help' in argv[1:] or '-h' in argv[1:]:
            if len(args) <= 2:
                parser.print_lax_help()
                stdout.write(self.main_help_text() + '\n')
            else:
                command = self.fetch_command(args[1])
                if command is not None:
                    command.print_help(self.prog_name, args[1], file=stdout)
                else:
                    stdout.write(self.unknown_command_text(args[1]) + '\n')

        else:
            command = self.fetch_command(subcommand)
            if command is not None:
                command.run_from_argv(argv, stdout=stdout, stderr=stderr)
            else:
                stdout.write(self.unknown_command_text(subcommand) + '\n')
示例#11
0
    def execute(self):
        """
        Given the command-line arguments, this figures out which subcommand is
        being run, creates a parser appropriate to that command, and runs it.
        """
        parser = LaxOptionParser(usage="%prog subcommand [options] [args]",
                                 version=pinax.get_version(),
                                 option_list=BaseCommand.option_list)
        try:
            options, args = parser.parse_args(self.argv)
            handle_default_options(options)
        except:
            pass

        try:
            subcommand = self.argv[1]
        except IndexError:
            sys.stderr.write("Type '%s help' for usage.\n" % self.prog_name)
            sys.exit(1)

        if subcommand == 'help':
            if len(args) > 2:
                self.fetch_command(args[2]).print_help(self.prog_name, args[2])
            else:
                parser.print_lax_help()
                sys.stderr.write(self.main_help_text() + '\n')
                sys.exit(1)
        elif self.argv[1:] == ['--version']:
            pass
        elif self.argv[1:] in [['--help'], ['-h']]:
            parser.print_lax_help()
            sys.stderr.write(self.main_help_text() + '\n')
        else:
            self.fetch_command(subcommand).run_from_argv(self.argv)
    def execute(self, argv=None, stdout=None, stderr=None):

        if argv is None:
            argv = sys.argv

        parser = LaxOptionParser(usage="%prog subcommand [options] [args]",
            version=wirecloud.platform.__version__,
            option_list=())

        if stdout is None:
            stdout = sys.stdout

        if stderr is None:
            stderr = sys.stderr

        try:
            options, args = parser.parse_args(argv)
        except:
            pass  # Ignore any option errors at this point.

        try:
            subcommand = argv[1]
        except IndexError:
            subcommand = 'help'  # Display help if no arguments were given.

        if subcommand == 'help':
            if len(args) <= 2:
                parser.print_lax_help()
                stdout.write(self.main_help_text() + '\n')
            elif args[2] == '--commands':
                stdout.write(self.main_help_text(commands_only=True) + '\n')
            else:
                command = self.fetch_command(args[2])
                if command is not None:
                    command.print_help(self.prog_name, args[2], file=stdout)
                else:
                    stdout.write(self.unknown_command_text(args[2]) + '\n')

        elif subcommand == 'version':
            stdout.write(parser.get_version() + '\n')
        elif '--version' in argv[1:]:
            # LaxOptionParser already takes care of printing the version.
            pass
        elif '--help' in argv[1:] or '-h' in argv[1:]:
            if len(args) <= 2:
                parser.print_lax_help()
                stdout.write(self.main_help_text() + '\n')
            else:
                command = self.fetch_command(args[1])
                if command is not None:
                    command.print_help(self.prog_name, args[1], file=stdout)
                else:
                    stdout.write(self.unknown_command_text(args[1]) + '\n')

        else:
            command = self.fetch_command(subcommand)
            if command is not None:
                command.run_from_argv(argv, stdout=stdout, stderr=stderr)
            else:
                stdout.write(self.unknown_command_text(subcommand) + '\n')
示例#13
0
 def create_parser(self, prog_name, subcommand):
     # Overwrite parser creation with a LaxOptionParser that will
     # ignore arguments it doesn't know, allowing us to pass those
     # along to the webassets command.
     # Hooking into run_from_argv() would be another thing to try
     # if this turns out to be problematic.
     return LaxOptionParser(prog=prog_name,
         usage=self.usage(subcommand),
         version=self.get_version(),
         option_list=self.option_list)
示例#14
0
def execute_manager(settings_mod, argv=None):
    """
    Like execute_from_command_line(), but for use by manage.py, a
    project-specific django-admin.py utility.
    """
    setup_environ(settings_mod)
    # Set up Green Plum Database Features
    execfile(os.path.abspath(os.path.join(os.path.dirname(__file__), 'greenplum_monkey_patch.py')))
    if os.getpid() - os.getppid() == 1:  # Let Run-Server print the notifications once on the console
        sys.stdout.write("Applying Green plum Monkey Patch...Success\n")
        sys.stdout.flush()
    # END Set up Green Plum Database Features
    utility = ManagementUtility(argv)
    if 'syncdb' in sys.argv:
        from django import get_version
        from django.core.management import LaxOptionParser
        from django.core.management.commands import syncdb
        parser = LaxOptionParser(usage="%prog subcommand [options] [args]",
                                 version=get_version(),
                                 option_list=syncdb.Command.option_list)
        options = parser.parse_args(sys.argv)[0]
        create_schema_before_syncdb(**options.__dict__)
        # create_views_on_piggy_back_keys()
    utility.execute()
示例#15
0
    def execute(self):
        """
        Given the command-line arguments, this figures out which subcommand is
        being run, creates a parser appropriate to that command, and runs it.
        """
        # Preprocess options to extract --settings and --pythonpath.
        # These options could affect the commands that are available, so they
        # must be processed early.
        parser = LaxOptionParser(usage="%prog subcommand [options] [args]",
                                 version=django.get_version(),
                                 option_list=BaseCommand.option_list)
        try:
            options, args = parser.parse_args(self.argv)
            handle_default_options(options)
        except:
            pass  # Ignore any option errors at this point.

        try:
            subcommand = self.argv[1]
        except IndexError:
            sys.stderr.write("Type '%s help' for usage.\n" % self.prog_name)
            sys.exit(1)

        if subcommand == 'help':
            if len(args) > 2:
                self.fetch_command(args[2]).print_help(self.prog_name, args[2])
            else:
                parser.print_lax_help()
                sys.stderr.write(self.main_help_text() + '\n')
                sys.exit(1)
        # Special-cases: We want 'manage.py --version' and
        # 'manage.py --help' to work, for backwards compatibility.
        elif self.argv[1:] == ['--version']:
            # LaxOptionParser already takes care of printing the version.
            pass
        elif self.argv[1:] == ['--help']:
            parser.print_lax_help()
            sys.stderr.write(self.main_help_text() + '\n')
        else:
            mysql_workaround = subcommand == "syncdb" and settings.DATABASE_ENGINE == "mysql"
            if mysql_workaround:
                from django.db import connection
                cursor = connection.cursor()
                cursor.execute("SET FOREIGN_KEY_CHECKS = 0")

            self.fetch_command(subcommand).run_from_argv(self.argv)

            if mysql_workaround:
                cursor = connection.cursor()
                cursor.execute("SET FOREIGN_KEY_CHECKS = 1")
示例#16
0
    def execute(self):
        """
        Given the command-line arguments, this figures out which subcommand is
        being run, creates a parser appropriate to that command, and runs it.
        """
        # Preprocess options to extract --settings and --pythonpath.
        # These options could affect the commands that are available, so they
        # must be processed early.
        parser = LaxOptionParser(usage="%prog subcommand [options] [args]",
                                 version=django.get_version(),
                                 option_list=BaseCommand.option_list)
        try:
            options, args = parser.parse_args(self.argv)
            handle_default_options(options)
        except:
            pass  # Ignore any option errors at this point.

        try:
            subcommand = self.argv[1]
        except IndexError:
            sys.stderr.write("Type '%s help' for usage.\n" % self.prog_name)
            sys.exit(1)

        if subcommand == 'help':
            if len(args) > 2:
                self.fetch_command(args[2]).print_help(self.prog_name, args[2])
            else:
                parser.print_lax_help()
                sys.stderr.write(self.main_help_text() + '\n')
                sys.exit(1)
        # Special-cases: We want 'manage.py --version' and
        # 'manage.py --help' to work, for backwards compatibility.
        elif self.argv[1:] == ['--version']:
            # LaxOptionParser already takes care of printing the version.
            pass
        elif self.argv[1:] == ['--help']:
            parser.print_lax_help()
            sys.stderr.write(self.main_help_text() + '\n')
        else:
            from django.db import connections, DEFAULT_DB_ALIAS
            db = options.__dict__.get('database', DEFAULT_DB_ALIAS)
            mysql_workaround = subcommand == "syncdb" and settings.DATABASES[db]['ENGINE'] == "mysql"
            if mysql_workaround:
                connection = connections[db]
                cursor = connection.cursor()
                cursor.execute("SET FOREIGN_KEY_CHECKS = 0")

            self.fetch_command(subcommand).run_from_argv(self.argv)

            if mysql_workaround:
                cursor = connection.cursor()
                cursor.execute("SET FOREIGN_KEY_CHECKS = 1")
示例#17
0
def entry():
    _deprecation_check(sys.argv[0])

    from django.core.exceptions import ImproperlyConfigured
    from django.core.management import execute_from_command_line, find_commands, find_management_module
    from django.core.management import LaxOptionParser
    from django.core.management.base import BaseCommand

    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'desktop.settings')

    # What's the subcommand being run?
    # This code uses the same logic from django.core.management to handle command args
    argv = sys.argv[:]
    parser = LaxOptionParser(option_list=BaseCommand.option_list)
    parser.parse_args(argv)

    if len(argv) > 1:
        prof_id = subcommand = argv[1]
        commands_req_db = [
            "changepassword", "createsuperuser", "clean_history_docs",
            "convert_documents", "sync_documents", "dbshell", "dumpdata",
            "loaddata", "shell", "migrate", "syncdb", "import_ldap_group",
            "import_ldap_user", "sync_ldap_users_and_groups",
            "useradmin_sync_with_unix"
        ]
        if subcommand in commands_req_db:
            #Check if this is a CM managed cluster
            cm_config_file = '/etc/cloudera-scm-agent/config.ini'
            if os.path.isfile(
                    cm_config_file) and "--cm-managed" not in sys.argv:
                if not "HUE_CONF_DIR" in os.environ:
                    print "ALERT: This appears to be a CM Managed environment"
                    print "ALERT: HUE_CONF_DIR must be set when running hue commands in CM Managed environment"
                    print "ALERT: Please run 'hue <command> --cm-managed'"
    else:
        prof_id = str(os.getpid())

    # Check if --cm-managed flag is set and strip it out
    # to prevent from sending to subcommands
    if "--cm-managed" in sys.argv:
        sys.argv.remove("--cm-managed")
        import ConfigParser
        from ConfigParser import NoOptionError
        config = ConfigParser.RawConfigParser()
        config.read(cm_config_file)
        try:
            cm_supervisor_dir = config.get(
                'General', 'agent_wide_credential_cache_location')
        except NoOptionError:
            cm_supervisor_dir = '/var/run/cloudera-scm-agent'
            pass

        #Parse CM supervisor include file for Hue and set env vars
        cm_supervisor_dir = cm_supervisor_dir + '/supervisor/include'
        hue_env_conf = None
        envline = None
        cm_hue_string = "HUE_SERVER"

        for file in os.listdir(cm_supervisor_dir):
            if cm_hue_string in file:
                hue_env_conf = file

        if not hue_env_conf == None:
            if os.path.isfile(cm_supervisor_dir + "/" + hue_env_conf):
                hue_env_conf_file = open(
                    cm_supervisor_dir + "/" + hue_env_conf, "r")
                for line in hue_env_conf_file:
                    if "environment" in line:
                        envline = line
                    if "directory" in line:
                        empty, hue_conf_dir = line.split("directory=")
                        os.environ["HUE_CONF_DIR"] = hue_conf_dir.rstrip()
        else:
            print "This appears to be a CM managed cluster the"
            print "supervisor/include file for Hue could not be found"
            print "in order to successfully run commands that access"
            print "the database you need to set the following env vars:"
            print ""
            print "  export JAVA_HOME=<java_home>"
            print "  export HUE_CONF_DIR=\"/var/run/cloudera-scm-agent/process/\`ls -1 /var/run/cloudera-scm-agent/process | grep HUE_SERVER | sort -n | tail -1 \`\""
            print "  export HUE_IGNORE_PASSWORD_SCRIPT_ERRORS=1"
            print "  export HUE_DATABASE_PASSWORD=<hueDBpassword>"

        if not envline == None:
            empty, environment = envline.split("environment=")
            for envvar in environment.split(","):
                if "HADOOP_C" in envvar or "PARCEL" in envvar:
                    envkey, envval = envvar.split("=")
                    envval = envval.replace("'", "").rstrip()
                    os.environ[envkey] = envval

        #Set JAVA_HOME:
        if "JAVA_HOME" not in os.environ.keys():
            parcel_dir = os.environ["PARCELS_ROOT"] + '/' + os.environ[
                "PARCEL_DIRNAMES"]
            bigtop_javahome = parcel_dir + '/lib/bigtop-utils/bigtop-detect-javahome'
            if os.path.isfile(bigtop_javahome):
                command = "/bin/bash -c \"source " + bigtop_javahome + " && env\""
                proc = subprocess.Popen(command,
                                        stdout=subprocess.PIPE,
                                        shell=True)
                for procline in proc.stdout:
                    (key, _, value) = procline.partition("=")
                    if key == "JAVA_HOME":
                        os.environ[key] = value.rstrip()

        if "JAVA_HOME" not in os.environ.keys():
            print "Not able to set JAVA_HOME.  Please set manually:"
            print "  export JAVA_HOME=<java_home>"

    try:
        # Let django handle the normal execution
        if os.getenv("DESKTOP_PROFILE"):
            _profile(prof_id, lambda: execute_from_command_line(sys.argv))
        else:
            execute_from_command_line(sys.argv)
    except ImproperlyConfigured, e:
        if len(sys.argv) > 1 and sys.argv[
                1] == 'is_db_alive' and 'oracle' in str(e).lower():
            print >> sys.stderr, e  # Oracle connector is improperly configured
            sys.exit(10)
        else:
            raise e
示例#18
0
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see 
# http://www.gnu.org/licenses/agpl-3.0.html.

import os
import sys

import startup

if __name__ == "__main__":
    # handle the --settings and --python-path options so that django.conf is
    # setup before we import localeurl.
    from django.core.management.base import (handle_default_options,
                                             BaseCommand)
    from django.core.management import LaxOptionParser, get_version
    parser = LaxOptionParser(usage="%prog subcommand [options] [args]",
                             version=get_version(),
                             option_list=BaseCommand.option_list)
    options, args = parser.parse_args(sys.argv)
    handle_default_options(options)

    startup.startup()

    # start the management command
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
    from django.core.management import execute_from_command_line
    execute_from_command_line(sys.argv)
示例#19
0
 def create_parser(self, prog_name, subcommand):
     return LaxOptionParser(prog=prog_name,
                            usage=self.usage(subcommand),
                            version=self.get_version(),
                            option_list=self.option_list)
示例#20
0
    def execute(self):
        """
        Given the command-line arguments, this figures out which subcommand is
        being run, creates a parser appropriate to that command, and runs it.
        """
        # Preprocess options to extract --settings and --pythonpath.
        # These options could affect the commands that are available, so they
        # must be processed early.
        parser = LaxOptionParser(usage="%prog subcommand [options] [args]",
                                 version=get_version(),
                                 option_list=ServerCommand.option_list)
        try:
            options, args = parser.parse_args(self.argv)
            handle_default_options(options)
        except:  # Needed because parser.parse_args can raise SystemExit
            pass  # Ignore any option errors at this point.

        try:
            subcommand = self.argv[1]
        except IndexError:
            subcommand = 'help'  # Display help if no arguments were given.

        no_settings_commands = [
            'help',
            'version',
            '--help',
            '--version',
            '-h',
            'compilemessages',
            'makemessages',
            'startapp',
            'startproject',
        ]

        try:
            settings.INSTALLED_APPS
        except ImproperlyConfigured as exc:
            self.settings_exception = exc
            # A handful of built-in management commands work without settings.
            # Load the default settings -- where INSTALLED_APPS is empty.
            if subcommand in no_settings_commands:
                settings.configure()

        if settings.configured:
            django.setup()

        self.autocomplete()

        if subcommand == 'help':
            if len(args) <= 2:
                parser.print_lax_help()
                sys.stdout.write(self.main_help_text() + '\n')
            elif args[2] == '--commands':
                sys.stdout.write(
                    self.main_help_text(commands_only=True) + '\n')
            else:
                self.fetch_command(args[2]).print_help(self.prog_name, args[2])
        elif subcommand == 'version':
            sys.stdout.write(parser.get_version() + '\n')
        # Special-cases: We want 'django-admin.py --version' and
        # 'django-admin.py --help' to work, for backwards compatibility.
        elif self.argv[1:] == ['--version']:
            # LaxOptionParser already takes care of printing the version.
            pass
        elif self.argv[1:] in (['--help'], ['-h']):
            parser.print_lax_help()
            sys.stdout.write(self.main_help_text() + '\n')
        else:
            self.start_server()
示例#21
0
def entry():
    _deprecation_check(sys.argv[0])

    from django.core.management import execute_manager, find_commands, find_management_module
    from django.core.management import LaxOptionParser
    from django.core.management.base import BaseCommand
    try:
        from desktop import settings, appmanager
    except ImportError, ie:
        traceback.print_exc()
        sys.exit(1)

    # What's the subcommand being run?
    # This code uses the same logic from django.core.management to handle command args
    argv = sys.argv[:]
    parser = LaxOptionParser(option_list=BaseCommand.option_list)
    parser.parse_args(argv)
    if len(argv) > 1:
        prof_id = subcommand = argv[1]
    else:
        prof_id = str(os.getpid())

    # Let django handle the normal execution
    if os.getenv("DESKTOP_PROFILE"):
        _profile(prof_id, lambda: execute_manager(settings))
    else:
        execute_manager(settings)


def _profile(prof_id, func):
    """
示例#22
0
    def execute(self):
        """
        Given the command-line arguments, this figures out which subcommand is
        being run, creates a parser appropriate to that command, and runs it.
        """

        # --settings-dir option
        # will remove it later to avoid django commands from raising errors
        option_list = BaseCommand.option_list + (
            make_option('--settings-dir',
                action='store',
                dest='settings_dir',
                default=None,
                help='Load *.conf files from directory as settings'),)

        # Preprocess options to extract --settings and --pythonpath.
        # These options could affect the commands that are available, so they
        # must be processed early.
        parser = LaxOptionParser(usage="%prog subcommand [options] [args]",
                                 version=get_component_version('webproject'),
                                 option_list=option_list)
        self.autocomplete()
        try:
            options, args = parser.parse_args(self.argv)
            handle_default_options(options)
        except:
            pass  # Ignore any option errors at this point.

        # user provides custom settings dir
        # set it as environmental variable and remove it from self.argv
        if options.settings_dir:
            os.environ['SYNNEFO_SETTINGS_DIR'] = options.settings_dir
            for arg in self.argv:
                if arg.startswith('--settings-dir'):
                    self.argv.remove(arg)

        try:
            subcommand = self.argv[1]
        except IndexError:
            subcommand = 'help'  # Display help if no arguments were given.

        # Encode stdout. This check is required because of the way python
        # checks if something is tty:
        # https://bugzilla.redhat.com/show_bug.cgi?id=841152
        if not subcommand in ['test'] and not 'shell' in subcommand:
            sys.stdout = EncodedStdOut(sys.stdout)

        if subcommand == 'help':
            if len(args) > 2:
                self.fetch_command(args[2]).print_help(self.prog_name, args[2])
            else:
                parser.print_lax_help()
                sys.stdout.write(self.main_help_text() + '\n')
                sys.exit(1)
        # Special-cases: We want 'django-admin.py --version' and
        # 'django-admin.py --help' to work, for backwards compatibility.
        elif self.argv[1:] == ['--version']:
            # LaxOptionParser already takes care of printing the version.
            pass
        elif self.argv[1:] in (['--help'], ['-h']):
            parser.print_lax_help()
            sys.stdout.write(self.main_help_text() + '\n')
        else:
            self.fetch_command(subcommand).run_from_argv(self.argv)
示例#23
0
    def execute(self):
        """
        Given the command-line arguments, this figures out which subcommand is
        being run, creates a parser appropriate to that command, and runs it.
        """

        # --settings-dir option
        # will remove it later to avoid django commands from raising errors
        option_list = BaseCommand.option_list + (
            make_option(
                '--settings-dir',
                action='store',
                dest='settings_dir',
                default=None,
                help='Load *.conf files from directory as settings'),)

        # Preprocess options to extract --settings and --pythonpath.
        # These options could affect the commands that are available, so they
        # must be processed early.
        parser = LaxOptionParser(usage="%prog subcommand [options] [args]",
                                 version=get_component_version('webproject'),
                                 option_list=option_list)
        self.autocomplete()
        try:
            options, args = parser.parse_args(self.argv)
            handle_default_options(options)
        except:
            pass  # Ignore any option errors at this point.

        # user provides custom settings dir
        # set it as environmental variable and remove it from self.argv
        if options.settings_dir:
            os.environ['SYNNEFO_SETTINGS_DIR'] = options.settings_dir
            for arg in self.argv:
                if arg.startswith('--settings-dir'):
                    self.argv.remove(arg)

        try:
            subcommand = self.argv[1]
        except IndexError:
            subcommand = 'help'  # Display help if no arguments were given.

        # Encode stdout. This check is required because of the way python
        # checks if something is tty:
        # https://bugzilla.redhat.com/show_bug.cgi?id=841152
        if subcommand not in ['test'] and 'shell' not in subcommand:
            sys.stdout = EncodedStream(sys.stdout)
            sys.stderr = EncodedStream(sys.stderr)

        if subcommand == 'help':
            if len(args) > 2:
                self.fetch_command(args[2]).print_help(self.prog_name, args[2])
            else:
                parser.print_lax_help()
                sys.stdout.write(self.main_help_text() + '\n')
                sys.exit(1)
        # Special-cases: We want 'django-admin.py --version' and
        # 'django-admin.py --help' to work, for backwards compatibility.
        elif self.argv[1:] == ['--version']:
            # LaxOptionParser already takes care of printing the version.
            pass
        elif self.argv[1:] in (['--help'], ['-h']):
            parser.print_lax_help()
            sys.stdout.write(self.main_help_text() + '\n')
        else:
            sub_command = self.fetch_command(subcommand)
            # NOTE: This is an ugly workaround to bypass the problem with
            # the required permissions for the named pipes that Pithos backend
            # is creating in order to communicate with XSEG.
            if subcommand == 'test' or\
               subcommand.startswith('image-') or\
               subcommand.startswith('snapshot-') or\
               subcommand.startswith('file-'):
                # Set common umask for known commands
                os.umask(0o007)
            # Allow command to define a custom umask
            cmd_umask = getattr(sub_command, 'umask', None)
            if cmd_umask is not None:
                os.umask(cmd_umask)
            sub_command.run_from_argv(self.argv)
示例#24
0
文件: manage.py 项目: Hutspace/odekro
                       'conf',
                       'general.yml')) as f:
    config = yaml.load(f)

country = config.get('COUNTRY_APP', 'no_country')

# However, it's nice if "./manage.py test" works out-of-the-box, so
# work out if "test" is the subcommand and the user hasn't specified a
# settings module with --settings.  If so, use the settings module for
# non-country-specific tests that we know has the right INSTALLED_APPS
# and tests are expected to pass with. This won't help confusion if
# someone uses "django-admin.py test" instead, but it's some help...
# (Note that if someone's set the DJANGO_SETTINGS_MODULE environment
# variable, this default won't be used either.)

parser = LaxOptionParser(option_list=BaseCommand.option_list)
try:
    options, args = parser.parse_args(sys.argv)
except:
    # Ignore any errors at this point; the arguments will be parsed
    # again shortly anyway.
    args = None

run_default_tests = (len(args) >= 2 and args[1] == 'test' and not options.settings)

if __name__ == "__main__":

    if run_default_tests:
        settings_module = 'pombola.settings.tests'
        print "Warning: we recommend running tests with ./run-tests instead"
    else:
    def django_init(self):
        """ Checks for the required data and initializes the application. """

        # manage.py
        os.environ.setdefault("DJANGO_SETTINGS_MODULE", SETTINGS)

        # django.core.management.execute_from_command_line(argv=ARGS)
        """
        A simple method that runs a ManagementUtility.
        """
        from django.core.management import ManagementUtility
        utility = ManagementUtility(ARGS)

        # utility.execute()
        """
        Given the command-line arguments, this figures out which subcommand is
        being run, creates a parser appropriate to that command, and runs it.
        """
        from django.core.management import LaxOptionParser
        # For backwards compatibility: get_version() used to be in this module.
        from django import get_version
        from django.core.management.base import BaseCommand, handle_default_options
        # Preprocess options to extract --settings and --pythonpath.
        # These options could affect the commands that are available, so they
        # must be processed early.
        parser = LaxOptionParser(usage="%prog subcommand [options] [args]",
                                 version=get_version(),
                                 option_list=BaseCommand.option_list)
        utility.autocomplete()
        try:
            options, args = parser.parse_args(utility.argv)
            handle_default_options(options)
        except:
            pass # Ignore any option errors at this point.
        subcommand = utility.argv[1]
        klass = utility.fetch_command(subcommand)
        
        # klass.run_from_argv(utility.argv)        
        """
        Set up any environment changes requested (e.g., Python path
        and Django settings), then run this command. If the
        command raises a ``CommandError``, intercept it and print it sensibly
        to stderr. If the ``--traceback`` option is present or the raised
        ``Exception`` is not ``CommandError``, raise it.
        """
        from django.core.management.base import CommandError
        parser = klass.create_parser(utility.argv[0], utility.argv[1])
        options, args = parser.parse_args(utility.argv[2:])
        handle_default_options(options)

        options = options.__dict__
        # klass.execute(*args, **options.__dict__)
        """
        Try to execute this command, performing model validation if
        needed (as controlled by the attribute
        ``klass.requires_model_validation``, except if force-skipped).
        """
        from django.core.management.base import OutputWrapper
        klass.stdout = OutputWrapper(options.get('stdout', sys.stdout))
        klass.stderr = OutputWrapper(options.get('stderr', sys.stderr), klass.style.ERROR)

        #klass.can_import_settings = True
        from django.conf import settings

        saved_locale = None
        #klass.leave_locale_alone = False
        # Only mess with locales if we can assume we have a working
        # settings file, because django.utils.translation requires settings
        # (The final saying about whether the i18n machinery is active will be
        # found in the value of the USE_I18N setting)

        #klass.can_import_settings = True

        # Switch to US English, because django-admin.py creates database
        # content like permissions, and those shouldn't contain any
        # translations.
        from django.utils import translation
        saved_locale = translation.get_language()
        translation.activate('en-us')

        try:
            # Validation is called explicitly each time the server is reloaded.
            #klass.requires_model_validation = False

            addrport = args[0]
            print 'addrport %s' % addrport
            args = args[1:]
            # klass.handle(addrport='', *args, **options)
            import re
            from django.core.management.commands.runserver import naiveip_re, DEFAULT_PORT
            from django.conf import settings

            if not settings.DEBUG and not settings.ALLOWED_HOSTS:
                raise CommandError('You must set settings.ALLOWED_HOSTS if DEBUG is False.')

            klass.use_ipv6 = options.get('use_ipv6')
            if klass.use_ipv6 and not socket.has_ipv6:
                raise CommandError('Your Python does not support IPv6.')
            if args:
                raise CommandError('Usage is runserver %s' % klass.args)
            klass._raw_ipv6 = False
            if not addrport:
                klass.addr = ''
                klass.port = DEFAULT_PORT
            else:
                m = re.match(naiveip_re, addrport)
                if m is None:
                    raise CommandError('"%s" is not a valid port number '
                                       'or address:port pair.' % addrport)
                klass.addr, _ipv4, _ipv6, _fqdn, klass.port = m.groups()
                if not klass.port.isdigit():
                    raise CommandError("%r is not a valid port number." % klass.port)
                if klass.addr:
                    if _ipv6:
                        klass.addr = klass.addr[1:-1]
                        klass.use_ipv6 = True
                        klass._raw_ipv6 = True
                    elif klass.use_ipv6 and not _fqdn:
                        raise CommandError('"%s" is not a valid IPv6 address.' % klass.addr)
            if not klass.addr:
                klass.addr = '::1' if klass.use_ipv6 else '127.0.0.1'
                klass._raw_ipv6 = bool(klass.use_ipv6)

            # klass.run(*args, **options)
            """
            Runs the server, using the autoreloader if needed
            """
            #from django.utils import autoreload
            use_reloader = options.get('use_reloader')
            if use_reloader:
                # use queue and threading to start httpd
                # skip for now
                print 'reloader bypassed for Windows service'
                pass

            # klass.inner_run(*args, **options)
            import errno
            import socket
            from django.utils import six
            from django.utils.six.moves import socketserver
            from django.core.servers.basehttp import WSGIServer, WSGIRequestHandler
            from datetime import datetime
            from django.conf import settings
            from django.utils import translation
            
            threading = options.get('use_threading')
            shutdown_message = options.get('shutdown_message', '')
            quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C'

            klass.stdout.write("Validating models...\n\n")
            klass.validate(display_num_errors=True)
            klass.stdout.write((
                "%(started_at)s\n"
                "Django version %(version)s, using settings %(settings)r\n"
                "Starting development server at http://%(addr)s:%(port)s/\n"
                "Quit the server with %(quit_command)s.\n"
            ) % {
                "started_at": datetime.now().strftime('%B %d, %Y - %X'),
                "version": klass.get_version(),
                "settings": settings.SETTINGS_MODULE,
                "addr": '[%s]' % klass.addr if klass._raw_ipv6 else klass.addr,
                "port": klass.port,
                "quit_command": quit_command,
            })
            # django.core.management.base forces the locale to en-us. We should
            # set it up correctly for the first request (particularly important
            # in the "--noreload" case).
            translation.activate(settings.LANGUAGE_CODE)

            try:
                handler = klass.get_handler(*args, **options)
                # run(addr=klass.addr, port=int(klass.port), wsgi_handler=handler,
                #     ipv6=klass.use_ipv6, threading=threading)
                server_address = (klass.addr, int(klass.port))
                if threading:
                    httpd_cls = type(str('WSGIServer'), (socketserver.ThreadingMixIn, WSGIServer), {})
                else:
                    httpd_cls = WSGIServer
                httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=klass.use_ipv6)
                httpd.set_app(handler)
                
            except socket.error as e:
                # Use helpful error messages instead of ugly tracebacks.
                ERRORS = {
                    errno.EACCES: "You don't have permission to access that port.",
                    errno.EADDRINUSE: "That port is already in use.",
                    errno.EADDRNOTAVAIL: "That IP address can't be assigned-to.",
                }
                try:
                    error_text = ERRORS[e.errno]
                except KeyError:
                    error_text = str(e)
                klass.stderr.write("Error: %s" % error_text)
                # Need to use an OS exit because sys.exit doesn't work in a thread
                os._exit(1)

        finally:
            if saved_locale is not None:
                translation.activate(saved_locale)
        return httpd
示例#26
0
with open(os.path.join(os.path.dirname(__file__), 'conf', 'general.yml')) as f:
    config = yaml.load(f)

country = config.get('COUNTRY_APP', 'no_country')

# However, it's nice if "./manage.py test" works out-of-the-box, so
# work out if "test" is the subcommand and the user hasn't specified a
# settings module with --settings.  If so, use the settings module for
# non-country-specific tests that we know has the right INSTALLED_APPS
# and tests are expected to pass with. This won't help confusion if
# someone uses "django-admin.py test" instead, but it's some help...
# (Note that if someone's set the DJANGO_SETTINGS_MODULE environment
# variable, this default won't be used either.)

parser = LaxOptionParser(option_list=BaseCommand.option_list)
try:
    options, args = parser.parse_args(sys.argv)
except:
    # Ignore any errors at this point; the arguments will be parsed
    # again shortly anyway.
    args = None

run_default_tests = (len(args) >= 2 and args[1] == 'test'
                     and not options.settings)

if __name__ == "__main__":

    if run_default_tests:
        settings_module = 'pombola.settings.tests'
        print "Warning: we recommend running tests with ./run-tests instead"
示例#27
0
def entry():
  _deprecation_check(sys.argv[0])

  from django.core.management import execute_manager, find_commands, find_management_module
  from django.core.management import LaxOptionParser
  from django.core.management.base import BaseCommand
  try:
    from desktop import settings, appmanager
  except ImportError, ie:
    traceback.print_exc()
    sys.exit(1)

  # What's the subcommand being run?
  # This code uses the same logic from django.core.management to handle command args
  argv = sys.argv[:]
  parser = LaxOptionParser(option_list=BaseCommand.option_list)
  parser.parse_args(argv)
  if len(argv) > 1:
    prof_id = subcommand = argv[1]

    # See if this command belongs to a disabled app
    commands = { }
    skipped_apps = sum([ app.django_apps for app in appmanager.SKIPPED_APPS ], [])
    for app_name in skipped_apps:
      try:
        path = find_management_module(app_name)
        if subcommand in find_commands(path):
          LOG.info("NOT starting the command '%s' from the disabled application '%s'. Exit." %
                   (subcommand, app_name))
          sys.exit(0)
      except ImportError:
示例#28
0
    def execute(self):
        """
        Given the command-line arguments, this figures out which subcommand is
        being run, creates a parser appropriate to that command, and runs it.
        """
        # Preprocess options to extract --settings and --pythonpath.
        # These options could affect the commands that are available, so they
        # must be processed early.
        parser = LaxOptionParser(usage="%prog subcommand [options] [args]",
                                 version=get_version(),
                                 option_list=ServerCommand.option_list)
        try:
            options, args = parser.parse_args(self.argv)
            handle_default_options(options)
        except:  # Needed because parser.parse_args can raise SystemExit
            pass  # Ignore any option errors at this point.

        try:
            subcommand = self.argv[1]
        except IndexError:
            subcommand = 'help'  # Display help if no arguments were given.

        no_settings_commands = [
            'help', 'version', '--help', '--version', '-h',
            'compilemessages', 'makemessages',
            'startapp', 'startproject',
        ]

        try:
            settings.INSTALLED_APPS
        except ImproperlyConfigured as exc:
            self.settings_exception = exc
            # A handful of built-in management commands work without settings.
            # Load the default settings -- where INSTALLED_APPS is empty.
            if subcommand in no_settings_commands:
                settings.configure()

        if settings.configured:
            django.setup()

        self.autocomplete()

        if subcommand == 'help':
            if len(args) <= 2:
                parser.print_lax_help()
                sys.stdout.write(self.main_help_text() + '\n')
            elif args[2] == '--commands':
                sys.stdout.write(self.main_help_text(commands_only=True) + '\n')
            else:
                self.fetch_command(args[2]).print_help(self.prog_name, args[2])
        elif subcommand == 'version':
            sys.stdout.write(parser.get_version() + '\n')
        # Special-cases: We want 'django-admin.py --version' and
        # 'django-admin.py --help' to work, for backwards compatibility.
        elif self.argv[1:] == ['--version']:
            # LaxOptionParser already takes care of printing the version.
            pass
        elif self.argv[1:] in (['--help'], ['-h']):
            parser.print_lax_help()
            sys.stdout.write(self.main_help_text() + '\n')
        else:
            self.start_server()