Passenger Namespace Reference

This file provides a bunch of classes for reading and writing messages in the MessageChannel format. More...


Classes

class  DirectoryMapper
 Utility class for determining URI-to-application directory mappings. More...
class  AbstractSpawnManager
 Spawning of application processes. More...
class  SystemException
 Represents an error returned by a system call or a standard library call. More...
class  FileSystemException
 A filesystem error, as returned by the operating system. More...
class  TimeRetrievalException
 Unable to retrieve the system time using time(). More...
class  IOException
 Represents an error that occured during an I/O operation. More...
class  FileNotFoundException
 Thrown when a certain file cannot be found. More...
class  EOFException
 An unexpected end-of-file I/O error. More...
class  ConfigurationException
 Thrown when an invalid configuration is given. More...
class  SpawnException
 Thrown when SpawnManager or ApplicationPool fails to spawn an application instance. More...
class  ArgumentException
 Indicates that a specified argument is incorrect or violates a requirement. More...
class  RuntimeException
 A generic runtime exception. More...
class  TimeoutException
 An exception indicating that some timeout expired. More...
class  SecurityException
 Represents some kind of security error. More...
class  BusyException
 The application pool is too busy and cannot fulfill a get() request. More...
class  FileDescriptor
 Wrapper class around a file descriptor integer, for RAII behavior. More...
class  EventFd
 A synchronization mechanism that's implemented with file descriptors, and as such can be used in combination with select() and friends. More...
class  MessageChannel
 Convenience class for I/O operations on file descriptors. More...
class  Uint16Reader
 Class for reading a 16-bit big-endian integer. More...
class  Uint32Reader
 Class for reading a 32-bit big-endian integer. More...
class  ArrayReader
 Class for reading a an array message. More...
class  ScalarReader
 Class for reading a scalar message. More...
class  MessageServer
 Simple pluggable request/response messaging server framework. More...
struct  PoolOptions
 This struct encapsulates information for ApplicationPool::get() and for SpawnManager::spawn(), such as which application is to be spawned. More...
class  Process
 Represents a single application process, as spawned by SpawnManager or by ApplicationPool::Interface::get(). More...
class  RandomGenerator
 A random data generator. More...
class  Session
 Represents a single request/response pair of an application process. More...
class  StandardSession
 A "standard" implementation of Session. More...
class  SpawnManager
 An AbstractSpawnManager implementation. More...
class  StaticString
 An immutable, static byte buffer. More...
struct  AnythingToString
 Used internally by toString(). More...
struct  AnythingToString< vector< string > >
 Used internally by toString(). More...
struct  AnythingToString< vector< StaticString > >
 Used internally by toString(). More...
class  BufferedUpload
 Represents a buffered upload file. More...
class  MemZeroGuard
 Fills the given memory space or string with zeroes when a MemoryZeroGuard object is destroyed. More...
class  HttpStatusExtractor
 Utility class for extracting the HTTP status value from an HTTP response. More...
class  ScgiRequestParser
 A parser for SCGI requests. More...

Typedefs

typedef shared_ptr
< AbstractSpawnManager
AbstractSpawnManagerPtr
 Convenient alias for AbstractSpawnManager smart pointer.
typedef shared_ptr< ProcessProcessPtr
 Convenient alias for Process smart pointer.
typedef shared_ptr< SpawnManagerSpawnManagerPtr
 Convenient alias for SpawnManager smart pointer.

Enumerations

enum  FileType { FT_NONEXISTANT, FT_REGULAR, FT_DIRECTORY, FT_OTHER }
 Enumeration which indicates what kind of file a file is. More...

Functions

apr_bucket * passenger_bucket_create (SessionPtr session, PassengerBucketStatePtr state, apr_bucket_alloc_t *list)
 We used to use an apr_bucket_pipe for forwarding the backend process's response to the HTTP client.
int atoi (const string &s)
 Converts the given string to an integer.
long atol (const string &s)
 Converts the given string to a long integer.
void split (const string &str, char sep, vector< string > &output)
 Split the given string using the given separator.
bool fileExists (const StaticString &filename, CachedFileStat *cstat=0, unsigned int throttleRate=0)
 Check whether the specified file exists.
FileType getFileType (const StaticString &filename, CachedFileStat *cstat=0, unsigned int throttleRate=0)
 Check whether 'filename' exists and what kind of file it is.
void createFile (const string &filename, const StaticString &contents, mode_t permissions=S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH, uid_t owner=USER_NOT_GIVEN, gid_t group=GROUP_NOT_GIVEN, bool overwrite=true)
 Create the given file with the given contents, permissions and ownership.
string canonicalizePath (const string &path)
 Returns a canonical version of the specified path.
string resolveSymlink (const string &path)
 If path refers to a symlink, then this function resolves the symlink for 1 level.
string extractDirName (const StaticString &path)
 Given a path, extracts its directory name.
string extractBaseName (const StaticString &path)
 Given a path, extracts its base name.
