def _wsgi_app(environ, start_response):
    """WSGI application to process the incoming Git client request.

    This is nearly equivalent to p4gf_auth_server.main() with the exception of
    input validation and error handling.
    """
    p4gf_version_3.log_version_extended()
    p4gf_util.log_environ(LOG, environ, "WSGI")
    p4gf_version_3.version_check()
    LOG.info("Processing LFS/HTTP request, pid=%s", os.getpid())
    result = p4gf_http_common.check_file_encoding(start_response)
    if result:
        return result
    _response = functools.partial(p4gf_http_common.send_error_response,
                                  start_response)
    try:
        input_file = p4gf_http_common.read_request_data(environ)
        server = LargeFileHttpServer(environ, start_response, input_file)
        try:
            server.process()
        except p4gf_server_common.BadRequestException as e:
            return _response(http.client.BAD_REQUEST, e)
        except p4gf_server_common.PerforceConnectionFailed:
            return _response(http.client.INTERNAL_SERVER_ERROR,
                             _("Perforce connection failed\n"))
        except p4gf_server_common.CommandError as ce:
            return _response(http.client.FORBIDDEN, ce)
        except p4gf_server_common.ReadOnlyInstanceException as roie:
            return _response(http.client.FORBIDDEN, roie)
        except RuntimeError as rerr:
            return _response(http.client.INTERNAL_SERVER_ERROR, rerr)
    finally:
        p4gf_http_common.rm_file_quietly(input_file)

    return []
示例#2
0
def main():
    """Create Perforce user and client for Git Fusion."""
    p4gf_version_3.log_version_extended(include_checksum=True)
    try:
        log_l10n()
        p4gf_version_3.version_check()
    except Exception as e:  # pylint: disable=broad-except
        sys.stderr.write(e.args[0] + '\n')
        sys.exit(1)

    # To fetch the object client below we need to ensure there is a server
    # ID available on this system, and since we require that anyway, may as
    # well check it now, when we need it.
    p4gf_util.has_server_id_or_exit()
    with p4gf_create_p4.Closer():
        p4 = p4gf_create_p4.create_p4_temp_client()
        if not p4:
            return 2

        Verbosity.report(Verbosity.INFO, "P4PORT : {}".format(p4.port))
        Verbosity.report(Verbosity.INFO, "P4USER : {}".format(p4.user))

        p4gf_util.reset_git_enviro()
        p4gf_proc.init()

        try:
            init(p4)
            remove_old_temp_and_repo_clients(p4)
        except PermissionError:
            LOG.exception("unable to initialize Git Fusion")
            sys.stderr.write(_("File permissions error, please check ownership"
                               " and mode of ~/.git-fusion directory.\n"))
            sys.exit(os.EX_NOPERM)

    return 0
示例#3
0
def run_main():
    """Some initial logging, then run main()."""
    # Ensure any errors occurring in the setup are sent to stderr, while the
    # code below directs them to stderr once rather than twice.
    try:
        with p4gf_log.ExceptionLogger(squelch=False, write_to_stderr_=True):
            p4gf_version_3.log_version_extended()
            log_l10n()
            p4gf_version_3.version_check()
    except:  # pylint: disable=bare-except
        # Cannot continue if above code failed.
        sys.exit(1)
    # main() already writes errors to stderr, so don't let logger do it again
    p4gf_log.run_with_exception_logger(main_ignores, write_to_stderr=False)
