# WebKit Install Guide

Contents

- Introduction
- Quick Start
- Prerequisites
  - Python
  - Web Server
    - Apache
    - IIS
    - AOLserver
    - Xitami
    - Other Servers
  - Webware Version
  - Operating Systems
- Installing Webware
- Updating Webware
- Architecture
  - Permissions
  - Adapters
  - WSGI-based Adapters
  - SCGI-based Adapters
  - CGI-based Adapters
    - wkcgi
    - Python CGI Adapter
    - mod_webkit
      - Posix Installation
      - Windows Installation
      - Apache Configuration
    - AOLServer
    - LRWP Adapter (for Xitami)
    - FastCGI
    - mod_python
    - mod_snake
    - OneShot
    - ISAPI
  - Renaming Adapters
  - Adapter Problems (not CGI)
- Configuration
  - Sessions
  - Contexts
  - Creating a Working Directory
- AppServer Notes
  - Stopping the App Server
  - Reloading Servlets
  - Launching the AppServer at Unix boot up
    - Start script configuration
    - Activating the start script
  - Running ThreadedAppServer as a Windows NT/2K/XP Service
  - Other Notes
- Troubleshooting
  - Bad Marshal Data

# Introduction

WebKit provides an application server that runs on both Unix and Windows as a persistent application (i.e., an application that stays running over the span of multiple requests).

This install guide takes you through the installation process while showing you what options are available and how you would use them. There are notes for specific operating systems and web servers preceded with tags such as Unix, WinNT, IIS, etc.

