Changeset - 5a47ce11427c
[Not reviewed]
Merge default
0 3 0
Mads Kiilerich - 10 years ago 2016-04-04 23:34:30
madski@unity3d.com
Merge stable
3 files changed with 43 insertions and 16 deletions:
0 comments (0 inline, 0 general)
docs/installation_iis.rst
Show inline comments
 
.. _installation_iis:
 

	
 
=====================================================================
 
Installing Kallithea on Microsoft Internet Information Services (IIS)
 
=====================================================================
 

	
 
The following is documented using IIS 7/8 terminology. There should be nothing
 
preventing you from applying this on IIS 6 well.
 

	
 
.. note::
 

	
 
    Installing Kallithea under IIS can enable Single Sign-On to the Kallithea
 
    web interface from web browsers that can authenticate to the web server.
 
    (As an alternative to IIS, SSO is also possible with for example Apache and
 
    mod_sspi.)
 

	
 
    Mercurial and Git do however by default not support SSO on the client side
 
    and will still require some other kind of authentication.
 
    (An extension like hgssoauthentication_ might solve that.)
 

	
 
.. note::
 

	
 
    For the best security, it is strongly recommended to only host the site over
 
    a secure connection, e.g. using TLS.
 

	
 

	
 
Prerequisites
 
-------------
 

	
 
Apart from the normal requirements for Kallithea, it is also necessary to get an
 
ISAPI-WSGI bridge module, e.g. isapi-wsgi.
 

	
 

	
 
Installation
 
------------
 

	
 
The following assumes that your Kallithea is at ``c:\inetpub\kallithea``, and
 
will be served from the root of its own website. The changes to serve it in its
 
own virtual folder will be noted where appropriate.
 

	
 
Application pool
 
^^^^^^^^^^^^^^^^
 

	
 
Make sure that there is a unique application pool for the Kallithea application
 
with an identity that has read access to the Kallithea distribution.
 

	
 
The application pool does not need to be able to run any managed code. If you
 
are using a 32-bit Python installation, then you must enable 32-bit program in
 
the advanced settings for the application pool; otherwise Python will not be able
 
to run on the website and neither will Kallithea.
 

	
 
.. note::
 

	
 
    The application pool can be the same as an existing application pool,
 
    as long as the Kallithea requirements are met by the existing pool.
 

	
 
ISAPI handler
 
^^^^^^^^^^^^^
 

	
 
The ISAPI handler can be generated using::
 

	
 
    paster install-iis my.ini --root=/
 
    paster install-iis my.ini --virtualdir=/
 

	
 
This will generate a ``dispatch.py`` file in the current directory that contains
 
the necessary components to finalize an installation into IIS. Once this file
 
has been generated, it is necessary to run the following command due to the way
 
that ISAPI-WSGI is made::
 

	
 
    python2 dispatch.py install
 

	
 
This accomplishes two things: generating an ISAPI compliant DLL file,
 
``_dispatch.dll``, and installing a script map handler into IIS for the
 
``--root`` specified above pointing to ``_dispatch.dll``.
 
``--virtualdir`` specified above pointing to ``_dispatch.dll``.
 

	
 
The ISAPI handler is registered to all file extensions, so it will automatically
 
be the one handling all requests to the specified root. When the website starts
 
be the one handling all requests to the specified virtual directory. When the website starts
 
the ISAPI handler, it will start a thread pool managed wrapper around the paster
 
middleware WSGI handler that Kallithea runs within and each HTTP request to the
 
site will be processed through this logic henceforth.
 

	
 
Authentication with Kallithea using IIS authentication modules
 
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 

	
 
The recommended way to handle authentication with Kallithea using IIS is to let
 
IIS handle all the authentication and just pass it to Kallithea.
 

	
 
.. note::
 

	
 
    As an alternative without SSO, you can also use LDAP authentication with
 
    Active Directory, see :ref:`ldap-setup`.
 

	
 
To move responsibility into IIS from Kallithea, we need to configure Kallithea
 
to let external systems handle authentication and then let Kallithea create the
 