def main():
    """Set up repo for a view."""
    p4gf_util.has_server_id_or_exit()
    args = _parse_argv()
    p4gf_version_3.log_version_extended(include_checksum=True)
    log_l10n()
    if args.enablemismatchedrhs:
        # Git Fusion should never modify the customer's config file, and
        # use of this option resulted in the config file losing all of the
        # comments and formatting the customer had put in place.
        sys.stderr.write(
            _('The --enablemismatchedrhs option is deprecated,'
              ' please use enable-mismatched-rhs config file'
              ' option instead.\n'))
        sys.exit(1)
    repo_name_p4client = None
    if args.p4client:
        repo_name_p4client = p4gf_util.argv_to_repo_name(args.p4client)
    repo_name = _argv_to_repo_name(args.repo_name)
    p4gf_util.reset_git_enviro()

    p4 = p4gf_create_p4.create_p4_temp_client()
    if not p4:
        raise RuntimeError(_('error connecting to Perforce'))

    LOG.debug("connected to P4 at %s", p4.port)
    p4gf_proc.init()

    try:
        with ExitStack() as stack:
            stack.enter_context(p4gf_create_p4.Closer())
            p4gf_version_3.version_check()
            p4gf_branch.init_case_handling(p4)
            repo_lock = p4gf_lock.RepoLock(p4, repo_name)
            stack.enter_context(repo_lock)
            ctx = p4gf_context.create_context(repo_name)
            ctx.p4gf = p4
            ctx.repo_lock = repo_lock
            initer = InitRepo(p4, repo_lock).set_repo_name(repo_name)
            initer.context = ctx
            initer.set_config_file_path(args.config)
            initer.set_charset(args.charset)
            initer.set_noclone(args.noclone)
            initer.set_start(args.start)
            stack.enter_context(ctx)
            initer.full_init(repo_name_p4client)
    except P4.P4Exception as e:
        _print_stderr(_('Error occurred: {exception}').format(exception=e))
        sys.exit(1)
示例#5
0
def main():
    """Do the thing."""
    # pylint: disable=too-many-statements, too-many-branches
    try:
        log_l10n()
        parse_argv()
        global P4PORT, P4USER, P4CLIENT
        needs_exit = False
        if not P4PORT and "P4PORT" not in os.environ:
            Verbosity.report(
                Verbosity.INFO,
                _('P4PORT is neither set in the environment nor passed as an option.'))
            needs_exit = True
        if not P4USER and "P4USER" not in os.environ:
            Verbosity.report(
                Verbosity.INFO,
                _('P4USER is neither set in the environment nor passed as an option.'))
            needs_exit = True
        # Check that a pre-existing P4GF_ENV config file P4PORT conflicts with the --port option
        if p4gf_const.P4GF_ENV and not Create_P4GF_CONFIG and P4PORT:
            if P4PORT != os.environ['P4PORT']:
                Verbosity.report(
                    Verbosity.INFO,
                    _("conflicting P4PORT in args: {p4port} and "
                      "P4GF_ENV {env} : P4PORT = {env_p4port}. Stopping.")
                    .format(p4port=P4PORT,
                            env=p4gf_const.P4GF_ENV,
                            env_p4port=os.environ['P4PORT']))
                needs_exit = True
            else:
                Verbosity.report(
                    Verbosity.INFO,
                    _("P4PORT argument is identically configured in {0}. Proceeding.")
                    .format(p4gf_const.P4GF_ENV))
        if needs_exit:
            sys.exit(1)

        p4gf_version_3.version_check()
        # Connect.
        global p4
        if not P4USER:
            P4USER = os.environ['P4USER']
        # if needed, set a bogus client name so that the default to hostname will not be used.
        if "P4CLIENT" not in os.environ:
            P4CLIENT = 'GF-' + str(uuid.uuid4().hex).lower()[-10:]
            os.environ['P4CLIENT'] = P4CLIENT
        else:
            P4CLIENT = os.environ['P4CLIENT']
        p4 = p4gf_create_p4.create_p4(port=P4PORT, user=P4USER, client=P4CLIENT)
        if not p4:
            raise RuntimeError(_("Failed to connect to P4."))
        P4PORT = p4.port
        P4USER = p4.user
        check_and_create_default_p4gf_env_config()
        if SHOW_IDS:
            show_all_server_ids()
            sys.exit(0)
        Verbosity.report(Verbosity.INFO, "P4PORT : {}".format(p4.port))
        Verbosity.report(Verbosity.INFO, "P4USER : {}".format(p4.user))

        # Require that we have super permission.
        # Might as well keep the result in case we need to write a new protect
        # table later. Saves a 'p4 protect -o' trip to the server
        protect_lines = fetch_protect()

        if P4_PASSWD and p4_security_level() > 0 and not strong_passwd(P4_PASSWD):
            Verbosity.report(
                Verbosity.ERROR,
                _("This Perforce server requires a strong password: >= 8 characters and"))
            Verbosity.report(
                Verbosity.ERROR,
                _("with mixed case or contain non alphabetic characters."))
            sys.exit(1)

        ensure_server_id()
        ensure_group()
        ensure_users()
        ensure_depot()
        ensure_protect(protect_lines)
        ensure_protects_configurable()
        set_proxy_protects_key()
        check_triggers()
        initialize_all_gf_reviews()

    except Exception as e:  # pylint: disable=broad-except
        sys.stderr.write(str(e) + '\n')
        p4gf_create_p4.close_all()
        sys.exit(1)