WebKit is fairly easy to install, but there are some important things to know. You will be doing yourself a favor by reading through this guide from top to bottom (skipping sections that don't apply to you).

We recommend that you get a simple configuration working first, where you can access the examples provided with Webware. Once you've gotten to that point, the remaining customization of the environment is fairly simple.

We use the term deploy to mean installing your web application/site in a well known location for access by your users. You first develop your web application and then deploy it. You will see deployment specific notes throughout the guide since the issues for these two situations can be different. In a nutshell, you want convenience during development, and security and performance during deployment.

You can always e-mail webware-discuss@lists.sourceforge.net to give feedback, discuss features and get help using WebKit.

# Quick Start

If you just want to get to a working configuration fast, install python, unpack your Webware distribution, and do the following (use backslashes instead of slashes if you are using Windows):

    $ cd path/to/Webware
    $ python install.py
    (enter password)
    $ WebKit/AppServer

You should now be able to go to your browser and open up the URL `http://localhost:8080`. The page you see is generated by `WebKit/Examples/Welcome.py`.

If the AppServer fails with the error message `Address already in use`, you will need to tell it to use a different port number. Edit `WebKit/Configs/AppServer.config`, set `AdapterPort` and `HTTPPort` to unused port numbers, restart AppServer, and alter your URL accordingly.

The AppServer has to be running anytime you want to access a Webware application or example. The last line of the instructions above is a simple way to start the AppServer in the console window you are working in. (There are scripts to run it automatically at boot up, see webkit init script).

# Prerequisites

## Python

Webware of course requires Python. It has been tested with Python version ranging from 2.4 to 2.7. For older Python versions, you can still use the Webware 1.0 branch. If you get an error message about the version, you're probably unwittingly running the wrong version of Python. Change the `AppServer` or `AppServer.bat` scripts, giving the full path to the correct Python interpreter. You can also try running Webware with PyPy. The AppServer should work with PyPy 1.5, but this has not been thoroughly tested and seems to be less performant.

Your installation of Python must be multi-threaded. It's not entirely uncommon for third party web host providers to leave this disabled in Python because they don't expect that it's needed or for compatibility with some software. If your Python installation is not multi-threaded you will have to reinstall it. If you're using a third party host provider in this situation, you may be able to install it yourself into your home directory via a telnet or ssh account. See the Python site for instructions.

To determine if threading is enabled, start the Python interpreter from the command line and enter `import thread`. If you don't get an exception, all is well.

## Web Server

Webware's built-in web server is adequate for development and casual use. Beyond that, you will want to use Webware in concert with another web server.

Any web server that supports CGI should be usable with Webware. Apache is the best supported platform, both on Posix and Windows systems. There is some experimental support for Xitami. For all other web servers (IIS included) you should expect to use CGI to interface with the AppServer.

### Apache

Apache is the best supported web server, both on Posix and Windows systems. The mod_webkit adapter is the fastest way to connect to Webware, and is only supported for Apache. CGI is also available to Apache users through wkcgi. For Windows users compiled versions of mod_webkit and wkcgi (named `wkcgi.exe`) are also available. There are also other adapter options, see Adapters.

Most of the Webware developers use Apache.

### IIS

Microsoft's Internet Information Server, or IIS, requires some special configuration due to its default non-standard CGI behavior. You have to do two things:

For IIS 4.0 to 6.0, configure it to handle PATH_INFO and PATH_TRANSLATED according to the CGI specification, by running the following command:

    > cscript adsutil.vbs SET W3SVC/1/AllowPathInfoForScriptMappings 1

This is lightly documented in http://msdn.microsoft.com/en-us/library/ms525840.aspx

A CGI adapter, written in C, is available in `WebKit/Adapters/wkcgi/wkcgi.exe`. The standard Python CGI adapter also works, but you must either configure IIS to run Python CGI scripts, or you must use PyInstaller or some other program to create an executable from the Python script.

In order to convert WebKit.cgi into WebKit.exe using PyInstaller, you first have to rename it to WebKit.py, and add `import socket` to the top of the file (you could use a configuration file instead, but this is easier). After creating the `.exe` file, delete `WebKit.pyc` and rename `WebKit.py` to `_WebKit.py`. This will avoid conflicts with `WebKit.exe`.

There is also an ISAPI module for Webware in `WebKit/Adapters/wkISAPI` that needs to be compiled before use. However, there have been problems with memory leaks in this adapter.

### AOLserver

The PyWX project aims to meld Python and AOLserver and as part of that, they created an AOLserver "stay resident" WebKit adapter for tighter integration. If you find that this adapter does not work with the latest release of Webware, please notify the PyWX project.

### Xitami

The Xitami web server purports to be smaller, and potentially easier to install than some of the other web servers. It can run the CGI adapters, but for more speed the LRWP adapter uses a persistent process for greater performance.

### Other Servers

Other servers should work using a CGI adapter or the SCGI connector.

## Webware Version

Unless you just downloaded Webware (and therefore WebKit), you should check to see if you have the latest version. This is:

Webware for Python

Version: | 1.1
Released: | 08/03/11

You can check for the latest version at http://www.webwareforpython.org.

If you're feeling adventurous, you can get the latest in-development source code from the public repository. Instructions are located at the Webware SVN page. You can find more information about SVN in general in the Subversion Book. The SVN version of Webware is generally fairly stable.

## Operating Systems

WebKit actively supports Posix (Linux, BSD, Mac OS X, Solaris, etc) and Windows (95/98/NT/2K/XP), and their various flavors.

Note that you don't have to develop and deploy on the same platform. One of the WebKit developers develops everything on Windows 98 2nd edition and deploys his web sites on BSD. Some of the web server setup is different, but in most cases the application itself will require no porting (unless you specifically use non-portable Python code in your application).

What follows are some OS specific notes:

Posix/Unix:
  Nothing special to report. Both Linux and BSD have been used with WebKit.
Windows 9x:
  Although a lot of the development of both WebKit and various web sites that use it has been done on Windows 9x, we don't recommend that you use this operating system to actually serve your users. Unix and NT are generally more robust and secure and therefore, more appropriate for deployment.
Windows:

  Some Windows users are surprised that URLs passed to WebKit are case sensitive. While it's true that the various Windows file systems are case insensitive, the data structures that WebKit uses internally are not.

  When editing path names in configuration files, keep in mind that you are editing a Python dictionary populated with Python strings. Therefore your paths must either use double backslashes (\) (since the backslash is a special character), use forward slashes or use "r-strings". An example of a bad string is `'C:\All\Web\'`. Good examples include:

  - `'/All/Web'`
  - `'C:/All/Web'`
  - `'C:\\All\\Web'`
  - `'C:\All\Web'`

  It's generally recommended to simply use forward slashes (/) for all your file paths.

# Installing Webware

Webware's main directory contains an `install.py` script that should always be run first.

Note that the install program doesn't actually copy the Webware files to any separate directory. It copies files within the Webware directory tree, modifies permissions, generates documentation, etc.

Also, you can run the install program as many times as you like with no ill effect, so if you're not sure whether or not it has been run, feel free to do so again. If you're debugging a problem with the installation, you can run `install.py -v` for verbose output.

# Updating Webware

When updating to a new major or minor version of Webware, check whether the Webware release notes recommend updating or recreating the working directories of your Webware applications.

# Architecture

The WebKit architecture involves three main entities at the top level:

- The web browser
- The web server
- The app server

The browser will be something like Microsoft Internet Explorer or Mozilla. The web server will be something like Apache or IIS. And finally, the app server will be WebKit, i.e. a Python process running the WebKit modules and your custom servlets.

The chronological order of events goes from top to bottom and then back up to top. In other words, the browser makes a request to the web server which in turn makes a request to the app server. The response then goes from the app server to the web server to the browser.

For development and casual use, you can replace Apache with the WebKit built-in web server that can be activated with the `AppServer.config` setting `EnableHTTP`. The port can be specified with the setting `HTTPPort` and will be `8080` by default.

If you are not using the built-in web server, you will have to get your web server and app server talking to each other. For this purpose, you must use a WebKit adapter. You must also activate the WebKit app server listener for adapters with the `AppServer.config` setting `EnableAdapter`. The port can be specified with the setting `AdapterPort` and will be `8086` by default. You can use several app servers listenting on different ports.

## Permissions

Webware runs as whatever user you run the AppServer as. So, while Apache might be running as nobody, if you start the AppServer as root then your application will be run as root. You may wish to set up another user specifically for running the AppServer. On Unix:

    $ adduser --no-create-home --system webkit
    $ cd path/to/Webware/WebKit
    $ sudo -u webkit ./AppServer

Whatever user you run the AppServer as, there are some directories under Webware/WebKit/ that must be writable by that user:

- Cache
- ErrorMsgs
- Logs
- Sessions

The easiest way to do this is to make these directories writeable by all (on Unix, that would be `cd Webware/WebKit; chmod -R a+rwX Cache ErrorMsgs Logs Sessions`).

You may wish to set it up this way at first, and review the permissions and create a new user later.

## Adapters

A WebKit adapter takes an HTTP request from a web server and, as quickly as possible, packs it up and ships it to the app server which subsequently sends the response back to the adapter for delivery to the web server and ultimately the web client. More concisely, an adapter is the go-between of the web server and the app server.

There are several adapters for Webware. However, it is highly recommended that you either use wkcgi or mod_webkit. Mod_webkit is the fastest adapter, but requires you to use Apache and usually to have root access to the computer. The wkcgi program uses CGI, and so is easy to install. Because it's small and written in C, wkcgi is still very fast.

All the adapters:

- wkcgi (C-based CGI script)
- mod_webkit (fastest!)
- mod_scgi (equally fast, not included with Webware)
- mod_wsgi (with the WSGIAdapter)
- AOLServer
- LRWP (Xitami)

These adapters are not really recommended:

- Python CGI Adapter
- FastCGI
- mod_python (with the ModPythonAdapter)
- mod_snake (with the ModSnakeAdapter)
- ISAPI (alpha, for IIS)
- OneShot (unusual to use, sometimes buggy)

## WSGI-based Adapters

WSGI is a standard interface between web servers and Python web applications that is described PEP333. It was invented much later than Webware and uses a very different approach from Webware and its WebKit architecture. Since it has been widely adapted as a Python standard in the last years, Webware now comes with an adapter that serves as an interface between any WSGI compliant webserver and the Webware application server. For Apache, the mod_wsgi module by Graham Dumpleton provides such an WSGI compliant interface. If the module is properly configured, this can be a solution nearly as fast as using the native mod_webkit adapter. Please see the documentation of mod_wsgi for details. You can use `WebKit/Adapters/WSGIAdapter.py` as the so called WSGI application script file for mod_wsgi.

## SCGI-based Adapters

Instead of using the standard WebKit adapter, you can also use any SCGI adapter such as mod_scgi (not part of Webware for Python). You can activate the SCGI connector, i.e. an WebKit app server listener for SCGI connections, with the `AppServer.config` setting `EnableSCGI`. The port can be specified with the setting `SCGIPort` and will be `8084` by default (SCGI often uses port 4000 or 9999, you may want to change that). The SCGI connector is actually very similar to the original Webware connector, but since Webware predates the SCGI protocol, it was added only later as an alternative that has not been in wide use. However, with mod_scgi, it is one of the fastest solutions for serving Webware applications.

## CGI-based Adapters

CGI-based adapters are the easiest to set up, and outside of Apache, Xitami, and AOLServer they are pretty much the only option.

Though these are CGI-based adapters, WebKit still runs as a persistent program with the AppServer. The CGI adapter is a program executed by the web server, which then contacts the AppServer and returns the response to the web server. Then the adapter quits, to be started again for another request. This starting up and stopping is what makes CGI slow. Because the adapter is small, this should still be faster than a all-CGI application, because most of the work is done in the persistent AppServer.

### wkcgi

wkcgi is a CGI-based adapter written in C. It's very small and is good at its one and only job of connecting to the AppServer. While a CGI-based adapter is the only option for some configurations, wkcgi is not a bad compromise -- it's quite fast. The only other adapter that is enough faster to be interesting is mod_webkit. You should choose one of these options.

On Windows systems you should find a file `WebKit/Adapters/wkcgi/wkcgi.exe`. You'll need to build the executable yourself on Posix systems -- just do:

    $ cd /path/to/Webware/WebKit/Adapters/wkcgi
    $ make

There will be a file `wkcgi`. You may want to rename it to `wkcgi.cgi`, since in some configurations files ending in `.cgi` will automatically be treated as CGI scripts.

To use the script, make sure you put it somewhere where CGI scripts can be executed. This may be in a `cgi-bin` directory, or in some configurations it can be located anywhere so long as the filename ends in `.cgi` and it's executable. Check your error log if you are (quickly) getting Internal Error when you try to access the script, and for Apache see the document Dynamic Content with CGI for configuration help.

If you get an Internal Error after a couple seconds, you don't have the AppServer running. Start the AppServer (`cd WebKit; ./AppServer`) and try again.

The AppServer may also be running on a non-standard host (i.e., not `localhost`) or a non-standard port (not 8086). If this is the case, you must put a file `webkit.cfg` in the same directory as the wkcgi executable. This file looks like:

    Host = localhost
    AdapterPort = 8086
    MaxConnectAttempts = 10
    ConnectRetryDelay = 1

### Python CGI Adapter

Though it's not recommended, there is an equivalent CGI script written in Python. This script is substantially slower, as it requires a Python interpreter to be started for each request. It is located in `WebKit/Adapters/WebKit.cgi` -- you may wish to point the first line (`#!/usr/bin/env python`) to the actual path of the Python interpreter (e.g., `#!/usr/local/bin/python`).

Otherwise, follow the instructions for wkcgi. Particularly, make sure that the script is executable. There is no configuration, and `WebKit.cgi` should be able to find the host and port of the AppServer automatically.

### mod_webkit

This is a native Apache module designed solely to communicate with WebKit. It is written in C, and has been tested on Linux and Windows. It can only be used with Apache.

This adapter is the fastest of the adapters available for WebKit. It is relatively easy to install, but you probably will need administrator or root access to the machine.

The source code and a README file describing how to configure, build and install mod_webkit as a DSO module for Apache 2.2 are located in the `Webware/WebKit/Adapters/mod_webkit2` directory. You can also find an older version for Apache 1.3 in `Webware/WebKit/Adapters/mod_webkit1`, but in the following we are assuming you are using Apache 2.2.

#### Posix Installation

To install:

    $ cd /path/to/Webware/WebKit/Adapters/mod_webkit2
    $ make
    $ make install

The most common error you will get in this process is an error `make: /usr/sbin/apxs: Command not found`. This means the `apxs` utility is probably located somewhere else, or you do not have it installed. It should be in one of these locations:

> - /usr/bin/apxs
> - /usr/local/bin/apxs
> - /usr/local/sbin/apxs
> - /usr/local/Apache-.../.../apxs

If you have an Apache directory under `/usr/local`, you should search it for the file. Execute the command `find /usr/local/Apache... -name apxs` to search for it.

If you cannot find it in any of these locations there is a good chance you don't have it installed. You should install an apache-devel package.

Once you've found or attained the apxs utility, change the `Makefile` file in the mod_webkit directory. Where it says `APXS=/usr/sbin/apxs`, change it to the appropriate location.

`make install` will copy the compiled module to the appropriate location and add a line to your httpd.conf file to load the module (but not activate it, see Apache Configuration below).

#### Windows Installation

Copy `WebKit/Adapters/mod_webkit2/mod_webkit.dll` into your Apache 2.2 module directory (usually located at `C:\Program Files\Apache Software Foundation\Apache2.2\modules\mod_webkit.so`). You should also change the extension of the file to `.so` according to the Apache convention.

Edit `httpd.conf` to include the line:

    LoadModule webkit_module modules/mod_webkit.so

Then, add the configuration below to activate the module.

#### Apache Configuration

You must also add something like this to your httpd.conf:

    <Location /WK>
        WKServer localhost 8086
        SetHandler webkit-handler
    </Location>

Some Apache 2.2 users have found that they must use "127.0.0.1" instead of "localhost", since Apache 2.2 defaults to using ipv6 addresses first.

With these lines, any URL that starts with `/WK/` will be directed to the AppServer on port 8086. You can also use:

    AddHandler psp-handler .psp

to run PSP files that are found anywhere (similar to how PHP would work, for example). You still need the `/WK` portion to tell mod_webkit where to find the AppServer.

To pass additional client HTTP headers through to the AppServer, use the `PassHeader` Apache directive. For example:

    PassHeader Accept-Language

Your servlet code can access the header value like this:

    lang = self.request().environ().get('Accept-Language')

If the client request contains the header `Accept-Language: fr`, the above code will set `lang` to `"fr"`.

### AOLServer

This adapter comes with the Python-enhanced AOLserver created by the PyWX project and is described there.

### LRWP Adapter (for Xitami)

The LRWP Adapter is meant to be used with the Xitami web server. It requires the LRWP Python library to be loaded. We don't know a great deal more than that.

### FastCGI

In most cases FastCGI will not be significantly faster than wkcgi (and may be slower!), and FastCGI is considerably slower than mod_webkit. At the same time it is also much more difficult to configure. Its use is not recommended.

Your web server will have to be FastCGI enabled, which you may be able to accomplish by downloading software at http://www.FastCGI.com where you can also learn more about FastCGI.

The top of `WebKit/Adapters/FCGIAdapter.py` contains a doc string explaining its setup.

Note that to date, we have only gotten this to work on Unix.

### mod_python

In most cases the mod_python adapter will not be significantly faster than wkcgi (and may be slower!), and the mod_python adapter is considerably slower than mod_webkit. At the same time it is also much more difficult to configure. Its use is not recommended.

The top of `WebKit/Adapters/ModPythonAdapter.py` contains a doc string explaining the setup.

This has been tested on both Unix and Windows. On Windows you should use mod_python 2.7.4 or later because there is a bug in earlier versions of mod_python for Windows that can cause Apache to crash or return incorrect responses under heavy load.

More information about mod_python can be found at http://www.modpython.org.

### mod_snake

In most cases the mod_snake adapter will not be significantly faster than wkcgi (and may be slower!), and the mod_snake adapter is considerably slower than mod_webkit. At the same time it is also much more difficult to configure. Its use is not recommended.

This adapter is similar to ModPython, but written for the mod_snake Apache module. mod_snake is another method of embedding a python interpreter into Apache.

A doc string is included at the top of `WebKit/Adapters/ModSnakeAdapter.py` which describes the configuration steps to use this adapter.

### OneShot

The OneShot adapter is another CGI based adapter, but unlike wkcgi and WebKit.cgi, the AppServer launches, serves a response and shuts down for every single request via OneShot.cgi.

OneShot is very slow, and has caused numerous weird errors over time. If you use OneShot and encounter a bug, be sure to report that you're using OneShot when you submit the bug. Most of the developers don't use OneShot anymore, and it's not as well tested as other parts of the Webware code (and the constant starting and stopping of the AppServer is also not well tested).

You may want to use OneShot on a commercial host where persistent processes (like the AppServer process) are not allowed. However, be warned that OneShot is very slow.

If you use OneShot, do not launch the AppServer separately. Note that in this case, the instructions on setting the permissions apply to the user running the web server.

### ISAPI

The ISAPI module is located in `WebKit/Adapters/wkISAPI`. It currently has some memory leaks and is not well tested. It is looking for a maintainer. There's no documentation for it, and you must compile it yourself.

## Renaming Adapters

Adapters such as WebKit.cgi and OneShot.cgi do not rely on their name. Consequently, when you deploy your web site, you can rename the adapter to something like `serve.cgi`. This allows you to switch adapters later without affecting the URLs and therefore the bookmarks of your users (provided you're still using some form of CGI adapter). mod_rewrite also offers several possibilities for changing names, redirecting the root of a site to a specific context, or other URL manipulations. Mod_rewrite is extremely general.

## Adapter Problems (not CGI)

There is one gotcha in setting up the adapters that don't rely on CGI. For mod_webkit, ModPython and ModSnake, the name that you give to the adapter location in your Apache configuration file must not actually exist in your Apache document root. Also, you may not have a file or directory in your document root with the same name as one of WebKit's contexts. So, you can't have a directory named Examples in your document root.

# Configuration

In this section, we'll briefly touch on some of the configuration options related to installing and running WebKit. A full reference to these options can be found in the User's Guide.

The settings referenced below are found in the configuration file, `WebKit/Configs/Application.config`.

## Sessions

WebKit provides a Session utility class for storing data on the server side that relates to an individual user's session with your site. The `SessionStore` setting determines where the data is stored and can currently be set to `Dynamic`, `File`, `Memcached`, `Memory` or `Shelve`.

Storing to the Dynamic session store is the fastest solution and is the default. This session storage method keeps the most recently used sessions in memory, and moves older sessions to disk periodocally. All sessions will be moved to disk when the server is stopped. This storage mechanism works with both the persistant, long running AppServers and OneShot. There are two settings in `Application.config` relating to this Dynamic session store. `MaxDynamicMemorySessions` specifies the maximum number of sessions that can be in memory at any one time. `DynamicSessionTimeout` specifies after what period of time sessions will be moved from memory to file. (Note: this setting is unrelated to the `SessionTimeout` setting below. Sessions which are moved to disk by the Dynamic Session store are not deleted). Alternatively to the Dynamic store, you can try out the Shelve session store which stores the sessions in a database file using the Python shelve module.

If you are using more than one AppServer for load-balancing, the Memcached store will be interesting for you. Using the python-memcached interface, it is able to connect to a Memcached system and store all the session data there. This allows user requests to be freely moved from one AppServer to another while keeping their sessions, because they are all connected to the same memcache.

Storing to files is provided mainly in support of the OneShot adapter. It may also prove useful in the future in support of load balancing. In this scenario, each individual session is stored in its own file, loaded for every request and saved when delivering the corresponding response.

All on-disk session information is located in WebKit/Sessions.

Also, the `SessionTimeout` setting lets you set the number of minutes of inactivity before a user's session becomes invalid and is deleted. The default is 60. The Session Timeout value can also be changed dynamically on a per session basis.

`Activity Log`

Three options let you control:

> - Whether or not to log activity (`LogActivity`, defaults to 0, i.e. off)
> - The name of the file to store the log (`ActivityLogFilename`, defaults to `Logs/Activity.csv`)
> - The fields to store in the log (`ActivityLogColumns`) </ul>

See Configuration in the User's Guide for more information.

E-mail Errors

`EmailErrors`, `ErrorEmailServer` and `ErrorEmailHeaders` let you configure the app server so that uncaught exceptions land in your mailbox in real time. You should definitely set these options when deploying a web site.

See Configuration in the User's Guide for more information.

## Contexts

WebKit divides the world into contexts, each of which is a directory with its own files and servlets. WebKit will only serve files out of its list of known contexts.

Some of the contexts you will find out of the box are `Examples`, `Documentation` and `Admin`. When viewing either an example or admin page, you will see a sidebar that links to all the contexts.

Another way to look at contexts is a means for "directory partitioning". If you have two distinct web applications (for example, `PythonTutor` and `DayTrader`), you will likely put each of these in their own context. In this configuration, both web applications would be served by the same appserver instance. Note that there may be also reasons to run multiple appserver instances for serving your web applications. For instance, this would allow you to start and stop them independently, run them under different users to give them different permissions, or partition resources like number of threads individually among the web applications.

Instead of adding your own contexts you may wish to use MakeAppWorkDir, which will partition your application from the Webware installation.

To add a new context, add to the `Contexts` dictionary of `Application.config`. The key is the name of the context as it appears in the URL and the value is the path (absolute or relative to the WebKit directory). Often the name of the context and the name of the directory will be the same:

    'DayTrader': '/All/Web/Apps/DayTrader',

The URL to access DayTrader would then be something like: `http://localhost/WebKit.cgi/DayTrader/`

The special name `default` is reserved to specify what context is served when none is specified (as in `http://localhost/WebKit.cgi/`). Upon installation, this is the `Examples` context, which is convenient during development since it provides links to all the other contexts.

Note that a context can contain an `__init__.py` which will be executed when the context is loaded at app server startup. You can put any kind of initialization code you deem appropriate there.

## Creating a Working Directory

You can create a working directory for your applications that is separate from the Webware installation. To do this you will use the script `bin/MakeAppWorkDir.py`. You should run it like:

    $ python Webware/bin/MakeAppWorkDir.py WorkDir

This will create a directory WorkDir that will contain a directory structure for your application. Name if after your application, place it where it is convenient for you -- it doesn't need to be located close to the Webware installation.

You have a couple of options available, e.g. for chosing the name and location of the default context or creating additional library directories that will be added to the Python seach path. You can see all of these options if you run `bin/MakeAppWorkDir.py` without any parameters.

When you list the created directory, you will see something like this:

    AppServer*  Configs/       ErrorMsgs/  Lib/   MyContext/  WebKit.cgi
    Cache/      error404.html  Launch.py   Logs/  Sessions/   webkit*

Here's what the files and directories are for:

`AppServer`:
  The script to start up the AppServer for this application. Each application will have its own AppServer, and its own process. If you are running under Windows, you will see a `AppServer.bat` instead and additionally, you will find a `AppServerService.py` script that can be used to start the AppServer as a service.
`Cache`:
  A directory containing cache files. You won't need to look in here.
`Configs`:
  Configuration files for the application. These files are copied from `WebKit/Configs`, but are specific to this application/AppServer.
`error404.html`:
  The static HTML page to be displayed when a page is not found. You can remove this to display a standard error message, modify the page according to your preferences, or use a custom error servlet instead by setting `ErrorPage` in the `Application.config` file appropriately.
`ErrorMsgs`:
  HTML pages for any errors that occur. These can pile up and take up considerable size (even just during development), so you'll want to purge these every so often.
`Launch.py`:
  Called by the `AppServer` script to launch the AppServer.
`Lib`:
  An example for an application-specific library package that can be created with the `-l` option (in this case, `-l Lib`). Import modules from this directory like `from Lib.SitePage import SitePage`.
`Logs`:
  Logs of accesses.
`MyContext`:
  The directory for your default context. This is where you put your servlets. you can change its name and location with the ``-c` and `-d` options. You can also change this subsequently in the `Application.config` file in the `Configs` directory, where you can also configure more than one context. You may also want to remove the other standard contexts that come with Webware from the config file.
`Sessions`:
  Users sessions. These should be cleaned out automatically, you won't have to look in this directory.
`WebKit.cgi`:
  A CGI script/adapter for accessing the AppServer here. You can still use the other adapters, but most of them don't need to be configured for the individual applications. I still recommend `mod_webkit` or `wkcgi`.
`webkit*`:
  If you are running under Unix, you can use this as a start script (see webkit init script).

# AppServer Notes

WebKit uses a process called an AppServer to handle requests. The AppServer is responsible for receiving a request from the adapter, and then running it through the Application, and then sending the response back to the adapter.

## Stopping the App Server

The recommended method of stopping the AppServer is through the Application Control interface. This is a servlet located in the Admin context. A username and password are required -- the username is always `admin`, and the password is set when you run `install.py`. (You can change the password through the `WebKit/Configs/Application.config` file). This shutdown method is safer than doing a Control-C from a terminal, as described below.

On all OSs, stopping the app server may also be accomplished by simply going to its terminal/command window and hitting Control-C. The app server is designed to intercept this interruption and shut down as gracefully as possible. This includes saving session data to disk, if necessary.

On Unix, a running appserver may be stopped from a terminal by typing `./AppServer stop`.

On Windows Control-C normally shuts the app server down gracefully, where as Control-Break does not. Keep that in mind and use Control-C, unless the server is unresponsive to it.

On Unix if you don't have access to the terminal window of the app server (perhaps because you used rlogin, telnet or ssh to remotely access the machine), and "AppServer stop" doesn't work, you can use `ps -ax | grep ThreadedAppServer` to get the pid and `kill <pid>` to effect a Control-C.

## Reloading Servlets

As you develop your web application, you will change the code of your various Python classes, including your servlets. The WebKit app server will detect a change in the timestamp of a servlet's source file and automatically reload it for you.

However, reloading fails in two areas. The first is that WebKit doesn't check ancestor classes of servlets for modifications. So if you modify an abstract class (for example, `SitePage`, `AccountPage`, etc.), it won't be reloaded. The second is that WebKit can't check non-servlet classes. So if you modify a utility class (for example, `ShoppingCart`, `Story`, etc.), it won't be reloaded.

While developing this will happen quite often. There is a setting in `WebKit/Configs/AppServer.config` that you should turn on early in your experimentations.

The line:

    'AutoReload':      0,

in `AppServer.config` controls a feature where the AppServer stops and restarts itself if any loaded modules have been changed.

You can also deal with reloading problems by stopping the app server (Control-C in its terminal/command window) and restarting it. And an alternative way of reloading ancestor classes is through the Application Control servlet, in the Admin context, which will provide a list of all of the currently loaded modules, and allow you to reload selected modules. Be warned, reloading modules can cause strange behavior, because instances of objects attached to the old class definitions can still exist. AutoReload is generally the best solution.

## Launching the AppServer at Unix boot up

The script `WebKit/webkit` is a Unix shell script launching WebKit at boot time through the standard "init" mechanisms.

There are several variants of this script for various flavors of Unix available in the folder `WebKit/StartScripts`. The `install.py` script copies the variant that it thinks is the best fit to `WebKit/webkit`. If the script does not fit to your system, you may want to try out other variants or the `Generic` script that should fit on most systems.

If you create a working directory using `bin/MakeAppWorkDir.py` as explained above, the `webkit` start script will also be copied to the working directory.

In order to start WebKit at boot time, copy this script to the system folder that is destined for start scripts, which is usually `/etc/init.d/` (e.g. for SuSE or Debian Linux or Solaris) or `/etc/rc.d/init.d/` (e.g. for RedHat or Mandrake Linux). Instead of copying the script, you can also make a symbolic link refering to the script located in your working directory. If you do this, the script will be able to determine the location of the working directory from the symbolic link and you do not have to set the location in the script itself.

### Start script configuration

At the top of the start script, you will find a configuration section where you can change several variables that influence the start-up process. The main configuration parameters are the following:

    WORK_DIR      the location of your working directory

    LOG_FILE      the location of the log file which records the standard
                  and error output of the application server

    PID_FILE      the location of the pid file which records the process id
                  of the Python application server

    WEBWARE_USER  the user to run the application server

For security reasons, you shouldn't use `root` as the Webware user, but a user with the least possible permissions, maybe even `nobody`. By default, the start script uses the owner of the `AppServer` script.

For the log file and the pid file, you may either use the standard locations on your system, usually something like `/var/log/webkit.log` and `/var/log/webkit.pid` (use different names for different instances), or you may store them in the working directory and its `Logs` subdirectory. In the first case, the files should be written as the root user, because other users usually won't have writing permission for the standard locations. In the second case, the files should be written as the Webware user, so you won't need to be `root` to restart the application server. Therefore, the configuration section has another variable `LAUNCH_AS_WEBWARE` that determines whether Webware will launch as `root` and then (after writing the pid and log files) switch to the Webware user, or whether Webware will immediately launch and write both files as the Webware user.

By default, the script will start as the Webware user and will write the files to the working directory, so you have to unset `LAUNCH_AS_WEBWARE` if you want to use the standard system locations for the files instead.

Note that the application server maintains its own pid file, usually called `appserver.pid`. You should use a different pid file for the start script, although it actually records the same pid, i.e. the pid of Webware's Python application server, not the pid of the wrapper script `AppServer` which is responsible for the AutoReload mechanism.

The start script also passes the variable `PYTHONOPTS` to the `AppServer` script. You can add options `-U` for unbuffered output (to the log file) or `-O` if you want to use optimized Python files (i.e. `.pyo` instead of `.pyc`). You can also add additional Python libraries with `PYTHONPATH`.

### Activating the start script

First try whether your start script works:

    > ./webkit start

The WebKit application server should now be launched and you should see it in the output of the `ps` command.

Also try to stop WebKit by typing:

    > ./webkit stop

To activate the script for future boots, you still have to put symbolic links to the runlevel directories in which you want to launch WebKit. On some systems, you have to do this manually. For example, if the start script is `/etc/init.d/webkit`, you would create the symbolic links like that:

    > cd /etc/rc0.d
    > ln -s ../init.d/webkit K75webkit
    (repeat for rc1.d and rc6.d)
    > cd /etc/rc2.d
    > ln -s ../init.d/webkit S25webkit
    (repeat for rc3.d, rc4.d, and rc5.d)

Some systems also provide a command line tool for this purpose, which will depend on the flavor of Unix you are using. For instance, you will use `insserv` on SuSE Linux, `chkconfig` for RedHat (Fedora), `update-rc.d` for Debian (Ubuntu) or `rc-update` for Gentoo.

Take care to launch the script after your web server and database and other services you are using. You can do this by using appropriate numbers for the symbolic links or setting approriate hints for the command line tools at the top of the script.

See the corresponding `man` pages or administrator handbook of your Unix system for the details of installing start scripts.

## Running ThreadedAppServer as a Windows NT/2K/XP Service

`AppServerService` is a script that runs the `ThreadedAppServer` as a Windows NT Service. This means it can be started and stopped from the Control Panel or from the command line using `net start` and `net stop`, and it can be configured in the Control Panel to auto-start when the machine boots. This is the preferred way to deploy WebKit on a Windows NT/2K/XP platform.

`AppServerService` requires the Python win32all extensions to have been installed.

To see the options for installing, removing, starting, and stopping the service, just run `AppServerService.py` with no arguments. Typical usage is to install the service to run under a particular user account and startup automatically on reboot with:

    > python AppServerService.py ^
      --username mydomain\myusername ^
      --password mypassword --startup auto install

(Note: The caret (^) is the line continuation character under Windows.)

Then, you can start the service from the Services applet in the Control Panel, where it will be listed as "WebKit Application Server". Or, from the command line, it can be started with either of the following commands:

    > net start WebKit
    > python AppServerService.py start

The service can be stopped from the Control Panel or with:

    > net stop WebKit
    > python AppServerService.py stop

And finally, to uninstall the service, stop it and then run:

    > python AppServerService.py remove

## Other Notes

See Stopping the App Server and Reloading Servlets above in Adapters.

# Troubleshooting

## Bad Marshal Data

The most common installation problem is a Python exception appearing in your browser that says "bad marshal data". This is always caused by pointing the web browser to the app server:

> http://localhost:8086/WebKit.cgi/

But the app server hides behind a web server so the correct URL would be:

> http://localhost/WebKit.cgi/

That requires that web server and app server are set up to talk to each other. And that's what the Adapters section is all about...