string escapeForXml (const string &input)
 Escape the given raw string into an XML value.
void setNonBlocking (int fd)
 Sets a socket in non-blocking mode.
string getProcessUsername ()
 Returns the username of the user that the current process is running as.
mode_t parseModeString (const StaticString &mode)
 Converts a mode string into a mode_t value.
const char * getSystemTempDir ()
 Return the path name for the directory in which the system stores general temporary files.
void makeDirTree (const string &path, const StaticString &mode="u=rwx,g=,o=", uid_t owner=USER_NOT_GIVEN, gid_t group=GROUP_NOT_GIVEN)
 Create the directory at the given path, creating intermediate directories if necessary.
void removeDirTree (const string &path)
 Remove an entire directory tree recursively.
bool verifyRailsDir (const string &dir, CachedFileStat *cstat=0, unsigned int throttleRate=0)
 Check whether the specified directory is a valid Ruby on Rails application root directory.
bool verifyRackDir (const string &dir, CachedFileStat *cstat=0, unsigned int throttleRate=0)
 Check whether the specified directory is a valid Rack application root directory.
bool verifyWSGIDir (const string &dir, CachedFileStat *cstat=0, unsigned int throttleRate=0)
 Check whether the specified directory is a valid WSGI application root directory.
string getHostName ()
 Returns the system's host name.
string fillInMiddle (unsigned int max, const string &prefix, const string &middle, const string &postfix="")
 Given a prefix string, a middle string and a postfix string, try to build a string that looks like prefix + middle + postfix, with as many characters from midle preserved as possible.
string toHex (const StaticString &data)
 Convert the given binary data to hexadecimal.
void toHex (const StaticString &data, char *output)
 Convert the given binary data to hexadecimal.
string getSignalName (int sig)
 Convert a signal number to its associated name.
int createUnixServer (const char *filename, unsigned int backlogSize=0, bool autoDelete=true)
 Create a new Unix server socket which is bounded to filename.
int connectToUnixServer (const char *filename)
 Connect to a Unix server socket at filename.
int connectToTcpServer (const char *hostname, unsigned int port)
 Connect to a TCP server socket at the given host name and port.
template<typename T >
shared_ptr< T > ptr (T *pointer)
 Convenience shortcut for creating a shared_ptr.
template<typename T >
string toString (T something)
 Convert anything to a string.
template<typename IntType >
IntType roundUp (IntType number, IntType multiple)
 Round number up to the nearest multiple of multiple.


Detailed Description

This file provides a bunch of classes for reading and writing messages in the MessageChannel format.

A random.

Unlike MessageChannel, whose operations take control over the I/O handle and may block, these classes are like parsers and data generators. Reader classes require the user to feed data to them. Writer classes generate a bunch of bytes that the user can send out. These classes will never block, making them ideal for use in evented servers.

Reading messages

To read a single message, one must instantiate a reader object and feed network data to it with the feed() method. This method returns the number of bytes actually processed by the reader (i.e. the number of bytes that it has recognized as part of the message).

When the reader has either successfully parsed the data or encountered an error, it will indicate so via the done() method. With hasError() one can check whether an error was encountered or whether the reader succeeded, and with errorCode() one can obtain the exact error reason. Not all readers support hasError() and errorCode() because some readers can never encounter errors and some readers only have a single reason to fail.

When successful, the parsed message can be obtained with value(). This method may only be called when done() is true and there is no error, otherwise the return value is undefined.

At this point, the reader object cannot process any more data and feed() will always return 0. To reuse the object for processing another message, one must reset its state by calling reset().

The following example demonstrates how to read a continuous stream of 32-bit integers:

   Uint32Reader intReader;
   while (true) {
       // Read a bunch of network data...
       char buf[1024];
       ssize_t size = recv(fd, buf, sizeof(buf));
       size_t consumed = 0;
       
       // ...and process it all. We only feed data to the reader that
       // hasn't already been fed.
       while (consumed < size) {
           consumed += intReader.feed(buf + consumed, size - consumed);
           if (intReader.done()) {
               printf("Integer: %d\n", (int) intReader.value());
               // The state must be reset before the reader can be reused.
               intReader.reset();
           }
       }
   }

Some readers return non-primitive values in their value() methods, such as ArrayReader and ScalarReader which return const vector<StaticString> & and StaticString, respectively. These values are only valid until either of the following things occur:

This is because the readers try to apply copy-zero optimizations whenever possible. For example, in case of ScalarReader, it'll check whether the data that has been fed in the first feed() call already contains a full scalar message. If so then it'll just return a StaticString that points to the scalar message in the fed data; it will not copy the fed data. In this case it is important that the buffer containing the fed data is not modified or destroyed while the StaticString is in use. If the first feed() call does not supply a full scalar message then it will buffer all fed data until the buffer contains a full scalar message, and the result will point to this buffer. Because the buffer is owned by the reader, the result will be invalidated as soon as the reader is destroyed.