user automatically. To do this, access the administration's authentication page
 
and enable the ``kallithea.lib.auth_modules.auth_container`` plugin. Once it is
 
added, enable it with the ``REMOTE_USER`` header and check *Clean username*.
 
Finally, save the changes on this page.
 

	
 
Switch to the administration's permissions page and disable anonymous access,
 
otherwise Kallithea will not attempt to use the authenticated user name. By
 
default, Kallithea will populate the list of users lazily as they log in. Either
 
disable external auth account activation and ensure that you pre-populate the
 
user database with an external tool, or set it to *Automatic activation of
 
external account*. Finally, save the changes.
 

	
 
The last necessary step is to enable the relevant authentication in IIS, e.g.
 
Windows authentication.
 

	
 

	
 
Troubleshooting
 
---------------
 

	
 
Typically, any issues in this setup will either be entirely in IIS or entirely
 
in Kallithea (or Kallithea's WSGI/paster middleware). Consequently, two
 
different options for finding issues exist: IIS' failed request tracking which
 
is great at finding issues until they exist inside Kallithea, at which point the
 
ISAPI-WSGI wrapper above uses ``win32traceutil``, which is part of ``pywin32``.
 

	
 
In order to dump output from WSGI using ``win32traceutil`` it is sufficient to
 
type the following in a console window::
 

	
 
    python2 -m win32traceutil
 

	
 
and any exceptions occurring in the WSGI layer and below (i.e. in the Kallithea
 
application itself) that are uncaught, will be printed here complete with stack
 
traces, making it a lot easier to identify issues.
 

	
 

	
 
.. _hgssoauthenticatio: https://bitbucket.org/domruf/hgssoauthentication
docs/setup.rst
Show inline comments
 
@@ -116,48 +116,49 @@ For an incremental index build, run::
 
For a full index rebuild, run::
 

	
 
    paster make-index my.ini -f
 

	
 
The ``--repo-location`` option allows the location of the repositories to be overriden;
 
usually, the location is retrieved from the Kallithea database.
 

	
 
The ``--index-only`` option can be used to limit the indexed repositories to a comma-separated list::
 

	
 
    paster make-index my.ini --index-only=vcs,kallithea
 

	
 
To keep your index up-to-date it is necessary to do periodic index builds;
 
for this, it is recommended to use a crontab entry. Example::
 

	
 
    0  3  *  *  *  /path/to/virtualenv/bin/paster make-index /path/to/kallithea/my.ini
 

	
 
When using incremental mode (the default), Whoosh will check the last
 
modification date of each file and add it to be reindexed if a newer file is
 
available. The indexing daemon checks for any removed files and removes them
 
from index.
 

	
 
If you want to rebuild the index from scratch, you can use the ``-f`` flag as above,
 
or in the admin panel you can check the "build from scratch" checkbox.
 

	
 
.. _ldap-setup:
 

	
 
Setting up LDAP support
 
-----------------------
 

	
 
Kallithea supports LDAP authentication. In order
 
to use LDAP, you have to install the python-ldap_ package. This package is
 
available via PyPI, so you can install it by running::
 

	
 
    pip install python-ldap
 

	
 
.. note:: ``python-ldap`` requires some libraries to be installed on
 
          your system, so before installing it check that you have at
 
          least the ``openldap`` and ``sasl`` libraries.
 

	
 
Choose *Admin > Authentication*, click the ``kallithea.lib.auth_modules.auth_ldap`` button
 
and then *Save*, to enable the LDAP plugin and configure its settings.
 

	
 
Here's a typical LDAP setup::
 

	
 
 Connection settings
 
 Enable LDAP          = checked
 
 Host                 = host.example.com
 
 Port                 = 389
 
 Account              = <account>
 
@@ -746,96 +747,105 @@ into ``[app:main]`` section of your .ini
 
Add the following at the end of the .ini file::
 

	
 
    [filter:proxy-prefix]
 
    use = egg:PasteDeploy#prefix
 
    prefix = /<someprefix>
 

	
 
then change ``<someprefix>`` into your chosen prefix
 

	
 

	
 
Apache with mod_wsgi
 
--------------------
 

	
 
Alternatively, Kallithea can be set up with Apache under mod_wsgi. For
 
that, you'll need to:
 

	
 
- Install mod_wsgi. If using a Debian-based distro, you can install
 
  the package libapache2-mod-wsgi::
 

	
 
    aptitude install libapache2-mod-wsgi
 

	
 
- Enable mod_wsgi::
 

	
 
    a2enmod wsgi
 

	
 
- Add global Apache configuration to tell mod_wsgi that Python only will be
 
  used in the WSGI processes and shouldn't be initialized in the Apache
 
  processes::
 

	
 
    WSGIRestrictEmbedded On
 

	
 
- Create a wsgi dispatch script, like the one below. Make sure you
 
  check that the paths correctly point to where you installed Kallithea
 
  and its Python Virtual Environment.
 
- Enable the ``WSGIScriptAlias`` directive for the WSGI dispatch script,
 
  as in the following example. Once again, check the paths are
 
  correctly specified.
 

	
 
Here is a sample excerpt from an Apache Virtual Host configuration file:
 

	
 
.. code-block:: apache
 

	
 
    WSGIDaemonProcess kallithea \
 
        processes=1 threads=4 \
 
        python-path=/srv/kallithea/venv/lib/python2.7/site-packages
 
        threads=4 \
 
        python-home=/srv/kallithea/venv
 
    WSGIProcessGroup kallithea
 
    WSGIScriptAlias / /srv/kallithea/dispatch.wsgi
 
    WSGIPassAuthorization On
 

	
 
Or if using a dispatcher WSGI script with proper virtualenv activation:
 

	
 
.. code-block:: apache
 

	
 
    WSGIDaemonProcess kallithea processes=1 threads=4
 
    WSGIDaemonProcess kallithea threads=4
 
    WSGIProcessGroup kallithea
 
    WSGIScriptAlias / /srv/kallithea/dispatch.wsgi
 
    WSGIPassAuthorization On
 

	
 
.. note::
 
   When running apache as root, please make sure it doesn't run Kallithea as
 
   root, for examply by adding: ``user=www-data group=www-data`` to the configuration.
 
Apache will by default run as a special Apache user, on Linux systems
 
usually ``www-data`` or ``apache``. If you need to have the repositories
 
directory owned by a different user, use the user and group options to
 
WSGIDaemonProcess to set the name of the user and group.
 

	
 
Example WSGI dispatch script:
 

	
 
.. code-block:: python
 

	
 
    import os
 
    os.environ["HGENCODING"] = "UTF-8"
 
    os.environ['PYTHON_EGG_CACHE'] = '/srv/kallithea/.egg-cache'
 

	
 
    # sometimes it's needed to set the curent dir
 
    os.chdir('/srv/kallithea/')
 

	
 
    import site
 
    site.addsitedir("/srv/kallithea/venv/lib/python2.7/site-packages")
 

	
 
    from paste.deploy import loadapp
 
    ini = '/srv/kallithea/my.ini'
 
    from paste.script.util.logging_config import fileConfig
 

	
 
    fileConfig('/srv/kallithea/my.ini')
 
    application = loadapp('config:/srv/kallithea/my.ini')
 
    fileConfig(ini)
 
    from paste.deploy import loadapp
 
    application = loadapp('config:' + ini)
 

	
 
Or using proper virtualenv activation:
 

	
 
.. code-block:: python
 

	
 
    activate_this = '/srv/kallithea/venv/bin/activate_this.py'
 
    execfile(activate_this, dict(__file__=activate_this))
 

	
 
    import os
 
    os.environ['HOME'] = '/srv/kallithea'
 

	
 
    ini = '/srv/kallithea/kallithea.ini'
 
    from paste.script.util.logging_config import fileConfig
 
    fileConfig(ini)
 
    from paste.deploy import loadapp
 
    application = loadapp('config:' + ini)
 

	
 

	
 
Other configuration files
 
-------------------------
 

	
 
A number of `example init.d scripts`__ can be found in
 
the ``init.d`` directory of the Kallithea source.
 

	
kallithea/controllers/api/__init__.py
Show inline comments
 
@@ -99,49 +99,48 @@ class JSONRPCController(WSGIController):
 
    def __call__(self, environ, start_response):
 
        """
 
        Parse the request body as JSON, look up the method on the
 
        controller and if it exists, dispatch to it.
 
        """
 
        try:
 
            return self._handle_request(environ, start_response)
 
        finally:
 
            meta.Session.remove()
 

	
 
    def _handle_request(self, environ, start_response):
 
        start = time.time()
 
        ip_addr = self.ip_addr = self._get_ip_addr(environ)
 
        self._req_id = None
 
        if 'CONTENT_LENGTH' not in environ:
 
            log.debug("No Content-Length")
 
            return jsonrpc_error(retid=self._req_id,
 
                                 message="No Content-Length in request")
 
        else:
 
            length = environ['CONTENT_LENGTH'] or 0
 
            length = int(environ['CONTENT_LENGTH'])
 
            log.debug('Content-Length: %s', length)
 

	
 
        if length == 0:
 
            log.debug("Content-Length is 0")
 
            return jsonrpc_error(retid=self._req_id,
 
                                 message="Content-Length is 0")
 

	
 
        raw_body = environ['wsgi.input'].read(length)
 

	
 
        try:
 
            json_body = json.loads(raw_body)
 
        except ValueError as e:
 
            # catch JSON errors Here
 
            return jsonrpc_error(retid=self._req_id,
 
                                 message="JSON parse error ERR:%s RAW:%r"
 
                                 % (e, raw_body))
 

	
 
        # check AUTH based on API key
 
        try:
 
            self._req_api_key = json_body['api_key']
 
            self._req_id = json_body['id']
 
            self._req_method = json_body['method']
 
            self._request_params = json_body['args']
 
            if not isinstance(self._request_params, dict):
 
                self._request_params = {}
 

	
 
            log.debug(
 
                'method: %s, params: %s', self._req_method,
 
@@ -218,50 +217,49 @@ class JSONRPCController(WSGIController):
 
                    retid=self._req_id,
 
                    message=(
 
                        'Missing non optional `%s` arg in JSON DATA' % arg
 
                    )
 
                )
 

	
 
        self._rpc_args = {USER_SESSION_ATTR: u}
 

	
 
        self._rpc_args.update(self._request_params)
 

	
 
        self._rpc_args['action'] = self._req_method
 
        self._rpc_args['environ'] = environ
 
        self._rpc_args['start_response'] = start_response
 

	
 
        status = []
 
        headers = []
 
        exc_info = []
 

	
 
        def change_content(new_status, new_headers, new_exc_info=None):
 
            status.append(new_status)
 
            headers.extend(new_headers)
 
            exc_info.append(new_exc_info)
 

	
 
        output = WSGIController.__call__(self, environ, change_content)
 
        output = list(output)
 
        headers.append(('Content-Length', str(len(output[0]))))
 
        output = list(output) # expand iterator - just to ensure exact timing
 
        replace_header(headers, 'Content-Type', 'application/json')
 
        start_response(status[0], headers, exc_info[0])
 
        log.info('IP: %s Request to %s time: %.3fs' % (
 
            self._get_ip_addr(environ),
 
            safe_unicode(_get_access_path(environ)), time.time() - start)
 
        )
 
        return output
 

	
 
    def _dispatch_call(self):
 
        """
 
        Implement dispatch interface specified by WSGIController
 
        """
 
        raw_response = ''
 
        try:
 
            raw_response = self._inspect_call(self._func)
 
            if isinstance(raw_response, HTTPError):
 
                self._error = str(raw_response)
 
        except JSONRPCError as e:
 
            self._error = safe_str(e)
 
        except Exception as e:
 
            log.error('Encountered unhandled exception: %s',
 
                      traceback.format_exc(),)
 
            json_exc = JSONRPCError('Internal server error')
 
            self._error = safe_str(json_exc)
0 comments (0 inline, 0 general)