示例#6
0
def _wsgi_app(environ, start_response):
    """WSGI application to process the incoming Git client request.

    This is nearly equivalent to p4gf_auth_server.main() with the exception of
    input validation and error handling.
    """
    # pylint: disable=too-many-branches
    p4gf_version_3.log_version_extended()
    p4gf_util.log_environ(LOG, environ, "WSGI")
    p4gf_version_3.version_check()
    LOG.info("Processing HTTP request, pid=%s", os.getpid())
    result = p4gf_http_common.check_file_encoding(start_response)
    if result:
        return result
    try:
        input_file = p4gf_http_common.read_request_data(environ)

        with OutputSink() as sink:
            _response = functools.partial(send_error_response, sink,
                                          start_response)
            # pylint 1.2.0 complains about http.server due to assignment in GitFusionRequestHandler
            # pylint 1.3.0 handles this fine with just the disable in GitFusionRequestHandler
            # pylint:disable=attribute-defined-outside-init
            server = GitHttpServer(environ, input_file)
            try:
                server.process()
            except p4gf_http_common.HttpException as e:
                return _response(e.code, e.msg)
            except p4gf_server_common.BadRequestException as e:
                return _response(http.client.BAD_REQUEST, e)
            except p4gf_server_common.PerforceConnectionFailed:
                return _response(http.client.INTERNAL_SERVER_ERROR,
                                 _("Perforce connection failed\n"))
            except p4gf_server_common.SpecialCommandException:
                user_agent = environ.get('HTTP_USER_AGENT')
                if user_agent and not user_agent.startswith('git'):
                    return _response(http.client.OK, sink.readall())
                else:
                    return _response(http.client.NOT_FOUND, sink.readall())
            except p4gf_server_common.CommandError as ce:
                return _response(http.client.FORBIDDEN, ce)
            except p4gf_server_common.RepoNotFoundException as e:
                return _response(http.client.NOT_FOUND, e)
            except p4gf_server_common.RepoInitFailedException:
                return _response(http.client.INTERNAL_SERVER_ERROR,
                                 _("Repository initialization failed\n"))
            except p4gf_server_common.MissingSubmoduleImportUrlException:
                msg = _(
                    'Stream imports require a valid http-url be configured.'
                    ' Contact your administrator.')
                return _response(http.client.INTERNAL_SERVER_ERROR, msg)
            except p4gf_atomic_lock.LockConflict as lc:
                return _response(http.client.INTERNAL_SERVER_ERROR, lc)
            except p4gf_server_common.ReadOnlyInstanceException as roie:
                return _response(http.client.FORBIDDEN, roie)
            except Exception as e:  # pylint: disable=broad-except
                return _response(http.client.INTERNAL_SERVER_ERROR, e)

            return []
    finally:
        p4gf_http_common.rm_file_quietly(input_file)