Add Sphinx documentation.

Add more events.

Also, return Job objects from event handlers for convenience of
subclasses.

Add sphinx config to setup.cfg.

Change-Id: I2ccc32fbc5f043a67d5da86cc3c37ab3d2c30d99
This commit is contained in:
James E. Blair 2013-04-08 15:17:42 -07:00
parent 8a8b7ffab0
commit ba9ff1c9c6
5 changed files with 521 additions and 9 deletions

243
doc/source/conf.py Normal file
View File

@ -0,0 +1,243 @@
# -*- coding: utf-8 -*-
#
# Gear documentation build configuration file, created by
# sphinx-quickstart on Mon Apr 8 15:28:36 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
sys.path.insert(0, os.path.abspath('../..'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Gear'
copyright = u'2013, OpenStack Foundation'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '1.0'
# The full version, including alpha/beta/rc tags.
release = '1.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'Geardoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'Gear.tex', u'Gear Documentation',
u'OpenStack Foundation', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'gear', u'Gear Documentation',
[u'OpenStack Foundation'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'Gear', u'Gear Documentation',
u'OpenStack Foundation', 'Gear', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'

21
doc/source/index.rst Normal file
View File

@ -0,0 +1,21 @@
.. Gear documentation master file, created by
sphinx-quickstart on Mon Apr 8 15:28:36 2013.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Gear: Asynchronous Event-Driven Gearman Interface
=================================================
.. automodule:: gear
:members:
.. automodule:: gear.constants
:members:
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

View File

@ -12,6 +12,55 @@
# License for the specific language governing permissions and limitations
# under the License.
"""
This module implements an asynchronous event-driven interface to
Gearman. Currently, only the client interface is implemented. To
use, instantiate a :py:class:`Client`, and submit a :py:class:`Job`.
For example::
import gear
client = gear.Client()
client.addServer('gearman.example.com')
client.waitForServer() # Wait for at least one server to be connected
job = gear.Job("reverse", "test string")
client.submitJob(job)
The waitForServer() call is only necessary when running in a
synchronous context. When running asynchronously, it is probably more
desirable to omit that call and instead handle the
:py:class:`NoConnectedServersError` exception that submitJob may
raise if no servers are connected at the time.
When Gearman returns data to the client, the :py:class:`Job` object is
updated immediately. Event handlers are called on the
:py:class:`Client` object so that subclasses have ample facilities for
reacting to events synchronously.
API Reference
=============
Constants
---------
These constants are used by public API classes.
.. py:data:: PRECEDENCE_NORMAL
Normal job precedence.
.. py:data:: PRECEDENCE_LOW
Low job precedence.
.. py:data:: PRECEDENCE_HIGH
High job precedence.
Class Reference
---------------
"""
import logging
import os
import select
@ -48,6 +97,8 @@ class UnknownJobError(Exception):
class Connection(object):
"""A Connection to a Gearman Server."""
log = logging.getLogger("gear.Connection")
def __init__(self, host, port):
@ -67,6 +118,11 @@ class Connection(object):
id(self), self.host, self.port)
def connect(self):
"""Open a connection to the server.
:raises ConnectionError: If unable to open the socket.
"""
self.log.debug("Connecting to %s port %s" % (self.host, self.port))
s = None
for res in socket.getaddrinfo(self.host, self.port,
@ -93,17 +149,34 @@ class Connection(object):
self.connected = True
def disconnect(self):
"""Disconnect from the server and remove all associated state
data.
"""
self.log.debug("Disconnected from %s port %s" % (self.host, self.port))
self._init()
def reconnect(self):
"""Disconnect from and reconnect to the server, removing all
associated state data.
"""
self.disconnect()
self.connect()
def sendPacket(self, packet):
"""Send a packet to the server.
:arg Packet packet: The :py:class:`Packet` to send.
"""
self.conn.send(packet.toBinary())
def readPacket(self):
"""Read one packet from the server.
Blocks until the complete packet is read.
:returns: The :py:class:`Packet` read.
:rtype: :py:class:`Packet`
"""
packet = b''
datalen = 0
code = None
@ -120,6 +193,18 @@ class Connection(object):
class Packet(object):
"""A data packet received from or to be sent over a
:py:class:`Connection`.
:arg str code: The Gearman magic code (:py:data:`constants.REQ` or
:py:data:`constants.RES`)
:arg str ptype: The packet type (one of the packet types in constasts).
:arg str data: The data portion of the packet.
:arg str connection: The connection on which the packet was received
(optional).
:raises InvalidDataError: If the magic code is unknown.
"""
log = logging.getLogger("gear.Packet")
def __init__(self, code, ptype, data, connection=None):
@ -135,14 +220,33 @@ class Packet(object):
return '<gear.Packet 0x%x type: %s>' % (id(self), ptype)
def toBinary(self):
"""Return a Gearman wire protocol binary representation of the packet.
:returns: The packet in binary form.
:rtype: str
"""
b = struct.pack('!4sii', self.code, self.ptype, len(self.data))
b += self.data
return b
def getArgument(self, index):
"""Get the nth argument from the packet data.
:arg int index: The argument index to look up.
:returns: The argument value.
:rtype: str
"""
return self.data.split('\x00')[index]
def getJob(self):
"""Get the :py:class:`Job` associated with the job handle in
this packet.
:returns: The :py:class:`Job` for this packet.
:rtype: str
:raises UnknownJobError: If the job is not known.
"""
handle = self.getArgument(0)
job = self.connection.related_jobs.get(handle)
if not job:
@ -151,6 +255,14 @@ class Packet(object):
class Client(object):
"""A Gearman client.
You may wish to subclass this class in order to override the
default event handlers to react to Gearman events. Be sure to
call the superclass event handlers so that they may perform
job-related housekeeping.
"""
log = logging.getLogger("gear.Client")
def __init__(self):
@ -192,6 +304,8 @@ class Client(object):
:arg str host: The hostname or IP address of the server.
:arg int port: The port on which the gearman server is listening.
:raises ConfigurationError: If the host/port combination has
already been added to the client.
"""
self.log.debug("Adding server %s port %s" % (host, port))
@ -283,6 +397,11 @@ class Client(object):
this method external to the library, as more consumer-oriented
methods such as submitJob already use it internally, but is
available nonetheless if necessary.
:returns: The next scheduled :py:class:`Connection` object.
:rtype: :py:class:`Connection`
:raises NoConnectedServersError: If there are not currently
connected servers.
"""
conn = None
@ -364,10 +483,16 @@ class Client(object):
:arg Job job: The :py:class:`Job` to submit.
:arg bool background: Whether the job should be backgrounded.
:arg int precedence: Whether the job should have normal, low, or
high precedence. One of gear.PRECEDENCE_NORMAL,
gear.PRECEDENCE_LOW, gear.PRECEDENCE_HIGH
high precedence. One of :py:data:`PRECEDENCE_NORMAL`,
:py:data:`PRECEDENCE_LOW`, or :py:data:`PRECEDENCE_HIGH`
:raises ConfigurationError: If an invalid precendence value
is supplied.
"""
data = '%s\x00%s\x00%s' % (job.name, job.unique, job.arguments)
if job.unique is None:
unique = ''
else:
unique = job.unique
data = '%s\x00%s\x00%s' % (job.name, unique, job.arguments)
if background:
if precedence == PRECEDENCE_NORMAL:
cmd = constants.SUBMIT_JOB_BG
@ -416,6 +541,16 @@ class Client(object):
self.handleJobCreated(packet)
elif packet.ptype == constants.WORK_COMPLETE:
self.handleWorkComplete(packet)
elif packet.ptype == constants.WORK_FAIL:
self.handleWorkFail(packet)
elif packet.ptype == constants.WORK_EXCEPTION:
self.handleWorkException(packet)
elif packet.ptype == constants.WORK_DATA:
self.handleWorkData(packet)
elif packet.ptype == constants.WORK_WARNING:
self.handleWorkWarning(packet)
elif packet.ptype == constants.WORK_STATUS:
self.handleWorkStatus(packet)
def handleJobCreated(self, packet):
"""Handle a JOB_CREATED packet.
@ -424,11 +559,15 @@ class Client(object):
returned job handle.
:arg Packet packet: The :py:class:`Packet` that was received.
:returns: The :py:class:`Job` object associated with the job request.
:rtype: :py:class:`Job`
"""
job = packet.connection.pending_jobs.pop(0)
job.handle = packet.data
packet.connection.related_jobs[job.handle] = job
self.log.debug("Job created; handle: %s" % job.handle)
return job
def handleWorkComplete(self, packet):
"""Handle a WORK_COMPLETE packet.
@ -438,6 +577,8 @@ class Client(object):
connection.
:arg Packet packet: The :py:class:`Packet` that was received.
:returns: The :py:class:`Job` object associated with the job request.
:rtype: :py:class:`Job`
"""
job = packet.getJob()
@ -445,6 +586,9 @@ class Client(object):
job.complete = True
job.failure = False
del packet.connection.related_jobs[job.handle]
self.log.debug("Job complete; handle: %s data: %s" %
(job.handle, job.data))
return job
def handleWorkFail(self, packet):
"""Handle a WORK_FAIL packet.
@ -454,12 +598,16 @@ class Client(object):
connection.
:arg Packet packet: The :py:class:`Packet` that was received.
:returns: The :py:class:`Job` object associated with the job request.
:rtype: :py:class:`Job`
"""
job = packet.getJob()
job.complete = True
job.failure = True
del packet.connection.related_jobs[job.handle]
self.log.debug("Job failed; handle: %s" % job.handle)
return job
def handleWorkException(self, packet):
"""Handle a WORK_Exception packet.
@ -469,6 +617,8 @@ class Client(object):
connection.
:arg Packet packet: The :py:class:`Packet` that was received.
:returns: The :py:class:`Job` object associated with the job request.
:rtype: :py:class:`Job`
"""
job = packet.getJob()
@ -476,6 +626,9 @@ class Client(object):
job.complete = True
job.failure = True
del packet.connection.related_jobs[job.handle]
self.log.debug("Job exception; handle: %s data: %s" %
(job.handle, job.exception))
return job
def handleWorkData(self, packet):
"""Handle a WORK_DATA packet.
@ -483,10 +636,15 @@ class Client(object):
Updates the referenced :py:class:`Job` with the returned data.
:arg Packet packet: The :py:class:`Packet` that was received.
:returns: The :py:class:`Job` object associated with the job request.
:rtype: :py:class:`Job`
"""
job = packet.getJob()
job.data += packet.getArgument(1)
self.log.debug("Job data; handle: %s data: %s" %
(job.handle, job.data))
return job
def handleWorkWarning(self, packet):
"""Handle a WORK_WARNING packet.
@ -494,11 +652,16 @@ class Client(object):
Updates the referenced :py:class:`Job` with the returned data.
:arg Packet packet: The :py:class:`Packet` that was received.
:returns: The :py:class:`Job` object associated with the job request.
:rtype: :py:class:`Job`
"""
job = packet.getJob()
job.data += packet.getArgument(1)
job.warning = True
self.log.debug("Job warning; handle: %s data: %s" %
(job.handle, job.data))
return job
def handleWorkStatus(self, packet):
"""Handle a WORK_STATUS packet.
@ -506,15 +669,20 @@ class Client(object):
Updates the referenced :py:class:`Job` with the returned data.
:arg Packet packet: The :py:class:`Packet` that was received.
:returns: The :py:class:`Job` object associated with the job request.
:rtype: :py:class:`Job`
"""
job = packet.getJob()
job.numerator = packet.getArgument(1)
job.denominator = packet.getArgument(1)
try:
job.percent_complete = float(job.numerator)/float(job.denominator)
job.fraction_complete = float(job.numerator)/float(job.denominator)
except Exception:
job.percent_complete = None
job.fraction_complete = None
self.log.debug("Job status; handle: %s complete: %s/%s" %
(job.handle, job.numerator, job.denominator))
return job
def handleStatusRes(self, packet):
"""Handle a STATUS_RES packet.
@ -522,6 +690,8 @@ class Client(object):
Updates the referenced :py:class:`Job` with the returned data.
:arg Packet packet: The :py:class:`Packet` that was received.
:returns: The :py:class:`Job` object associated with the job request.
:rtype: :py:class:`Job`
"""
job = packet.getJob()
@ -530,15 +700,63 @@ class Client(object):
job.numerator = packet.getArgument(3)
job.denominator = packet.getArgument(4)
try:
job.percent_complete = float(job.numerator)/float(job.denominator)
job.fraction_complete = float(job.numerator)/float(job.denominator)
except Exception:
job.percent_complete = None
job.fraction_complete = None
return job
class Job(object):
"""A job to run or being run by Gearman.
:arg str name: The name of the job.
:arg str arguments: The opaque data blob to be passed to the worker
as arguments.
:arg str unique: A string to uniquely identify the job to Gearman
(optional).
The following instance attributes are available:
**name** (str)
The name of the job.
**arguments** (str)
The opaque data blob passed to the worker as arguments.
**unique** (str or None)
The unique ID of the job (if supplied).
**handle** (str or None)
The Gearman job handle. None if no job handle has been received yet.
**data** (str)
The result data returned from Gearman. The empty string until
data have been received.
**exception** (str or None)
Exception information returned from Gearman. None if no exception
has been received.
**warning** (bool)
Whether the worker has reported a warning.
**complete** (bool)
Whether the job is complete.
**failure** (bool)
Whether the job has failed. Only set when complete is True.
**numerator** (str or None)
The numerator of the completion ratio reported by the worker.
Only set when a status update is sent by the worker.
**denominator** (str or None)
The denominator of the completion ratio reported by the
worker. Only set when a status update is sent by the worker.
**fraction_complete** (float or None)
The fractional complete ratio reported by the worker. Only set when
a status update is sent by the worker.
**known** (bool or None)
Whether the job is known to Gearman. Only set by handleStatusRes() in
response to a getStatus() query.
**running** (bool or None)
Whether the job is running. Only set by handleStatusRes() in
response to a getStatus() query.
"""
log = logging.getLogger("gear.Job")
def __init__(self, name, arguments, unique):
def __init__(self, name, arguments, unique=None):
self.name = name
self.arguments = arguments
self.unique = unique
@ -550,7 +768,7 @@ class Job(object):
self.failure = False
self.numerator = None
self.denominator = None
self.percent_complete = None
self.fraction_complete = None
self.known = None
self.running = None

View File

@ -12,6 +12,30 @@
# License for the specific language governing permissions and limitations
# under the License.
"""
Protocol Constants
==================
These are not necessary for normal API usage. See the `Gearman
protocol reference <http://gearman.org/protocol>`_ for an explanation
of each of these.
Magic Codes
-----------
.. py:data:: REQ
The Gearman magic code for a request.
.. py:data:: RES
The Gearman magic code for a response.
Packet Types
------------
"""
types = {
1: 'CAN_DO',
2: 'CANT_DO',
@ -53,6 +77,7 @@ types = {
for i, name in types.items():
globals()[name] = i
__doc__ += '\n.. py:data:: %s\n' % name
REQ = '\x00REQ'
RES = '\x00RES'

View File

@ -24,6 +24,11 @@ packages =
setup-hooks =
pbr.hooks.setup_hook
[build_sphinx]
all_files = 1
build-dir = doc/build
source-dir = doc/source
[egg_info]
tag_build =
tag_date = 0