txlongpoll-0.3.1+bzr86.orig/.testr.conf 0000644 0000000 0000000 00000000322 11730141124 016026 0 ustar 0000000 0000000 [DEFAULT]
test_command = bin/testpy -m subunit/run -- discover $LISTOPT $IDOPTION
test_id_option = --load-list $IDFILE
# The "ignore" value below works around a bug in subunit.
test_list_option = --list=ignore
txlongpoll-0.3.1+bzr86.orig/LICENSE 0000644 0000000 0000000 00000104404 11730141124 014753 0 ustar 0000000 0000000 txlongpoll is Copyright 2005-2011 Canonical Ltd.
Canonical Ltd ("Canonical") distributes the txlongpoll source code
under the GNU Affero General Public License, version 3 ("AGPLv3").
The full text of this licence is given below.
Third-party copyright in this distribution is noted where applicable.
All rights not expressly granted are reserved.
=========================================================================
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
(http://www.gnu.org/licenses/agpl.html)
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
.
=========================================================================
txlongpoll-0.3.1+bzr86.orig/MANIFEST.in 0000644 0000000 0000000 00000000065 11730141124 015502 0 ustar 0000000 0000000 graft etc
graft txlongpoll/specs
exclude MANIFEST.in
txlongpoll-0.3.1+bzr86.orig/Makefile 0000644 0000000 0000000 00000003165 11730141124 015410 0 ustar 0000000 0000000 # Copyright 2005-2011 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
PYTHON = python
BOOTSTRAP_BIN := bootstrap.py
BOOTSTRAP = PYTHONPATH= $(PYTHON) $(BOOTSTRAP_BIN)
BUILDOUT_BIN := bin/buildout
BUILDOUT_CFG := buildout.cfg
BUILDOUT = PYTHONPATH= $(BUILDOUT_BIN) -qc $(BUILDOUT_CFG)
default: check
build: bin/twistd
# When a built tree is moved this updates absolute paths.
build-update-paths:
$(BUILDOUT)
check: bin/testpy
bin/testpy -m subunit/run -- discover
dist: $(BUILDOUT_BIN)
$(BUILDOUT) setup setup.py egg_info -r sdist
TAGS: bin/tags
bin/tags --ctags-emacs
tags: bin/tags
bin/tags --ctags-vi
download-cache:
mkdir -p download-cache
eggs:
mkdir -p eggs
$(BUILDOUT_BIN): download-cache eggs
$(BOOTSTRAP) \
--setup-source=download-cache/dist/ez_setup.py \
--download-base=download-cache/dist \
--eggs=eggs --version=1.5.2
touch --no-create $@
bin/twistd: $(BUILDOUT_BIN) $(BUILDOUT_CFG) setup.py
$(BUILDOUT) install runtime
bin/testpy: $(BUILDOUT_BIN) $(BUILDOUT_CFG) setup.py
$(BUILDOUT) install test
bin/tags: $(BUILDOUT_BIN) $(BUILDOUT_CFG) setup.py
$(BUILDOUT) install tags
clean_buildout:
$(RM) -r bin
$(RM) -r parts
$(RM) -r develop-eggs
$(RM) .installed.cfg
$(RM) -r build
$(RM) -r dist
clean_eggs:
$(RM) -r download-cache
$(RM) -r *.egg-info
$(RM) -r eggs
clean: clean_buildout
find txlongpoll twisted -name '*.py[co]' -print0 | xargs -r0 $(RM)
clean_all: clean_buildout clean_eggs
.PHONY: \
build build-update-paths check clean clean_all clean_buildout \
clean_eggs default dist
txlongpoll-0.3.1+bzr86.orig/NEWS 0000644 0000000 0000000 00000001135 11730141124 014442 0 ustar 0000000 0000000 txlongpoll NEWS
+++++++++++++++
Changes and improvements to txlongpoll, grouped by release.
NEXT
----
* OOPS reports can be reported directly over AMQP if the oops-exchange
option is given. The oops-prefix option has been renamed to
oops-reporter to fit in with the long term terminology oops has
adopted. (Robert Collins, Gavin Panella)
* Tests are run with subunit by default, removing the dependency on
Zope's test runner. Support for testrepository has also been
added. (Gavin Panella)
0.3
---
* Allow txlongpoll to take a config file in addition to specifying command
line options.
txlongpoll-0.3.1+bzr86.orig/NOTES 0000644 0000000 0000000 00000017257 11730141124 014572 0 ustar 0000000 0000000 Javascript code in the package?
===============================
12:17:26> jml, should the javascript code reside in the same project btw?
...
therve: I'm not sure. What's the purpose & function of the JS code?
jml, it contains the logic to maintain the long-polling connections
therve: that *sounds* like it would be useful to be in there, but I'm really not informed or familiar enough to make a call. What do you think?
--> smethia (samir@19F698F0.3EE626CE.96F3C2F7.IP) has joined #landscape
<_mup_> landscape/synchronise-licences r2938 committed by kevin@canonical.com
Synchronise now removes unknown licences.
jml, the main concern I have is about running the tests
adding such an infrastructure to a project is painful
therve: ahh, I see.
therve: otoh, being self-contained is pretty useful.
therve: is it a short-term pain / long-term gain thing?
we're going to need some kind of test running infrastructure anyway
kind of. The pain is somewhat there all the time :)
therve: well, yeah, software
jml, therve: the js part is pretty much YUI-integration of the project, in principle there could be a jQuery-integration for it, we can surely put all of them in the same tree, however for the YUI part it'd be nice to have it in the gallery, also for greater exposure to the public
jml, I mean, our current solution in Landscape involves nodejs
it'd be nice to have it in the YUI gallery *too*, that is
free, I'm not sure how generic it is
also the current code is not awesome :)
and depend on the Deferred implementation
therve: I mean, the backend code can run with any js frontend
therve: sure, deferred should be in the gallery btw
therve: what I mean is that what we have works with YUI, but there could be similar code for jQuery, say
yeah, I'm not going to write it though.
therve: essentially I'd like the project to be a way to enable python web up to have notifications and jobs
therve: sure
well, we're YUI anyway
therve: the frontend is somehow orthogonal
s/web up/web apps/.
free, the thing is I don't see what we gain from it being in the gallery, except "it's nice"
therve: some exposure, I'd say, but it can be a sync to the launchpad project, I don't really care
therve: also, uhh, where does the JS code actually *live*?
therve: btw which code specifically it's not awsome?
jml: c.l.javascript.deferred and c.l.javascript.datasource
jml, canonical/landscape/javascript/datasource mainly
free, the datasource code
and, tbh, I'm a bit confused, it sounded like "maybe don't include JS code because it's hard to set up the test infrastructure"
and now you're talking about YUI, jQuery and the gallery
therve: it's not too bad I'd say
jml, the gallery is somewhat a way to delegate the testing outside :)
therve: so, split off more than one component...
therve: that sounds like too much work to do at once.
therve: btw, I was eventually thinking to move that to http://yuilibrary.com/gallery/show/eventsource, that will transparently use EventSource on browsers that have it (Chrome) and fall back to HTTP streaming to the ones that don't (FF), in both cases it should reduce the polling overhead
therve: I mean use Y.EventSource for implementing PageDataSource, and change the server side accordingly, it should be easy
jml, maybe
therve: ok.
therve: basically, I'm no closer to knowing what to do.
thedac therve
jml, sorry
jml: are you at the platform rally?
therve: that's ok. sometimes the world is inherently confusing
free: yes.
jml: I'm coming there tomorrow night, we can discuss about this if you wish
Porting the daemons
===================
async-frontend, job-handler, pingserver
should we move those over?
jml: the tac files?
free: I guess, yes.
jml: async-frontend and joh-handler, yes, pingserver it's Landscape specific
free: async-frontend looks LS specific
free: can you give us a hand de-landscapifying them?
as does job-handler
jml: sure
free: now?
bigjools, jml: they are probably coupled to Landscape, but they shouldn't, in principle
jml: I can have quick look now of what would be needed
jml: but I guess not help doing the actual work
free: thank you. even that would be a good help for us.
jml: just to understand, you are aiming at having the ball rolling as quick as possible?
free: yes.
jml: ok
free: we want something up-and-running end-to-end with a Launchpad page as quickly as possible
jml: so I assume canonical.amqp doesn't import anything from canonical.landscape (or other canonical.xxx modules), I didn't verify though, please check that first
jml: then for the tac files..
jml: job-hanlder imports from canonical.landscape.scripts, the quickest thing to do is probably cut & paste, it might turn out that you don't really need those wrappers and you can go with plain twisted machinery, I'm not sure
free: only crappy stuff c.l.testing.twist
jml: then there's load_config from canonical.landscape.application, that is essentially to load the zcml configuration, for 1) the amqp connection details 2) the db/storm details
jml: if you can go without that, I'm happy, I don't know the details but I suspect it was for working around bugs that were solved (my guess)
free: what about all the env vars & literals?
jml: where?
jml: oh
jml: that's for choosing the config file to load
jml: if you're not in such a terrible rush and have some time, it'd be good to go with a config mechanism that doesn't require zcml, things will be simpler
free: +1
jml: it should probably have a hook to load application-specific configuration in the job-handler process, like the db connections
jml: that's all is needed I think
jml: an .ini file would be enough for the AMQP broker connection
free: what about the literal 'landscape' passed to JobHandler?
jml, that's a prefix for the queue names iirc
jml: that should be configurable, it's just the prefix
jml: what sidnei says
ok, thanks.
jml: the other bit is from canonical.landscape.model.job.registry import get_handlers
jml: if we had time that'd deserve more care
jml: because lots of that has grown to be general enough to be extracted and included in the standalone project, I believe
free: that'd be cool.
jml: but you can also go without it for now
jml: I've been meaning to do that for a while, fwiw
free: once we've got the standalone project, I reckon it'll be to both projects' benefits to factor stuff into it
free: but, let's get it working first
jml: JobHandler(threadpool, get_handlers(), "landscape"), the get_handlers() just gets you a dictionary of job names to callables
jml: sure
jml: look at canonical.amqp.job.handler line 80 and after
sidnei: is txstatsd a case where we will have our own trunk (landscape's) and upstream?
jml: a dictionary of job names to callables is bare minimum required, but in practice you want to have some base Job class, so we should offer that facility, maybe as optional
jml: also we'd like the ability to aggregate jobs so, a JobSet would be nice too
jml: that's all for the future, you can get the ball rolling using the handlers dictionary, I'd say
free: rockin'. thanks.
jml: I think that's all for the job handler
jml: for async-frontend the same applies, it's probably even simpler
jml: it doesn't even need authentication, as it's implicit in the page_key concept (if you read the spec)
txlongpoll-0.3.1+bzr86.orig/README 0000644 0000000 0000000 00000002706 11730141124 014630 0 ustar 0000000 0000000 Generic long poll server used by Launchpad and Landscape.
Dependencies
------------
By default txlongpoll attempts to build without going to the network;
instead it tries to find all dependencies from download-cache/dist,
and you must download all the dependencies yourself.
If you prefer to use resources from the 'net, PyPI for example, then:
- Remove the --setup-source and --download-base options in Makefile to
allow bootstrap.py to download setuptools.
- Comment out the ``install-from-cache = true`` line in buildout.cfg
to allow bin/buildout to download dependencies.
To run the tests you may also need lp:rabbitfixture (bzr branch
lp:rabbitfixture). Build an sdist tarball and drop it into
download-cache/dist. You may also need to do the same for
testresources-0.2.4_r58 until it reaches PyPI.
txlongpoll needs a recent RabbitMQ with support for rejection. Maverick's
1.8.0 is not sufficient, but 2.1.1 works fine, so >= Natty is OK.
Building
--------
$ make build
will build only those parts needed to run txlongpoll. No support for
tags or testing.
Testing
-------
$ make check
will build all the test-related parts of txlongpoll and then do a full
test run, but
$ make bin/test
will just do the first part.
There is testrepository
support, so you can also do the following:
$ testr init
$ testr run
This is probably the best way to develop txlongpoll.
Running
-------
$ bin/twistd txlongpoll
txlongpoll-0.3.1+bzr86.orig/bootstrap.py 0000644 0000000 0000000 00000023522 11730141124 016336 0 ustar 0000000 0000000 ##############################################################################
#
# Copyright (c) 2006 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Bootstrap a buildout-based project
Simply run this script in a directory containing a buildout.cfg.
The script accepts buildout command-line options, so you can
use the -c option to specify an alternate configuration file.
"""
import os, shutil, sys, tempfile, textwrap, urllib, urllib2, subprocess
from optparse import OptionParser
if sys.platform == 'win32':
def quote(c):
if ' ' in c:
return '"%s"' % c # work around spawn lamosity on windows
else:
return c
else:
quote = str
# See zc.buildout.easy_install._has_broken_dash_S for motivation and comments.
stdout, stderr = subprocess.Popen(
[sys.executable, '-Sc',
'try:\n'
' import ConfigParser\n'
'except ImportError:\n'
' print 1\n'
'else:\n'
' print 0\n'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
has_broken_dash_S = bool(int(stdout.strip()))
# In order to be more robust in the face of system Pythons, we want to
# run without site-packages loaded. This is somewhat tricky, in
# particular because Python 2.6's distutils imports site, so starting
# with the -S flag is not sufficient. However, we'll start with that:
if not has_broken_dash_S and 'site' in sys.modules:
# We will restart with python -S.
args = sys.argv[:]
args[0:0] = [sys.executable, '-S']
args = map(quote, args)
os.execv(sys.executable, args)
# Now we are running with -S. We'll get the clean sys.path, import site
# because distutils will do it later, and then reset the path and clean
# out any namespace packages from site-packages that might have been
# loaded by .pth files.
clean_path = sys.path[:]
import site
sys.path[:] = clean_path
for k, v in sys.modules.items():
if k in ('setuptools', 'pkg_resources') or (
hasattr(v, '__path__') and
len(v.__path__)==1 and
not os.path.exists(os.path.join(v.__path__[0],'__init__.py'))):
# This is a namespace package. Remove it.
sys.modules.pop(k)
is_jython = sys.platform.startswith('java')
setuptools_source = 'http://peak.telecommunity.com/dist/ez_setup.py'
distribute_source = 'http://python-distribute.org/distribute_setup.py'
# parsing arguments
def normalize_to_url(option, opt_str, value, parser):
if value:
if '://' not in value: # It doesn't smell like a URL.
value = 'file://%s' % (
urllib.pathname2url(
os.path.abspath(os.path.expanduser(value))),)
if opt_str == '--download-base' and not value.endswith('/'):
# Download base needs a trailing slash to make the world happy.
value += '/'
else:
value = None
name = opt_str[2:].replace('-', '_')
setattr(parser.values, name, value)
usage = '''\
[DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options]
Bootstraps a buildout-based project.
Simply run this script in a directory containing a buildout.cfg, using the
Python that you want bin/buildout to use.
Note that by using --setup-source and --download-base to point to
local resources, you can keep this script from going over the network.
'''
parser = OptionParser(usage=usage)
parser.add_option("-v", "--version", dest="version",
help="use a specific zc.buildout version")
parser.add_option("-d", "--distribute",
action="store_true", dest="use_distribute", default=False,
help="Use Distribute rather than Setuptools.")
parser.add_option("--setup-source", action="callback", dest="setup_source",
callback=normalize_to_url, nargs=1, type="string",
help=("Specify a URL or file location for the setup file. "
"If you use Setuptools, this will default to " +
setuptools_source + "; if you use Distribute, this "
"will default to " + distribute_source +"."))
parser.add_option("--download-base", action="callback", dest="download_base",
callback=normalize_to_url, nargs=1, type="string",
help=("Specify a URL or directory for downloading "
"zc.buildout and either Setuptools or Distribute. "
"Defaults to PyPI."))
parser.add_option("--eggs",
help=("Specify a directory for storing eggs. Defaults to "
"a temporary directory that is deleted when the "
"bootstrap script completes."))
parser.add_option("-t", "--accept-buildout-test-releases",
dest='accept_buildout_test_releases',
action="store_true", default=False,
help=("Normally, if you do not specify a --version, the "
"bootstrap script and buildout gets the newest "
"*final* versions of zc.buildout and its recipes and "
"extensions for you. If you use this flag, "
"bootstrap and buildout will get the newest releases "
"even if they are alphas or betas."))
parser.add_option("-c", None, action="store", dest="config_file",
help=("Specify the path to the buildout configuration "
"file to be used."))
options, args = parser.parse_args()
# if -c was provided, we push it back into args for buildout's main function
if options.config_file is not None:
args += ['-c', options.config_file]
if options.eggs:
eggs_dir = os.path.abspath(os.path.expanduser(options.eggs))
else:
eggs_dir = tempfile.mkdtemp()
if options.setup_source is None:
if options.use_distribute:
options.setup_source = distribute_source
else:
options.setup_source = setuptools_source
if options.accept_buildout_test_releases:
args.append('buildout:accept-buildout-test-releases=true')
args.append('bootstrap')
try:
import pkg_resources
import setuptools # A flag. Sometimes pkg_resources is installed alone.
if not hasattr(pkg_resources, '_distribute'):
raise ImportError
except ImportError:
ez_code = urllib2.urlopen(
options.setup_source).read().replace('\r\n', '\n')
ez = {}
exec ez_code in ez
setup_args = dict(to_dir=eggs_dir, download_delay=0)
if options.download_base:
setup_args['download_base'] = options.download_base
if options.use_distribute:
setup_args['no_fake'] = True
ez['use_setuptools'](**setup_args)
if 'pkg_resources' in sys.modules:
reload(sys.modules['pkg_resources'])
import pkg_resources
# This does not (always?) update the default working set. We will
# do it.
for path in sys.path:
if path not in pkg_resources.working_set.entries:
pkg_resources.working_set.add_entry(path)
cmd = [quote(sys.executable),
'-c',
quote('from setuptools.command.easy_install import main; main()'),
'-mqNxd',
quote(eggs_dir)]
if not has_broken_dash_S:
cmd.insert(1, '-S')
find_links = options.download_base
if not find_links:
find_links = os.environ.get('bootstrap-testing-find-links')
if find_links:
cmd.extend(['-f', quote(find_links)])
if options.use_distribute:
setup_requirement = 'distribute'
else:
setup_requirement = 'setuptools'
ws = pkg_resources.working_set
setup_requirement_path = ws.find(
pkg_resources.Requirement.parse(setup_requirement)).location
env = dict(
os.environ,
PYTHONPATH=setup_requirement_path)
requirement = 'zc.buildout'
version = options.version
if version is None and not options.accept_buildout_test_releases:
# Figure out the most recent final version of zc.buildout.
import setuptools.package_index
_final_parts = '*final-', '*final'
def _final_version(parsed_version):
for part in parsed_version:
if (part[:1] == '*') and (part not in _final_parts):
return False
return True
index = setuptools.package_index.PackageIndex(
search_path=[setup_requirement_path])
if find_links:
index.add_find_links((find_links,))
req = pkg_resources.Requirement.parse(requirement)
if index.obtain(req) is not None:
best = []
bestv = None
for dist in index[req.project_name]:
distv = dist.parsed_version
if _final_version(distv):
if bestv is None or distv > bestv:
best = [dist]
bestv = distv
elif distv == bestv:
best.append(dist)
if best:
best.sort()
version = best[-1].version
if version:
requirement = '=='.join((requirement, version))
cmd.append(requirement)
if is_jython:
import subprocess
exitcode = subprocess.Popen(cmd, env=env).wait()
else: # Windows prefers this, apparently; otherwise we would prefer subprocess
exitcode = os.spawnle(*([os.P_WAIT, sys.executable] + cmd + [env]))
if exitcode != 0:
sys.stdout.flush()
sys.stderr.flush()
print ("An error occurred when trying to install zc.buildout. "
"Look above this message for any errors that "
"were output by easy_install.")
sys.exit(exitcode)
ws.add_entry(eggs_dir)
ws.require(requirement)
import zc.buildout.buildout
zc.buildout.buildout.main(args)
if not options.eggs: # clean up temporary egg directory
shutil.rmtree(eggs_dir)
txlongpoll-0.3.1+bzr86.orig/buildout.cfg 0000644 0000000 0000000 00000001627 11730141124 016261 0 ustar 0000000 0000000 # Copyright 2005-2011 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
[buildout]
parts = runtime
use-dependency-links = false
unzip = true
include-site-packages = false
allowed-eggs-from-site-packages = pyyaml
exec-sitecustomize = true
develop = .
download-cache = download-cache
eggs-directory = eggs
# Relative paths are useful when deploying built trees.
relative-paths = true
# Disable this option temporarily if you want buildout to find
# software dependencies *other* than those in our download-cache.
# Once you have the desired software, reenable this option.
install-from-cache = true
[runtime]
recipe = zc.recipe.egg:scripts
eggs = txlongpoll
entry-points = twistd=twisted.scripts.twistd:run
[test]
recipe = zc.recipe.egg:scripts
eggs = txlongpoll [test]
interpreter = testpy
[tags]
recipe = z3c.recipe.tag:tags
eggs = txlongpoll
txlongpoll-0.3.1+bzr86.orig/etc/ 0000755 0000000 0000000 00000000000 11730141124 014516 5 ustar 0000000 0000000 txlongpoll-0.3.1+bzr86.orig/setup.py 0000755 0000000 0000000 00000001646 11730141124 015467 0 ustar 0000000 0000000 #!/usr/bin/env python
# Copyright 2005-2011 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
"""Distutils installer for txlongpoll."""
from setuptools import (
find_packages,
setup,
)
setup(
name='txlongpoll',
version="0.3.1",
packages=find_packages('.') + ['twisted.plugins'],
include_package_data=True,
zip_safe=False,
description='Long polling HTTP frontend for AMQP',
install_requires=[
'formencode',
'oops_amqp',
'oops_datedir_repo >= 0.0.13',
'oops_twisted >= 0.0.3',
'pyyaml',
'Twisted',
'txAMQP >= 0.5',
'zope.interface',
],
extras_require=dict(
test=[
'rabbitfixture',
'testresources >= 0.2.4_r58',
'testtools',
# 'subunit', # Not easy-installable.
],
))
txlongpoll-0.3.1+bzr86.orig/test 0000755 0000000 0000000 00000000115 11730141124 014645 0 ustar 0000000 0000000 #!/usr/bin/env bash
exec "$(dirname "$0")/bin/testpy" -m subunit/run -- "$@"
txlongpoll-0.3.1+bzr86.orig/twisted/ 0000755 0000000 0000000 00000000000 11730141124 015426 5 ustar 0000000 0000000 txlongpoll-0.3.1+bzr86.orig/txlongpoll/ 0000755 0000000 0000000 00000000000 11730141124 016145 5 ustar 0000000 0000000 txlongpoll-0.3.1+bzr86.orig/etc/txlongpoll.yaml 0000644 0000000 0000000 00000001172 11730141124 017605 0 ustar 0000000 0000000 ##
## txlongpoll configuration.
##
## The front-end service.
#
frontend:
## The port on which to serve.
port: 56100
## If specified, queue names requested must have the given prefix.
# prefix:
## OOPS configuration.
#
oops:
## Directory in which to place OOPS reports.
# directory: ""
## The reporter used when generating OOPS reports.
# reporter: "LONGPOLL"
## Message broker configuration.
#
broker:
# host: "localhost"
# port: 5672
# username: "guest"
# password: "guest"
# vhost: "/"
## Where to log. This log can be rotated by sending SIGUSR1 to the
## running server.
#
# logfile: "txlongpoll.log"
txlongpoll-0.3.1+bzr86.orig/twisted/plugins/ 0000755 0000000 0000000 00000000000 11730141124 017107 5 ustar 0000000 0000000 txlongpoll-0.3.1+bzr86.orig/twisted/plugins/txlongpoll.py 0000644 0000000 0000000 00000001314 11730141124 021662 0 ustar 0000000 0000000 # Copyright 2005-2011 Canonical Ltd. This software is licensed under
# the GNU Affero General Public License version 3 (see the file LICENSE).
from __future__ import absolute_import
from txlongpoll.plugin import AMQServiceMaker
# Construct objects which *provide* the relevant interfaces. The name of
# these variables is irrelevant, as long as there are *some* names bound to
# providers of IPlugin and IServiceMaker.
service_amqp_longpoll = AMQServiceMaker(
"amqp-longpoll", "An AMQP -> HTTP long-poll bridge. *Note* that "
"the `amqp-longpoll' name is deprecated; please use `txlongpoll' "
"instead.")
service_txlongpoll = AMQServiceMaker(
"txlongpoll", "An AMQP -> HTTP long-poll bridge.")
txlongpoll-0.3.1+bzr86.orig/txlongpoll/__init__.py 0000644 0000000 0000000 00000000220 11730141124 020250 0 ustar 0000000 0000000 # Copyright 2005-2011 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
txlongpoll-0.3.1+bzr86.orig/txlongpoll/client.py 0000644 0000000 0000000 00000007613 11730141124 020004 0 ustar 0000000 0000000 # Copyright 2005-2011 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
"""
Asynchronous client for AMQP using txAMQP.
"""
import os.path
from twisted.internet.defer import maybeDeferred
from twisted.internet.protocol import ReconnectingClientFactory
from txamqp.client import TwistedDelegate
from txamqp.protocol import AMQClient
from txamqp.queue import Closed
from txamqp.spec import load as load_spec
class AMQClientWithCallback(AMQClient):
"""
An C{AMQClient} that notifies connections with a callback.
@ivar connected_callback: callback called when C{connectionMade} is
called. It takes one argument, the protocol instance itself.
"""
def __init__(self, connected_callback, *args, **kwargs):
AMQClient.__init__(self, *args, **kwargs)
self.connected_callback = connected_callback
def connectionMade(self):
AMQClient.connectionMade(self)
self.connected_callback(self)
_base_dir = os.path.dirname(os.path.abspath(__file__))
AMQP0_8_SPEC = load_spec(os.path.join(_base_dir, "specs", "amqp0-8.xml"))
del _base_dir
class AMQFactory(ReconnectingClientFactory):
"""
A C{ClientFactory} for C{AMQClient} protocol with reconnecting facilities.
@ivar user: the user name to use to connect to the AMQP server.
@ivar password: the corresponding password of the user.
@ivar vhost: the AMQP vhost to create connections against.
@ivar connected_callback: callback called when a successful connection
happened. It takes one argument, the channel opened for the connection.
@ivar disconnected_callback: callback called when a previously connected
connection was lost. It takes no argument.
"""
protocol = AMQClientWithCallback
initialDelay = 0.01
def __init__(self, user, password, vhost, connected_callback,
disconnected_callback, failed_callback, spec=None):
self.user = user
self.password = password
self.vhost = vhost
self.delegate = TwistedDelegate()
if spec is None:
spec = AMQP0_8_SPEC
self.spec = spec
self.connected_callback = connected_callback
self.disconnected_callback = disconnected_callback
self.failed_callback = failed_callback
def buildProtocol(self, addr):
"""
Create the protocol instance and returns it for letting Twisted
connect it to the transport.
@param addr: the attributed address, unused for now.
"""
protocol = self.protocol(self.clientConnectionMade, self.delegate,
self.vhost, spec=self.spec)
protocol.factory = self
return protocol
def clientConnectionMade(self, client):
"""
Called when a connection succeeds: login to the server, and open a
channel against it.
"""
self.resetDelay()
def started(ignored):
# We don't care about authenticate result as long as it succeeds
return client.channel(1).addCallback(got_channel)
def got_channel(channel):
return channel.channel_open().addCallback(opened, channel)
def opened(ignored, channel):
deferred = maybeDeferred(
self.connected_callback, (client, channel))
deferred.addErrback(catch_closed)
def catch_closed(failure):
failure.trap(Closed)
deferred = client.authenticate(self.user, self.password)
return deferred.addCallback(started)
def clientConnectionLost(self, connector, reason):
ReconnectingClientFactory.clientConnectionLost(self, connector, reason)
self.disconnected_callback()
def clientConnectionFailed(self, connector, reason):
ReconnectingClientFactory.clientConnectionFailed(
self, connector, reason)
self.failed_callback((connector, reason))
txlongpoll-0.3.1+bzr86.orig/txlongpoll/frontend.py 0000644 0000000 0000000 00000022535 11730141124 020345 0 ustar 0000000 0000000 # Copyright 2005-2011 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
"""
Async frontend server for serving answers from background processor.
"""
import json
from twisted.internet.defer import (
Deferred,
inlineCallbacks,
returnValue,
)
from twisted.python import log
from twisted.web.http import (
BAD_REQUEST,
INTERNAL_SERVER_ERROR,
NOT_FOUND,
REQUEST_TIMEOUT,
)
from twisted.web.resource import Resource
from twisted.web.server import NOT_DONE_YET
from txamqp.client import Closed
from txamqp.queue import (
Closed as QueueClosed,
Empty,
)
__all__ = ["QueueManager", "FrontEndAjax"]
class NotFound(Exception):
"""Exception raised when a queue is not found in the message server."""
class QueueManager(object):
"""
An AMQP consumer which handles messages sent over a "frontend" queue to
set up temporary queues. The L{get_message} method should be invoked to
retrieve one single message from those temporary queues.
@ivar message_timeout: time to wait for a message before giving up in
C{get_message}.
@ivar _channel: reference to the current C{AMQChannel}.
@ivar _client: reference to the current C{AMQClient}.
"""
# The timeout must be lower than the Apache one in front, which by default
# is 5 minutes.
message_timeout = 270
def __init__(self, prefix=None):
self._prefix = prefix
self._channel = None
self._client = None
self._pending_requests = []
# Preserve compatibility by using special forms for naming when a
# prefix is specified.
if self._prefix is not None and len(self._prefix) != 0:
self._tag_form = "%s.notifications-tag.%%s.%%s" % self._prefix
self._queue_form = "%s.notifications-queue.%%s" % self._prefix
else:
self._tag_form = "%s.%s"
self._queue_form = "%s"
def disconnected(self):
"""
Called when losing the connection to broker: cancel all pending calls,
reinitialize variables.
"""
self._channel = None
self._client = None
def connected(self, (client, channel)):
"""
This method should be used as the C{connected_callback} parameter to
L{AMQFactory}.
"""
log.msg("Async frontend connected to AMQP broker")
self._client = client
self._channel = channel
# Make sure we only get one message at a time, to make load balancing
# work.
d = channel.basic_qos(prefetch_count=1)
while self._pending_requests:
self._pending_requests.pop(0).callback(None)
return d
def _wait_for_connection(self):
"""
Return a L{Deferred} which will fire when the connection is available.
"""
pending = Deferred()
self._pending_requests.append(pending)
return pending
@inlineCallbacks
def get_message(self, uuid, sequence):
"""Consume and return one message for C{uuid}.
@param uuid: The identifier of the queue.
@param sequence: The sequential number for identifying the subscriber
in the queue.
If no message is received within the number of seconds in
L{message_timeout}, then the returned Deferred will errback with
L{Empty}.
"""
if self._channel is None:
yield self._wait_for_connection()
tag = self._tag_form % (uuid, sequence)
try:
yield self._channel.basic_consume(
consumer_tag=tag, queue=(self._queue_form % uuid))
log.msg("Consuming from queue '%s'" % uuid)
queue = yield self._client.queue(tag)
msg = yield queue.get(self.message_timeout)
except Empty:
# Let's wait for the cancel here
yield self._channel.basic_cancel(consumer_tag=tag)
self._client.queues.pop(tag, None)
# Check for the messages arrived in the mean time
if queue.pending:
msg = queue.pending.pop()
returnValue((msg.content.body, msg.delivery_tag))
raise Empty()
except QueueClosed:
# The queue has been closed, presumably because of a side effect.
# Let's retry after reconnection.
yield self._wait_for_connection()
data = yield self.get_message(uuid, sequence)
returnValue(data)
except Closed, e:
if self._client and self._client.transport:
self._client.transport.loseConnection()
if e.args and e.args[0].reply_code == 404:
raise NotFound()
else:
raise
except:
if self._client and self._client.transport:
self._client.transport.loseConnection()
raise
yield self._channel.basic_cancel(consumer_tag=tag, nowait=True)
self._client.queues.pop(tag, None)
returnValue((msg.content.body, msg.delivery_tag))
def reject_message(self, tag):
"""Put back a message."""
return self._channel.basic_reject(tag, requeue=True)
def ack_message(self, tag):
"""Confirm the reading of a message)."""
return self._channel.basic_ack(tag)
@inlineCallbacks
def cancel_get_message(self, uuid, sequence):
"""
Cancel a previous C{get_message} when a request is done, to be able to
reuse the tag properly.
@param uuid: The identifier of the queue.
@param sequence: The sequential number for identifying the subscriber
in the queue.
"""
if self._client is not None:
tag = self._tag_form % (uuid, sequence)
queue = yield self._client.queue(tag)
queue.put(Empty)
class FrontEndAjax(Resource):
"""
A web resource which, when rendered with a C{'uuid'} in the request
arguments, will return the raw data from the message queue associated with
that UUID.
"""
isLeaf = True
def __init__(self, message_queue):
Resource.__init__(self)
self.message_queue = message_queue
self._finished = {}
def render(self, request):
"""Render the request.
It expects a page key (the UUID), and a sequence number indicated how
many times this key has been used, and use the page key to retrieve
messages from the associated queue.
"""
if "uuid" not in request.args and "sequence" not in request.args:
request.setHeader("Content-Type", "text/plain")
return "Async frontend for %s" % self.message_queue._prefix
if "uuid" not in request.args or "sequence" not in request.args:
request.setHeader("Content-Type", "text/plain")
request.setResponseCode(BAD_REQUEST)
return "Invalid request"
uuid = request.args["uuid"][0]
sequence = request.args["sequence"][0]
if not uuid or not sequence:
request.setHeader("Content-Type", "text/plain")
request.setResponseCode(BAD_REQUEST)
return "Invalid request"
request_id = "%s-%s" % (uuid, sequence)
def _finished(ignored):
if request_id in self._finished:
# If the request_id is already in finished, that means the
# request terminated properly. We remove it from finished to
# prevent from it growing indefinitely.
self._finished.pop(request_id)
else:
# Otherwise, put it in finished so that the message is not sent
# when write is called.
self._finished[request_id] = True
self.message_queue.cancel_get_message(uuid, sequence)
request.notifyFinish().addBoth(_finished)
d = self.message_queue.get_message(uuid, sequence)
def write(data):
result, tag = data
if self._finished.get(request_id):
self._finished.pop(request_id)
self.message_queue.reject_message(tag)
return
self.message_queue.ack_message(tag)
data = json.loads(result)
if data.pop("original-uuid", None) == uuid:
# Ignore the message for the page who emitted the job
d = self.message_queue.get_message(uuid, sequence)
d.addCallback(write)
d.addErrback(failed)
return
if "error" in data:
request.setResponseCode(BAD_REQUEST)
request.setHeader("Content-Type", "application/json")
request.write(result)
self._finished[request_id] = False
request.finish()
def failed(error):
if self._finished.get(request_id):
self._finished.pop(request_id)
return
if error.check(Empty):
request.setResponseCode(REQUEST_TIMEOUT)
elif error.check(NotFound):
request.setResponseCode(NOT_FOUND)
else:
log.err(error, "Failed to get message")
request.setResponseCode(INTERNAL_SERVER_ERROR)
request.write(str(error.value))
self._finished[request_id] = False
request.finish()
d.addCallback(write)
d.addErrback(failed)
return NOT_DONE_YET
txlongpoll-0.3.1+bzr86.orig/txlongpoll/plugin.py 0000644 0000000 0000000 00000011334 11730141124 020017 0 ustar 0000000 0000000 # Copyright 2005-2011 Canonical Ltd. This software is licensed under
# the GNU Affero General Public License version 3 (see the file LICENSE).
from __future__ import (
print_function,
unicode_literals,
)
__all__ = [
"AMQServiceMaker",
]
from formencode import Schema
from formencode.api import set_stdtranslation
from formencode.validators import (
Int,
RequireIfPresent,
String,
)
from twisted.application.internet import (
TCPClient,
TCPServer,
)
from twisted.application.service import (
IServiceMaker,
MultiService,
)
from twisted.plugin import IPlugin
from twisted.python import (
log,
usage,
)
from twisted.web.server import Site
from txlongpoll.client import AMQFactory
from txlongpoll.frontend import (
FrontEndAjax,
QueueManager,
)
from txlongpoll.services import (
LogService,
OOPSService,
)
import yaml
from zope.interface import implements
# Ensure that formencode does not translate strings; there are encoding issues
# that are easier to side-step for now.
set_stdtranslation(languages=[])
class ConfigOops(Schema):
"""Configuration validator for OOPS options."""
if_key_missing = None
directory = String(if_missing=b"")
reporter = String(if_missing=b"LONGPOLL")
chained_validators = (
RequireIfPresent("reporter", present="directory"),
)
class ConfigBroker(Schema):
"""Configuration validator for message broker options."""
if_key_missing = None
host = String(if_missing=b"localhost")
port = Int(min=1, max=65535, if_missing=5672)
username = String(if_missing=b"guest")
password = String(if_missing=b"guest")
vhost = String(if_missing="/")
class ConfigFrontend(Schema):
"""Configuration validator for the front-end service."""
if_key_missing = None
port = Int(min=1, max=65535, if_missing=8001)
prefix = String(if_missing=None)
class Config(Schema):
"""Configuration validator."""
if_key_missing = None
oops = ConfigOops
broker = ConfigBroker
frontend = ConfigFrontend
logfile = String(
if_empty=b"txlongpoll.log",
if_missing=b"txlongpoll.log")
@classmethod
def parse(cls, stream):
"""Load a YAML configuration from `stream` and validate."""
return cls.to_python(yaml.load(stream))
@classmethod
def load(cls, filename):
"""Load a YAML configuration from `filename` and validate."""
with open(filename, "rb") as stream:
return cls.parse(stream)
class Options(usage.Options):
optParameters = [
["config-file", "c", "etc/txlongpoll.yaml",
"Configuration file to load."],
]
class AMQServiceMaker(object):
"""Create an asynchronous frontend server for AMQP."""
implements(IServiceMaker, IPlugin)
options = Options
def __init__(self, name, description):
self.tapname = name
self.description = description
def makeService(self, options):
"""Construct a service."""
services = MultiService()
config_file = options["config-file"]
config = Config.load(config_file)
log_service = LogService(config["logfile"])
log_service.setServiceParent(services)
oops_config = config["oops"]
oops_dir = oops_config["directory"]
oops_reporter = oops_config["reporter"]
oops_service = OOPSService(log_service, oops_dir, oops_reporter)
oops_service.setServiceParent(services)
frontend_config = config["frontend"]
frontend_port = frontend_config["port"]
frontend_prefix = frontend_config["prefix"]
frontend_manager = QueueManager(frontend_prefix)
broker_config = config["broker"]
broker_port = broker_config["port"]
broker_host = broker_config["host"]
broker_username = broker_config["username"]
broker_password = broker_config["password"]
broker_vhost = broker_config["vhost"]
cb_connected = frontend_manager.connected
cb_disconnected = frontend_manager.disconnected
cb_failed = lambda connector_and_reason: (
log.err(connector_and_reason[1], "Connection failed"))
client_factory = AMQFactory(
broker_username, broker_password, broker_vhost,
cb_connected, cb_disconnected, cb_failed)
client_service = TCPClient(
broker_host, broker_port, client_factory)
client_service.setName("amqp")
client_service.setServiceParent(services)
frontend_resource = FrontEndAjax(frontend_manager)
frontend_service = TCPServer(frontend_port, Site(frontend_resource))
frontend_service.setName("frontend")
frontend_service.setServiceParent(services)
return services
txlongpoll-0.3.1+bzr86.orig/txlongpoll/services.py 0000644 0000000 0000000 00000005722 11730141124 020350 0 ustar 0000000 0000000 # Copyright 2012 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
"""Additional services that compose txlongpoll."""
from __future__ import (
print_function,
unicode_literals,
)
__metaclass__ = type
__all__ = [
"LogService",
"OOPSService",
]
import signal
import sys
import oops
from oops_datedir_repo import DateDirRepo
from oops_twisted import (
Config as oops_config,
defer_publisher,
OOPSObserver,
)
from twisted.application.service import Service
from twisted.internet import reactor
from twisted.python.log import (
addObserver,
FileLogObserver,
removeObserver,
)
from twisted.python.logfile import LogFile
class LogService(Service):
name = "log"
def __init__(self, filename):
self.filename = filename
self.logfile = None
self.observer = None
def _signal_handler(self, sig, frame):
reactor.callFromThread(self.logfile.reopen)
def startService(self):
Service.startService(self)
if self.filename != '-':
self.logfile = LogFile.fromFullPath(
self.filename, rotateLength=None, defaultMode=0o644)
self.__previous_signal_handler = signal.signal(
signal.SIGUSR1, self._signal_handler)
else:
self.logfile = sys.stdout
self.observer = FileLogObserver(self.logfile)
self.observer.start()
def stopService(self):
Service.stopService(self)
if self.filename != '-':
signal.signal(signal.SIGUSR1, self.__previous_signal_handler)
del self.__previous_signal_handler
self.observer.stop()
self.observer = None
self.logfile.close()
self.logfile = None
else:
self.observer.stop()
self.observer = None
# Don't close stdout.
self.logfile = None
class OOPSService(Service):
name = "oops"
def __init__(self, log_service, oops_dir, oops_reporter):
self.config = None
self.log_service = log_service
self.oops_dir = oops_dir
self.oops_reporter = oops_reporter
def startService(self):
Service.startService(self)
self.config = oops_config()
# Add the oops publisher that writes files in the configured place if
# the command line option was set.
if self.oops_dir:
repo = DateDirRepo(self.oops_dir)
self.config.publishers.append(
defer_publisher(oops.publish_new_only(repo.publish)))
if self.oops_reporter:
self.config.template['reporter'] = self.oops_reporter
self.observer = OOPSObserver(
self.config, self.log_service.observer.emit)
addObserver(self.observer.emit)
def stopService(self):
Service.stopService(self)
removeObserver(self.observer.emit)
self.observer = None
self.config = None
txlongpoll-0.3.1+bzr86.orig/txlongpoll/specs/ 0000755 0000000 0000000 00000000000 11730141124 017262 5 ustar 0000000 0000000 txlongpoll-0.3.1+bzr86.orig/txlongpoll/testing/ 0000755 0000000 0000000 00000000000 11730141124 017622 5 ustar 0000000 0000000 txlongpoll-0.3.1+bzr86.orig/txlongpoll/tests/ 0000755 0000000 0000000 00000000000 11730141124 017307 5 ustar 0000000 0000000 txlongpoll-0.3.1+bzr86.orig/txlongpoll/specs/amqp0-8.xml 0000644 0000000 0000000 00000076472 11730141124 021207 0 ustar 0000000 0000000
txlongpoll-0.3.1+bzr86.orig/txlongpoll/testing/__init__.py 0000644 0000000 0000000 00000000220 11730141124 021725 0 ustar 0000000 0000000 # Copyright 2005-2011 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
txlongpoll-0.3.1+bzr86.orig/txlongpoll/testing/client.py 0000644 0000000 0000000 00000011377 11730141124 021463 0 ustar 0000000 0000000 # Copyright 2005-2011 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
from rabbitfixture.server import RabbitServer
from testresources import (
FixtureResource,
ResourcedTestCase,
)
from testtools import TestCase
from testtools.deferredruntest import (
AsynchronousDeferredRunTestForBrokenTwisted,
)
from twisted.internet import reactor
from twisted.internet.defer import (
Deferred,
DeferredQueue,
inlineCallbacks,
)
from txamqp.client import Closed
from txlongpoll.client import AMQFactory
class QueueWrapper(object):
"""
Wrap a queue to have notifications when get is called on this particular
queue.
"""
def __init__(self, queue):
self._real_queue_get = queue.get
self.event_queue = DeferredQueue()
queue.get = self.get
def get(self, timeout=None):
self.event_queue.put(None)
return self._real_queue_get(timeout)
class AMQTest(ResourcedTestCase, TestCase):
run_tests_with = AsynchronousDeferredRunTestForBrokenTwisted.make_factory(
timeout=5)
resources = [('rabbit', FixtureResource(RabbitServer()))]
VHOST = "/"
USER = "guest"
PASSWORD = "guest"
def setUp(self):
"""
At each run, we delete the test vhost and recreate it, to be sure to be
in a clean environment.
"""
super(AMQTest, self).setUp()
self.queues = set()
self.exchanges = set()
self.connected_deferred = Deferred()
self.factory = AMQFactory(self.USER, self.PASSWORD, self.VHOST,
self.amq_connected, self.amq_disconnected, self.amq_failed)
self.factory.initialDelay = 2.0
self.connector = reactor.connectTCP(
self.rabbit.config.hostname, self.rabbit.config.port,
self.factory)
return self.connected_deferred
@inlineCallbacks
def tearDown(self):
# XXX: Moving this up here to silence a nigh-on inexplicable error
# that occurs when it's at the bottom of the function.
self.factory.stopTrying()
self.connector.disconnect()
super(AMQTest, self).tearDown()
# XXX: This is only safe because we tear down the whole server.
# We can't run this after the tearDown above, because the
# fixture is gone.
return
self.connected_deferred = Deferred()
factory = AMQFactory(self.USER, self.PASSWORD, self.VHOST,
self.amq_connected, self.amq_disconnected, self.amq_failed)
connector = reactor.connectTCP(
self.rabbit.config.hostname, self.rabbit.config.port, factory)
yield self.connected_deferred
channel_id = 1
for queue in self.queues:
try:
yield self.channel.queue_delete(queue=queue)
except Closed:
channel_id += 1
self.channel = yield self.client.channel(channel_id)
yield self.channel.channel_open()
for exchange in self.exchanges:
try:
yield self.channel.exchange_delete(exchange=exchange)
except Closed:
channel_id += 1
self.channel = yield self.client.channel(channel_id)
yield self.channel.channel_open()
factory.stopTrying()
connector.disconnect()
def amq_connected(self, (client, channel)):
"""
Save the channel and client, and fire C{self.connected_deferred}.
This is the connected_callback that's pased to the L{AMQFactory}.
"""
self.real_queue_declare = channel.queue_declare
channel.queue_declare = self.queue_declare
self.real_exchange_declare = channel.exchange_declare
channel.exchange_declare = self.exchange_declare
self.channel = channel
self.client = client
self.connected_deferred.callback(None)
def amq_disconnected(self):
"""
This is the disconnected_callback that's passed to the L{AMQFactory}.
"""
def amq_failed(self, (connector, reason)):
"""
This is the failed_callback that's passed to the L{AMQFactory}.
"""
self.connected_deferred.errback(reason)
def queue_declare(self, queue, **kwargs):
"""
Keep track of the queue declaration, and forward to the real
queue_declare function.
"""
self.queues.add(queue)
return self.real_queue_declare(queue=queue, **kwargs)
def exchange_declare(self, exchange, **kwargs):
"""
Keep track of the exchange declaration, and forward to the real
exchange_declare function.
"""
self.exchanges.add(exchange)
return self.real_exchange_declare(exchange=exchange, **kwargs)
txlongpoll-0.3.1+bzr86.orig/txlongpoll/tests/__init__.py 0000644 0000000 0000000 00000000220 11730141124 021412 0 ustar 0000000 0000000 # Copyright 2005-2011 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
txlongpoll-0.3.1+bzr86.orig/txlongpoll/tests/test_client.py 0000644 0000000 0000000 00000004464 11730141124 022206 0 ustar 0000000 0000000 # Copyright 2005-2011 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
"""
Tests for C{AMQFactory}.
"""
from unittest import (
defaultTestLoader,
TestCase,
)
from testtools.deferredruntest import flush_logged_errors
from twisted.internet.defer import Deferred
from txamqp.protocol import AMQChannel
from txamqp.queue import Closed
from txamqp.spec import Spec
from txlongpoll.client import AMQFactory
from txlongpoll.testing.client import AMQTest
class AMQFactoryTest(TestCase):
def test_init(self):
factory = AMQFactory("guest", "secret", "localhost", lambda x: None,
lambda: None, lambda x: None)
self.assertEquals(factory.user, "guest")
self.assertEquals(factory.password, "secret")
self.assertEquals(factory.vhost, "localhost")
self.assertTrue(isinstance(factory.spec, Spec))
class AMQFactoryConnectedTest(AMQTest):
def test_connected_callback(self):
self.assertTrue(isinstance(self.channel, AMQChannel))
def test_disconnected_callback(self):
d = Deferred()
def disconnected():
d.callback(None)
self.factory.disconnected_callback = disconnected
self.connector.disconnect()
return d
def test_reconnection(self):
d = Deferred()
def connected((client, channel)):
self.assertTrue(isinstance(channel, AMQChannel))
self.assertIsNot(channel, self.channel)
d.callback(None)
self.factory.connected_callback = connected
self.factory.maxDelay = 0.01
self.connector.disconnect()
return d
class AMQClosingTest(AMQTest):
"""Tests the L{AMQFactory} when the connection is closing."""
count = 0
def amq_connected(self, (client, channel)):
super(AMQClosingTest, self).amq_connected((client, channel))
if not self.count:
self.count += 1
raise Closed()
def test_catch_closed(self):
"""
This test ensures that L{Closed} exception raised by C{amq_connected}
is swallowed by L{AMQFactory}.
"""
errors = flush_logged_errors()
self.assertEquals(len(errors), 0)
def test_suite():
return defaultTestLoader.loadTestsFromName(__name__)
txlongpoll-0.3.1+bzr86.orig/txlongpoll/tests/test_frontend.py 0000644 0000000 0000000 00000035006 11730141124 022543 0 ustar 0000000 0000000 # Copyright 2005-2011 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
from cStringIO import StringIO
import json
from unittest import defaultTestLoader
from testtools import TestCase
from testtools.deferredruntest import assert_fails_with
from twisted.internet import reactor
from twisted.internet.defer import (
Deferred,
fail,
inlineCallbacks,
succeed,
)
from twisted.internet.task import (
Clock,
deferLater,
)
from txamqp.content import Content
from txamqp.protocol import (
AMQChannel,
AMQClient,
)
from txamqp.queue import Empty
from txlongpoll.frontend import (
FrontEndAjax,
NotFound,
QueueManager,
)
from txlongpoll.testing.client import (
AMQTest,
QueueWrapper,
)
class QueueManagerTest(AMQTest):
prefix = None
tag_prefix = ""
queue_prefix = ""
def setUp(self):
self.clock = Clock()
self.manager = QueueManager(self.prefix)
return AMQTest.setUp(self)
def test_wb_connected(self):
"""
The C{connected} callback of L{QueueManager} sets the C{_client} and
C{_channel} attributes.
"""
d = self.manager.connected((self.client, self.channel))
self.assertTrue(isinstance(self.manager._client, AMQClient))
self.assertTrue(isinstance(self.manager._channel, AMQChannel))
self.assertIs(self.manager._client, self.client)
self.assertIs(self.manager._channel, self.channel)
return d
@inlineCallbacks
def test_get_message(self):
"""
C{get_message} returns the message exposed to a previously created
queue.
"""
yield self.manager.connected((self.client, self.channel))
yield self.channel.queue_declare(
queue=self.queue_prefix + "uuid1", auto_delete=True)
content = Content("some content")
yield self.channel.basic_publish(
routing_key=self.queue_prefix + "uuid1",
content=content)
message = yield self.manager.get_message("uuid1", "0")
self.assertEquals(message[0], "some content")
self.assertNotIn(self.tag_prefix + "uuid1.0", self.client.queues)
@inlineCallbacks
def test_reject_message(self):
"""
C{reject_message} puts back a message in the queue so that it's
available to subsequent C{get_message} calls.
"""
yield self.manager.connected((self.client, self.channel))
yield self.channel.queue_declare(
queue=self.queue_prefix + "uuid1")
content = Content("some content")
yield self.channel.basic_publish(
routing_key=self.queue_prefix + "uuid1",
content=content)
message, tag = yield self.manager.get_message("uuid1", "0")
yield self.manager.reject_message(tag)
message2, tag2 = yield self.manager.get_message("uuid1", "1")
self.assertEquals(message2, "some content")
@inlineCallbacks
def test_ack_message(self):
"""
C{ack_message} confirms the removal of a message from the queue, making
subsequent C{get_message} calls waiting for another message.
"""
yield self.manager.connected((self.client, self.channel))
yield self.channel.queue_declare(
queue=self.queue_prefix + "uuid1")
content = Content("some content")
yield self.channel.basic_publish(
routing_key=self.queue_prefix + "uuid1",
content=content)
message, tag = yield self.manager.get_message("uuid1", "0")
yield self.manager.ack_message(tag)
reply = yield self.client.queue(self.tag_prefix + "uuid1.1")
reply.clock = self.clock
event_queue = QueueWrapper(reply).event_queue
d = self.manager.get_message("uuid1", "1")
yield event_queue.get()
yield deferLater(reactor, 0, lambda: None)
self.clock.advance(self.manager.message_timeout + 1)
yield assert_fails_with(d, Empty)
@inlineCallbacks
def test_get_message_after_error(self):
"""
If an error occurs in C{get_message}, the transport is closed so that
we can query messages again.
"""
yield self.manager.connected((self.client, self.channel))
d = self.manager.get_message("uuid_unknown", "0")
yield assert_fails_with(d, NotFound)
self.assertTrue(self.channel.closed)
yield deferLater(reactor, 0.1, lambda: None)
self.assertTrue(self.client.transport.disconnected)
@inlineCallbacks
def test_get_message_during_error(self):
"""
If an error occurs in C{get_message}, other C{get_message} calls don't
fail, and are retried on reconnection instead.
"""
self.factory.initialDelay = 0.1
self.factory.resetDelay()
self.amq_disconnected = self.manager.disconnected
yield self.manager.connected((self.client, self.channel))
yield self.channel.queue_declare(
queue=self.queue_prefix + "uuid1")
content = Content("some content")
reply = yield self.client.queue(self.tag_prefix + "uuid1.0")
reply.clock = self.clock
event_queue = QueueWrapper(reply).event_queue
d1 = self.manager.get_message("uuid1", "0")
yield event_queue.get()
d2 = self.manager.get_message("uuid_unknown", "0")
yield assert_fails_with(d2, NotFound)
self.assertTrue(self.channel.closed)
self.connected_deferred = Deferred()
yield self.connected_deferred
yield self.manager.connected((self.client, self.channel))
yield self.channel.basic_publish(
routing_key=self.queue_prefix + "uuid1",
content=content)
message = yield d1
self.assertEquals(message[0], "some content")
@inlineCallbacks
def test_get_message_timeout(self):
"""
C{get_message} timeouts after a certain amount of time if no message
arrived on the queue.
"""
yield self.manager.connected((self.client, self.channel))
yield self.channel.queue_declare(
queue=self.queue_prefix + "uuid1")
reply = yield self.client.queue(self.tag_prefix + "uuid1.0")
reply.clock = self.clock
event_queue = QueueWrapper(reply).event_queue
d = self.manager.get_message("uuid1", "0")
yield event_queue.get()
yield deferLater(reactor, 0, lambda: None)
self.clock.advance(self.manager.message_timeout + 1)
yield assert_fails_with(d, Empty)
self.assertNotIn(self.tag_prefix + "uuid1.0", self.client.queues)
@inlineCallbacks
def test_wb_timeout_race_condition(self):
"""
If a message is received between the time the queue gets a timeout and
C{get_message} cancels the subscription, the message is recovered and
returned by C{get_message}.
"""
yield self.manager.connected((self.client, self.channel))
yield self.channel.queue_declare(
queue=self.queue_prefix + "uuid1")
content = Content("some content")
reply = yield self.client.queue(self.tag_prefix + "uuid1.0")
reply.clock = self.clock
event_queue = QueueWrapper(reply).event_queue
old_timeout = reply._timeout
def timeout(deferred):
self.channel.basic_publish(
routing_key=self.queue_prefix + "uuid1",
content=content)
old_timeout(deferred)
reply._timeout = timeout
d = self.manager.get_message("uuid1", "0")
yield event_queue.get()
yield deferLater(reactor, 0, lambda: None)
self.clock.advance(self.manager.message_timeout + 1)
message = yield d
self.assertEquals(message[0], "some content")
@inlineCallbacks
def test_retry_after_timeout(self):
"""
If a timeout happens, one can retry to consume message from the queue
later on.
"""
yield self.manager.connected((self.client, self.channel))
yield self.channel.queue_declare(
queue=self.queue_prefix + "uuid1")
reply = yield self.client.queue(self.tag_prefix + "uuid1.0")
reply.clock = self.clock
event_queue = QueueWrapper(reply).event_queue
d1 = self.manager.get_message("uuid1", "0")
yield event_queue.get()
yield deferLater(reactor, 0, lambda: None)
self.clock.advance(self.manager.message_timeout + 1)
yield assert_fails_with(d1, Empty)
# Let's wrap the queue again
reply = yield self.client.queue(self.tag_prefix + "uuid1.1")
reply.clock = self.clock
event_queue = QueueWrapper(reply).event_queue
d2 = self.manager.get_message("uuid1", "1")
yield event_queue.get()
yield deferLater(reactor, 0, lambda: None)
self.clock.advance(self.manager.message_timeout + 1)
yield assert_fails_with(d2, Empty)
class QueueManagerTestWithPrefix(QueueManagerTest):
prefix = "test"
tag_prefix = "test.notifications-tag."
queue_prefix = "test.notifications-queue."
class FakeMessageQueue(object):
def __init__(self):
self.messages = {}
self._prefix = "test"
def get_message(self, uuid, sequence):
message = self.messages[uuid]
if isinstance(message, Exception):
return fail(message)
else:
return succeed((message, "tag"))
def ack_message(self, tag):
pass
class FakeRequest(object):
def __init__(self, args):
self.args = args
self.written = StringIO()
self.finished = False
self.code = 200
self.notifications = []
def write(self, content):
assert type(content) is str, "Only strings should be written"
self.written.write(content)
def finish(self):
self.finished = True
for deferred in self.notifications:
deferred.callback(None)
def setResponseCode(self, code):
self.code = code
def notifyFinish(self):
deferred = Deferred()
self.notifications.append(deferred)
return deferred
def setHeader(self, key, value):
pass
class FrontEndAjaxTest(TestCase):
"""
Tests for L{FrontEndAjax}.
"""
def setUp(self):
super(FrontEndAjaxTest, self).setUp()
self.message_queue = FakeMessageQueue()
self.ajax = FrontEndAjax(self.message_queue)
def test_render_success(self):
"""
L{FrontEndAjax.render} displays the message got via get_message after
getting the uuid from the request.
"""
body = json.dumps({"result": "some content"})
self.message_queue.messages["uuid1"] = body
request = FakeRequest({"uuid": ["uuid1"], "sequence": ["0"]})
self.ajax.render(request)
self.assertEquals(request.written.getvalue(), body)
def test_render_ignore_self_messages(self):
"""
L{FrontEndAjax.render} ignores notifications for generated by the same
page, to prevent useless messages.
"""
body1 = json.dumps(
{"result": "some content", "original-uuid": "uuid1"})
body2 = json.dumps({"result": "some other content"})
messages = [body1, body2]
def get_message(uuid, sequence):
return succeed((messages.pop(0), "tag"))
self.message_queue.get_message = get_message
request = FakeRequest({"uuid": ["uuid1"], "sequence": ["0"]})
self.ajax.render(request)
self.assertEquals(request.written.getvalue(), body2)
def test_render_catch_error(self):
"""
L{FrontEndAjax.render} checks the content of the message to see if it
contains an error, and returns that error message along with a 500 code
if it's the case.
"""
body = json.dumps({"error": u"oops a problem"})
self.message_queue.messages["uuid1"] = body
request = FakeRequest({"uuid": ["uuid1"], "sequence": ["0"]})
self.ajax.render(request)
self.assertEquals(request.written.getvalue(), body)
self.assertEquals(request.code, 400)
def test_render_error(self):
"""
L{FrontEndAjax.render} displays an error if C{get_message} raises an
exception.
"""
self.message_queue.messages["uuid1"] = ValueError("Not there")
request = FakeRequest({"uuid": ["uuid1"], "sequence": ["0"]})
self.ajax.render(request)
self.assertEquals(request.written.getvalue(), "Not there")
self.assertEquals(request.code, 500)
def test_render_monitor(self):
"""
L{FrontEndAjax.render} returns a static string if no parameters are
passed for monitoring purposes.
"""
request = FakeRequest({})
data = self.ajax.render(request)
self.assertEqual("Async frontend for test", data)
self.assertEqual("", request.written.getvalue())
self.assertEqual(200, request.code)
def test_render_no_uuid(self):
"""
L{FrontEndAjax.render} displays an error if no uuid is passed to the
request.
"""
request = FakeRequest({"sequence": ["0"]})
data = self.ajax.render(request)
self.assertEqual("Invalid request", data)
self.assertEqual("", request.written.getvalue())
self.assertEqual(400, request.code)
def test_render_no_sequence(self):
"""
L{FrontEndAjax.render} displays an error if no sequence is passed to
the request.
"""
request = FakeRequest({"uuid": ["uuid1"]})
data = self.ajax.render(request)
self.assertEqual("Invalid request", data)
self.assertEqual("", request.written.getvalue())
self.assertEqual(400, request.code)
def test_render_empty_uuid(self):
"""
L{FrontEndAjax.render} displays an error if the given UUID is empty.
"""
request = FakeRequest({"uuid": [""], "sequence": ["0"]})
data = self.ajax.render(request)
self.assertEqual("Invalid request", data)
self.assertEqual("", request.written.getvalue())
self.assertEqual(400, request.code)
def test_render_empty_sequence(self):
"""
L{FrontEndAjax.render} displays an error if the given sequence is
empty.
"""
request = FakeRequest({"uuid": ["uuid"], "sequence": [""]})
data = self.ajax.render(request)
self.assertEqual("Invalid request", data)
self.assertEqual("", request.written.getvalue())
self.assertEqual(400, request.code)
def test_suite():
return defaultTestLoader.loadTestsFromName(__name__)
txlongpoll-0.3.1+bzr86.orig/txlongpoll/tests/test_plugin.py 0000644 0000000 0000000 00000010030 11730141124 022210 0 ustar 0000000 0000000 # Copyright 2005-2011 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
from functools import partial
import os
from unittest import defaultTestLoader
from fixtures import TempDir
from formencode import Invalid
from subunit import IsolatedTestCase
from testtools import TestCase
from testtools.matchers import (
MatchesException,
Raises,
)
from twisted.application.service import MultiService
from txlongpoll.plugin import (
AMQServiceMaker,
Config,
Options,
)
class TestConfig(TestCase):
"""Tests for `txlongpoll.plugin.Options`."""
def test_defaults(self):
expected = {
'broker': {
'host': 'localhost',
'password': 'guest',
'port': 5672,
'username': "guest",
'vhost': u'/',
},
'frontend': {
'port': 8001,
'prefix': None,
},
'logfile': 'txlongpoll.log',
'oops': {
'directory': '',
'reporter': 'LONGPOLL',
},
}
observed = Config.to_python({})
self.assertEqual(expected, observed)
def test_parse(self):
# Configuration can be parsed from a snippet of YAML.
observed = Config.parse(b'logfile: "/some/where.log"')
self.assertEqual("/some/where.log", observed["logfile"])
def test_load(self):
# Configuration can be loaded and parsed from a file.
filename = os.path.join(
self.useFixture(TempDir()).path, "config.yaml")
with open(filename, "wb") as stream:
stream.write(b'logfile: "/some/where.log"')
observed = Config.load(filename)
self.assertEqual("/some/where.log", observed["logfile"])
def test_load_example(self):
# The example configuration can be loaded and validated.
filename = os.path.join(
os.path.dirname(__file__), os.pardir,
os.pardir, "etc", "txlongpoll.yaml")
Config.load(filename)
def check_exception(self, config, message):
# Check that a UsageError is raised when parsing options.
self.assertThat(
partial(Config.to_python, config),
Raises(MatchesException(Invalid, message)))
def test_option_broker_port_integer(self):
self.check_exception(
{"broker": {"port": "bob"}},
"broker: port: Please enter an integer value")
def test_option_frontend_port_integer(self):
self.check_exception(
{"frontend": {"port": "bob"}},
"frontend: port: Please enter an integer value")
class TestOptions(TestCase):
"""Tests for `txlongpoll.plugin.Options`."""
def test_defaults(self):
options = Options()
expected = {"config-file": "etc/txlongpoll.yaml"}
self.assertEqual(expected, options.defaults)
def test_parse_minimal_options(self):
options = Options()
# The minimal set of options that must be provided.
arguments = []
options.parseOptions(arguments) # No error.
class TestAMQServiceMaker(IsolatedTestCase, TestCase):
"""Tests for `txlongpoll.plugin.AMQServiceMaker`."""
def test_init(self):
service_maker = AMQServiceMaker("Harry", "Hill")
self.assertEqual("Harry", service_maker.tapname)
self.assertEqual("Hill", service_maker.description)
def test_makeService(self):
options = Options()
service_maker = AMQServiceMaker("Harry", "Hill")
service = service_maker.makeService(options)
self.assertIsInstance(service, MultiService)
self.assertEqual(4, len(service.services))
self.assertSequenceEqual(
["amqp", "frontend", "log", "oops"],
sorted(service.namedServices))
self.assertEqual(
len(service.namedServices), len(service.services),
"Not all services are named.")
def test_suite():
return defaultTestLoader.loadTestsFromName(__name__)
txlongpoll-0.3.1+bzr86.orig/txlongpoll/tests/test_services.py 0000644 0000000 0000000 00000010312 11730141124 022540 0 ustar 0000000 0000000 # Copyright 2012 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
"""Tests for `txlongpoll.services`."""
from __future__ import (
print_function,
unicode_literals,
)
__metaclass__ = type
__all__ = []
import os
import signal
import sys
from fixtures import TempDir
from oops_twisted import OOPSObserver
from txlongpoll.services import (
LogService,
OOPSService,
)
from testtools import TestCase
from testtools.content import content_from_file
from testtools.deferredruntest import AsynchronousDeferredRunTest
from twisted.application.service import MultiService
from twisted.python.log import (
FileLogObserver,
theLogPublisher,
)
from twisted.python.logfile import LogFile
class TestServicesBase:
run_tests_with = AsynchronousDeferredRunTest.make_factory(timeout=5)
def setUp(self):
super(TestServicesBase, self).setUp()
self.observers = theLogPublisher.observers[:]
self.services = MultiService()
self.services.privilegedStartService()
self.services.startService()
def tearDown(self):
super(TestServicesBase, self).tearDown()
d = self.services.stopService()
# The log file must be read in right after services have stopped,
# before the temporary directory where the log lives is removed.
d.addBoth(lambda ignore: self.addDetailFromLog())
d.addBoth(lambda ignore: self.assertNoObserversLeftBehind())
return d
def addDetailFromLog(self):
content = content_from_file(self.log_filename, buffer_now=True)
self.addDetail("log", content)
def assertNoObserversLeftBehind(self):
self.assertEqual(self.observers, theLogPublisher.observers)
class TestLogService(TestServicesBase, TestCase):
"""Tests for `txlongpoll.services.LogService`."""
def test_log_to_stdout(self):
log_service = LogService("-")
log_service.setServiceParent(self.services)
self.assertIsInstance(log_service.observer, FileLogObserver)
self.assertEqual("-", log_service.filename)
self.assertEqual(sys.stdout, log_service.logfile)
# The SIGUSR1 signal handler is untouched.
self.assertEqual(
signal.getsignal(signal.SIGUSR1),
signal.SIG_DFL)
def test_log_to_file(self):
tempdir = self.useFixture(TempDir()).path
log_filename = os.path.join(tempdir, "test.log")
log_service = LogService(log_filename)
log_service.setServiceParent(self.services)
self.assertIsInstance(log_service.observer, FileLogObserver)
self.assertEqual(log_filename, log_service.filename)
self.assertIsInstance(log_service.logfile, LogFile)
self.assertEqual(log_filename, log_service.logfile.path)
# The SIGUSR1 signal handler is set.
self.assertEqual(
signal.getsignal(signal.SIGUSR1),
log_service._signal_handler)
class TestOOPSService(TestServicesBase, TestCase):
"""Tests for `txlongpoll.services.OOPSService`."""
def setUp(self):
super(TestOOPSService, self).setUp()
# OOPSService relies upon LogService.
self.tempdir = self.useFixture(TempDir()).path
self.log_filename = os.path.join(self.tempdir, "test.log")
self.log_service = LogService(self.log_filename)
self.log_service.setServiceParent(self.services)
def test_minimal(self):
oops_service = OOPSService(self.log_service, None, None)
oops_service.setServiceParent(self.services)
observer = oops_service.observer
self.assertIsInstance(observer, OOPSObserver)
self.assertEqual([], observer.config.publishers)
self.assertEqual({}, observer.config.template)
def test_with_all_params(self):
oops_dir = os.path.join(self.tempdir, "oops")
oops_service = OOPSService(self.log_service, oops_dir, "Sidebottom")
oops_service.setServiceParent(self.services)
observer = oops_service.observer
self.assertIsInstance(observer, OOPSObserver)
self.assertEqual(1, len(observer.config.publishers))
self.assertEqual(
{"reporter": "Sidebottom"},
observer.config.template)