Typedef Documentation

Convenient alias for AbstractSpawnManager smart pointer.

typedef shared_ptr<Process> Passenger::ProcessPtr

Convenient alias for Process smart pointer.

Convenient alias for SpawnManager smart pointer.


Enumeration Type Documentation

Enumeration which indicates what kind of file a file is.

Enumerator:
FT_NONEXISTANT  The file doesn't exist.

FT_REGULAR  A regular file or a symlink to a regular file.

FT_DIRECTORY  A directory.

FT_OTHER  Something else, e.g.

a pipe or a socket.


Function Documentation

string Passenger::fillInMiddle ( unsigned int  max,
const string &  prefix,
const string &  middle,
const string &  postfix = "" 
)

Given a prefix string, a middle string and a postfix string, try to build a string that looks like prefix + middle + postfix, with as many characters from midle preserved as possible.

If prefix + middle + postfix does not fit in max characters, then middle will be truncated so that it fits. If max is too small to contain even 1 character from middle, then an ArgumentException will be thrown.

   fillInMiddle(18, "server.", "1234", ".socket");    // "server.1234.socket"
   fillInMiddle(16, "server.", "1234", ".socket");    // "server.12.socket"
   fillInMiddle(14, "server.", "1234", ".socket");    // ArgumentException

Returns:
The resulting string, with middle possibly truncated.
Exceptions:
ArgumentException max is too small to contain even 1 character from middle.
Postcondition:
result.size() <= max

string Passenger::getHostName (  ) 

Returns the system's host name.

Exceptions:
SystemException The host name cannot be retrieved.

string Passenger::getProcessUsername (  ) 

Returns the username of the user that the current process is running as.

If the user has no associated username, then "UID xxxx" is returned, where xxxx is the current UID.

void Passenger::makeDirTree ( const string &  path,
const StaticString &  mode = "u=rwx,g=,o=",
uid_t  owner = USER_NOT_GIVEN,
gid_t  group = GROUP_NOT_GIVEN 
)

Create the directory at the given path, creating intermediate directories if necessary.

The created directories' permissions are exactly as specified by the 'mode' parameter (i.e. the umask will be ignored). You can specify this directory's owner and group through the 'owner' and 'group' parameters. A value of USER_NOT_GIVEN for 'owner' and/or GROUP_NOT_GIVEN 'group' means that the owner/group should not be changed.

If 'path' already exists, then nothing will happen.

Parameters:
mode A mode string, as supported by parseModeString().
Exceptions:
FileSystemException Something went wrong.
InvalidModeStringException The mode string cannot be parsed.

mode_t Passenger::parseModeString ( const StaticString &  mode  ) 

Converts a mode string into a mode_t value.

At this time only the symbolic mode strings are supported, e.g. something like looks this: "u=rwx,g=w,o=rx". The grammar is as follows:

   mode   ::= (clause ("," clause)*)?
   clause ::= who "=" permission*
   who    ::= "u" | "g" | "o"
   permission ::= "r" | "w" | "x" | "s"

Notes:

  • The mode value starts with 0. So if you specify "u=rwx", then the group and world permissions will be empty (set to 0).
  • The "s" permission is only allowed for who == "u" or who == "g".
  • The return value does not depend on the umask.

Exceptions:
InvalidModeStringException The mode string cannot be parsed.

apr_bucket * Passenger::passenger_bucket_create ( SessionPtr  session,
PassengerBucketStatePtr  state,
apr_bucket_alloc_t *  list 
)

We used to use an apr_bucket_pipe for forwarding the backend process's response to the HTTP client.

However, apr_bucket_pipe has a number of issues:

  • It closes the pipe's file descriptor when it has reached end-of-stream, but not when an error has occurred. This behavior is undesirable because it can easily cause file descriptor leaks.
  • It does weird non-blocking-I/O related things which can cause it to read less data than can actually be read.

PassengerBucket is like apr_bucket_pipe, but:

  • It also holds a reference to a Session. When a read error has occured or when end-of-stream has been reached, the Session will be dereferenced, so that the underlying file descriptor is closed.
  • It ignores the APR_NONBLOCK_READ flag because that's known to cause strange I/O problems.
  • It can store its current state in a PassengerBucketState data structure.

void Passenger::removeDirTree ( const string &  path  ) 

Remove an entire directory tree recursively.

If the directory doesn't exist then this function does nothing.

Exceptions:
FileSystemException Something went wrong.

template<typename IntType >
IntType Passenger::roundUp ( IntType  number,
IntType  multiple 
) [inline]

Round number up to the nearest multiple of multiple.

void Passenger::toHex ( const StaticString &  data,
char *  output 
)

Convert the given binary data to hexadecimal.

This form accepts an output buffer which must be at least data.size() * 2 bytes large.


Generated on Sun Mar 28 14:11:58 2010 for Passenger by  doxygen 1.5.8